mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-03 15:21:17 -05:00
Merge main into fix/asset-export-narrow-layout
This commit is contained in:
@@ -123,7 +123,9 @@
|
||||
}
|
||||
},
|
||||
"max_artifact_bytes": 2147483648,
|
||||
"automatic_signer_actors": [],
|
||||
"automatic_signer_actors": [
|
||||
"github-actions[bot]"
|
||||
],
|
||||
"platforms": {
|
||||
"windows-x86_64": {
|
||||
"unsigned_artifact_name": "nightly-unsigned-windows-x86_64",
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
"""Check a real installed release RPM and exercise the GUI control channel."""
|
||||
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import secrets
|
||||
import socket
|
||||
import subprocess
|
||||
import time
|
||||
import tempfile
|
||||
|
||||
|
||||
def run_smoke(results):
|
||||
requirements = (results / "rpm-requires.txt").read_text()
|
||||
for capability in (
|
||||
"libc.so.6()(64bit)",
|
||||
"libm.so.6(GLIBC_2.35)(64bit)",
|
||||
"libgcc_s.so.1()(64bit)",
|
||||
"libxkbcommon.so.0()(64bit)",
|
||||
"(libvulkan.so.1()(64bit) or libEGL.so.1()(64bit))",
|
||||
):
|
||||
if capability not in requirements.splitlines():
|
||||
raise RuntimeError(f"Missing RPM requirement: {capability}")
|
||||
|
||||
version = subprocess.check_output(["vectorcraft-cli", "--version"], text=True)
|
||||
(results / "cli-version.txt").write_text(version)
|
||||
# Original fixture authored for this package smoke test; no external artwork.
|
||||
fixture = results / "original-smoke.svg"
|
||||
fixture.write_text('<svg xmlns="http://www.w3.org/2000/svg" width="200" height="140">'
|
||||
'<rect x="20" y="20" width="160" height="100" rx="12" fill="#2463eb"/>'
|
||||
'<circle cx="100" cy="70" r="30" fill="#ffcc33"/></svg>')
|
||||
token = secrets.token_hex(32)
|
||||
with tempfile.TemporaryDirectory(prefix="vectorcraft-runtime-") as runtime, (results / "gui.log").open("w") as log:
|
||||
env = dict(os.environ, VECTORCRAFT_NO_PREFS="1", XDG_RUNTIME_DIR=runtime,
|
||||
VECTORCRAFT_CONTROL_TOKEN=token)
|
||||
app = subprocess.Popen([
|
||||
"vectorcraft", "--control", "32180", "--automation-read-root", str(results),
|
||||
"--automation-write-root", str(results), str(fixture),
|
||||
], stdout=log, stderr=subprocess.STDOUT, env=env)
|
||||
try:
|
||||
deadline = time.monotonic() + 90
|
||||
while True:
|
||||
if app.poll() is not None:
|
||||
raise RuntimeError(f"GUI exited during startup: {app.returncode}")
|
||||
try:
|
||||
channel = socket.create_connection(("127.0.0.1", 32180), timeout=5)
|
||||
break
|
||||
except OSError:
|
||||
if time.monotonic() >= deadline:
|
||||
raise RuntimeError("GUI control channel did not become ready") from None
|
||||
time.sleep(1)
|
||||
channel.settimeout(30)
|
||||
with channel, channel.makefile("rwb") as stream:
|
||||
for request_id, method, params in (
|
||||
(0, "auth", {"token": token}),
|
||||
(1, "ui.inspect", {}),
|
||||
):
|
||||
stream.write((json.dumps(dict(id=request_id, method=method, params=params)) + "\n").encode())
|
||||
stream.flush()
|
||||
response = json.loads(stream.readline())
|
||||
(results / f"{method}.json").write_text(json.dumps(response, indent=2))
|
||||
if response.get("id") != request_id or response.get("ok") is not True:
|
||||
raise RuntimeError(f"GUI request failed: {method}")
|
||||
finally:
|
||||
app.terminate()
|
||||
try:
|
||||
app.wait(timeout=10)
|
||||
except subprocess.TimeoutExpired:
|
||||
app.kill()
|
||||
app.wait()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_smoke(Path("/results"))
|
||||
@@ -0,0 +1,116 @@
|
||||
"""Exercise failures that an installed-package happy-path check cannot reproduce."""
|
||||
import importlib.util
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
spec = importlib.util.spec_from_file_location("rpm_smoke", Path(__file__).parents[1] / "release-rpm-smoke.py")
|
||||
smoke = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(smoke)
|
||||
|
||||
|
||||
class SmokeLifecycleTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.folder = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.folder.cleanup)
|
||||
self.results = Path(self.folder.name)
|
||||
(self.results / "rpm-requires.txt").write_text("\n".join([
|
||||
"libc.so.6()(64bit)", "libm.so.6(GLIBC_2.35)(64bit)",
|
||||
"libgcc_s.so.1()(64bit)", "libxkbcommon.so.0()(64bit)",
|
||||
"(libvulkan.so.1()(64bit) or libEGL.so.1()(64bit))",
|
||||
]))
|
||||
self.app = MagicMock()
|
||||
self.app.poll.return_value = None
|
||||
self.channel = MagicMock()
|
||||
self.stream = self.channel.makefile.return_value.__enter__.return_value
|
||||
self.stream.readline.side_effect = [
|
||||
b'{"id":0,"ok":true}\n', b'{"id":1,"ok":true,"result":{"window":"fixture"}}\n',
|
||||
]
|
||||
self.runtime = None
|
||||
|
||||
def launch(*args, **kwargs):
|
||||
self.runtime = Path(kwargs["env"]["XDG_RUNTIME_DIR"])
|
||||
self.assertTrue(self.runtime.is_dir())
|
||||
return self.app
|
||||
|
||||
self.launch = self.start_patch(smoke.subprocess, "Popen", side_effect=launch)
|
||||
self.start_patch(smoke.subprocess, "check_output", return_value="vectorcraft-cli 0.25.0\n")
|
||||
self.connect = self.start_patch(smoke.socket, "create_connection", return_value=self.channel)
|
||||
self.start_patch(smoke.time, "sleep")
|
||||
|
||||
def start_patch(self, owner, name, **kwargs):
|
||||
patcher = patch.object(owner, name, **kwargs)
|
||||
result = patcher.start()
|
||||
self.addCleanup(patcher.stop)
|
||||
return result
|
||||
|
||||
def assert_cleaned_up(self):
|
||||
self.app.terminate.assert_called_once()
|
||||
self.assertFalse(self.runtime.exists())
|
||||
|
||||
def test_success_records_inspection_and_removes_private_runtime(self):
|
||||
smoke.run_smoke(self.results)
|
||||
report = json.loads((self.results / "ui.inspect.json").read_text())
|
||||
self.assertEqual(report["result"], {"window": "fixture"})
|
||||
requests = [json.loads(call.args[0]) for call in self.stream.write.call_args_list]
|
||||
self.assertEqual(requests[0]["method"], "auth")
|
||||
self.assertEqual(requests[0]["params"]["token"], self.launch.call_args.kwargs["env"]["VECTORCRAFT_CONTROL_TOKEN"])
|
||||
self.assert_cleaned_up()
|
||||
|
||||
def test_missing_runtime_dependency_prevents_launch(self):
|
||||
(self.results / "rpm-requires.txt").write_text("")
|
||||
with self.assertRaisesRegex(RuntimeError, "Missing RPM requirement"):
|
||||
smoke.run_smoke(self.results)
|
||||
self.launch.assert_not_called()
|
||||
|
||||
def test_child_exit_during_startup_is_a_failure(self):
|
||||
self.app.poll.return_value = 1
|
||||
self.app.returncode = 1
|
||||
with self.assertRaisesRegex(RuntimeError, "exited during startup"):
|
||||
smoke.run_smoke(self.results)
|
||||
self.assert_cleaned_up()
|
||||
|
||||
def test_connection_is_retried_until_ready(self):
|
||||
self.connect.side_effect = [OSError("not ready"), self.channel]
|
||||
smoke.run_smoke(self.results)
|
||||
self.assertEqual(self.connect.call_count, 2)
|
||||
self.assert_cleaned_up()
|
||||
|
||||
def test_startup_timeout_stops_child(self):
|
||||
self.connect.side_effect = OSError("not ready")
|
||||
self.start_patch(smoke.time, "monotonic", side_effect=[0, 91])
|
||||
with self.assertRaisesRegex(RuntimeError, "did not become ready"):
|
||||
smoke.run_smoke(self.results)
|
||||
self.assert_cleaned_up()
|
||||
|
||||
def test_auth_refusal_prevents_inspection(self):
|
||||
self.stream.readline.side_effect = [b'{"id":0,"ok":false}\n']
|
||||
with self.assertRaisesRegex(RuntimeError, "request failed: auth"):
|
||||
smoke.run_smoke(self.results)
|
||||
self.assertFalse((self.results / "ui.inspect.json").exists())
|
||||
self.assert_cleaned_up()
|
||||
|
||||
def test_response_for_another_request_is_rejected(self):
|
||||
self.stream.readline.side_effect = [b'{"id":0,"ok":true}\n', b'{"id":99,"ok":true}\n']
|
||||
with self.assertRaisesRegex(RuntimeError, "request failed: ui.inspect"):
|
||||
smoke.run_smoke(self.results)
|
||||
self.assert_cleaned_up()
|
||||
|
||||
def test_malformed_response_still_stops_child(self):
|
||||
self.stream.readline.side_effect = [b'not json\n']
|
||||
with self.assertRaises(json.JSONDecodeError):
|
||||
smoke.run_smoke(self.results)
|
||||
self.assert_cleaned_up()
|
||||
|
||||
def test_unresponsive_child_is_killed_after_termination_timeout(self):
|
||||
self.app.wait.side_effect = [subprocess.TimeoutExpired("vectorcraft", 10), 0]
|
||||
smoke.run_smoke(self.results)
|
||||
self.app.kill.assert_called_once()
|
||||
self.assert_cleaned_up()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -11,9 +11,9 @@ permissions: {}
|
||||
|
||||
jobs:
|
||||
dispatch:
|
||||
# SOURCE PREPARATION: literal off until immutable shared tooling and policy qualification.
|
||||
# Enabled for automated scheduled producer completions on main.
|
||||
if: >-
|
||||
false && github.repository == 'storytold/vectorcraft' &&
|
||||
github.repository == 'storytold/vectorcraft' &&
|
||||
github.event_name == 'workflow_run'
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
name: VectorCraft unsigned nightly
|
||||
|
||||
# Enabled for supervised manual runs by the reviewed manual actor only; no schedule yet.
|
||||
# A later explicit opt-in may add a cadence (and turn on nightly-dispatch.yml with it).
|
||||
# Automated daily nightly builds at 06:30 UTC, plus supervised manual runs by reviewed manual actors.
|
||||
on:
|
||||
schedule:
|
||||
- cron: '30 6 * * *'
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
name: Release RPM smoke
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
run-id:
|
||||
description: Release run containing both RPM artifacts (empty selects the latest available pair)
|
||||
type: string
|
||||
default: ""
|
||||
pull_request:
|
||||
paths:
|
||||
- .github/workflows/release-rpm-smoke.yml
|
||||
- .github/scripts/release-rpm-smoke.py
|
||||
- .github/scripts/tests/test_release_rpm_smoke.py
|
||||
|
||||
permissions: {}
|
||||
|
||||
jobs:
|
||||
source:
|
||||
permissions:
|
||||
actions: read
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 5
|
||||
outputs:
|
||||
run-id: ${{ steps.source.outputs.run-id }}
|
||||
steps:
|
||||
- id: source
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
RUN_ID: ${{ inputs.run-id }}
|
||||
run: |
|
||||
candidates="$RUN_ID"
|
||||
if [ -z "$candidates" ]; then
|
||||
candidates=$(gh run list --repo "$GITHUB_REPOSITORY" --workflow release.yml --branch release --limit 10 --json databaseId --jq '.[].databaseId')
|
||||
fi
|
||||
for candidate in $candidates; do
|
||||
[[ "$candidate" =~ ^[0-9]+$ ]]
|
||||
names=$(gh api "repos/$GITHUB_REPOSITORY/actions/runs/$candidate/artifacts?per_page=100" --jq '.artifacts[] | select(.expired == false) | .name')
|
||||
if grep -Fxq release-linux-x86_64 <<< "$names" && grep -Fxq release-linux-aarch64 <<< "$names"; then
|
||||
printf 'run-id=%s\n' "$candidate" >> "$GITHUB_OUTPUT"
|
||||
exit 0
|
||||
fi
|
||||
done
|
||||
echo '::error::No release run has both Linux package artifacts available'
|
||||
exit 1
|
||||
smoke:
|
||||
permissions:
|
||||
contents: read
|
||||
actions: read
|
||||
needs: source
|
||||
timeout-minutes: 25
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
platform:
|
||||
- {arch: x86_64, runner: ubuntu-24.04}
|
||||
- {arch: aarch64, runner: ubuntu-24.04-arm}
|
||||
distro: [fedora, rocky, opensuse]
|
||||
runs-on: ${{ matrix.platform.runner }}
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: Download the release packages
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
RUN_ID: ${{ needs.source.outputs.run-id }}
|
||||
ARCH: ${{ matrix.platform.arch }}
|
||||
run: |
|
||||
[[ "$RUN_ID" =~ ^[0-9]+$ ]]
|
||||
mkdir -p packages results
|
||||
gh run view "$RUN_ID" --json headSha,url > results/source.json
|
||||
gh run download "$RUN_ID" --name "release-linux-$ARCH" --dir packages
|
||||
sha256sum packages/*.rpm > results/rpm-sha256.txt
|
||||
- name: Install and start the RPM on the target distribution
|
||||
env:
|
||||
DISTRO: ${{ matrix.distro }}
|
||||
run: |
|
||||
sudo apt-get update -qq
|
||||
sudo apt-get install -y xvfb
|
||||
Xvfb :99 -screen 0 1440x900x24 -ac -nolisten tcp > results/xvfb.log 2>&1 &
|
||||
for _attempt in {1..20}; do
|
||||
[ -S /tmp/.X11-unix/X99 ] && break
|
||||
sleep 1
|
||||
done
|
||||
[ -S /tmp/.X11-unix/X99 ]
|
||||
case "$DISTRO" in
|
||||
fedora) image=fedora:latest ;;
|
||||
rocky) image=rockylinux:10 ;;
|
||||
opensuse) image=opensuse/tumbleweed:latest ;;
|
||||
esac
|
||||
docker pull "$image"
|
||||
docker image inspect "$image" --format '{{json .RepoDigests}}' > results/container-digest.json
|
||||
docker run --rm --ipc=host --name rpm-smoke -e DISTRO -e DISPLAY=:99 -e LIBGL_ALWAYS_SOFTWARE=1 \
|
||||
-v /tmp/.X11-unix:/tmp/.X11-unix:ro -v "$PWD/packages:/packages:ro" \
|
||||
-v "$PWD/results:/results" -v "$PWD/.github/scripts:/checks:ro" "$image" bash -euc '
|
||||
cat /etc/os-release > /results/os-release.txt
|
||||
if [ "$DISTRO" = opensuse ]; then
|
||||
zypper --non-interactive refresh
|
||||
zypper --non-interactive install python3 Mesa-dri Mesa-libEGL1 libX11-6 libXcursor1 libXi6 libXrandr2 libxkbcommon0 libxkbcommon-x11-0
|
||||
zypper --non-interactive --no-gpg-checks install /packages/*.rpm
|
||||
else
|
||||
dnf -y install python3 mesa-dri-drivers mesa-libEGL libX11 libXcursor libXi libXrandr libxkbcommon libxkbcommon-x11
|
||||
dnf -y --nogpgcheck install /packages/*.rpm
|
||||
fi
|
||||
rpm -qp --requires /packages/*.rpm > /results/rpm-requires.txt
|
||||
python3 /checks/release-rpm-smoke.py
|
||||
'
|
||||
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9
|
||||
if: always()
|
||||
with:
|
||||
name: rpm-smoke-${{ matrix.distro }}-${{ matrix.platform.arch }}
|
||||
path: results/
|
||||
if-no-files-found: error
|
||||
@@ -43,6 +43,7 @@ jobs:
|
||||
app-name: vectorcraft
|
||||
app-title: VectorCraft
|
||||
macos-runner: macos-15
|
||||
macos-split-build: true
|
||||
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
|
||||
web-craft-fonts: true
|
||||
version: ${{ inputs.version }}
|
||||
|
||||
@@ -21,4 +21,7 @@ jobs:
|
||||
# The reusable workflow defaults build-jobs to 2 so a cold instrumented
|
||||
# archive stays within hosted-runner memory (craft-common-actions#333).
|
||||
uses: storytold/craft-common-actions/.github/workflows/sonarcloud.yml@main
|
||||
with:
|
||||
python-coverage-source: .github/scripts
|
||||
python-coverage-script: .github/scripts/tests/test_release_rpm_smoke.py
|
||||
secrets: inherit
|
||||
|
||||
Generated
+189
-193
File diff suppressed because it is too large
Load Diff
+52
-57
@@ -4,56 +4,57 @@ members = ["crates/*", "apps/*", "xtask"]
|
||||
default-members = ["crates/*", "apps/vectorcraft", "apps/vectorcraft-cli", "xtask"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.25.0"
|
||||
version = "0.25.1"
|
||||
edition = "2024"
|
||||
license = "MIT OR Apache-2.0"
|
||||
rust-version = "1.95"
|
||||
repository = "https://github.com/storytold/vectorcraft"
|
||||
|
||||
[workspace.dependencies]
|
||||
craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735", default-features = false, features = ["interpret", "write"] }
|
||||
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d", default-features = false, features = ["interpret", "write"] }
|
||||
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
|
||||
craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
|
||||
# Language packs: the Craft apps' shared font store installs them (#4936).
|
||||
craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
|
||||
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
|
||||
# The `.vectorcraft` envelope: its members, version, embedded images and the data after the JSON.
|
||||
craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
|
||||
craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
|
||||
# `.pcraft` documents: their manifest, full-size composite, preview, layer pixels and ICC profile.
|
||||
craft-doc = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735", features = ["pcraft-pixels"] }
|
||||
craft-doc = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d", features = ["pcraft-pixels"] }
|
||||
# Native Affinity documents (craft-libs#914).
|
||||
craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
|
||||
# Bounded CDR (v1-v27) and CMX (32-bit) reader (craft-libs#778).
|
||||
craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
|
||||
# SVG parsing, limits, SVGZ and writer (craft-libs#778).
|
||||
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735", features = ["tree"] }
|
||||
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d", features = ["tree"] }
|
||||
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
|
||||
# EPS container, previews, ASCII85 and DSC comments (craft-libs#778).
|
||||
craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
|
||||
# DXF tags, reader and writer (craft-libs#778, #926, #927).
|
||||
craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
|
||||
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
|
||||
# WMF, EMF and EMF+ reader (craft-libs#778).
|
||||
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735", default-features = false, features = ["read", "write"] }
|
||||
craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
|
||||
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
|
||||
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
|
||||
craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
|
||||
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
|
||||
craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d", default-features = false, features = ["read", "write"] }
|
||||
craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
|
||||
craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
|
||||
craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
|
||||
craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
|
||||
# The framework facade (`craft::ui`, `craft::settings`, `craft::platform`, ...). No default features: each crate names
|
||||
# the members it imports.
|
||||
craft = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
craft = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
|
||||
# Below the egui layer, so not through the facade: the colour harmony rules and their settings (craft-color-ui
|
||||
# without its `ui` feature), the colour type they work in, and the craft-fonts tables the text crate's build writes.
|
||||
craft-color-ui = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
craft-color-ui = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
|
||||
craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
|
||||
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
|
||||
# Nightly profile isolation, launch protocol, and security fence.
|
||||
craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
|
||||
# internal
|
||||
vectorcraft-geom = { path = "crates/geom" }
|
||||
vectorcraft-color = { path = "crates/color" }
|
||||
@@ -89,7 +90,6 @@ vectorcraft-apischema = { path = "crates/apischema" }
|
||||
|
||||
# foundation
|
||||
kurbo = { version = "0.13", features = ["serde"] }
|
||||
peniko = "0.6"
|
||||
thiserror = "2"
|
||||
serde = { version = "1", features = ["derive", "rc"] }
|
||||
serde_json = { version = "1", features = ["float_roundtrip"] }
|
||||
@@ -159,10 +159,8 @@ egui = "0.37"
|
||||
egui_extras = { version = "0.37", default-features = false, features = ["svg"] }
|
||||
eframe = { version = "0.37", default-features = false }
|
||||
egui_kittest = "0.37"
|
||||
rfd = "0.17"
|
||||
arboard = { version = "3.6", default-features = false }
|
||||
clipboard-win = "5.4"
|
||||
webbrowser = "1"
|
||||
|
||||
[workspace.lints.rust]
|
||||
unsafe_code = "deny"
|
||||
@@ -196,25 +194,22 @@ lto = "thin"
|
||||
codegen-units = 1
|
||||
|
||||
[patch.crates-io]
|
||||
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
krilla = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
emath = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
epaint = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
egui = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
eframe = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" }
|
||||
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
|
||||
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
|
||||
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
|
||||
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
|
||||
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
|
||||
krilla = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
|
||||
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
|
||||
emath = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
|
||||
epaint = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
|
||||
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
|
||||
egui = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
|
||||
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
|
||||
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
|
||||
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
|
||||
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
|
||||
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
|
||||
eframe = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
|
||||
winit = { git = "https://github.com/storytold/winit.git", rev = "0dfcec0eb62fda5904137a63a6dd0c3d83295f45" }
|
||||
|
||||
@@ -163,6 +163,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
|
||||
- 2026-11-01: Expand Dashes into Paths joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): each selected path's dashed stroke becomes separate open paths, one per dash, laid out exactly as the stroke draws them (pattern, offset, Align Dashes to Corners and Path Ends), each keeping the stroke with the dashes off, so the gaps are real gaps for cutters and plotters, as one undo step (`addon.pathtools.expandDashes`, #4922).
|
||||
- 2026-11-01: Randomize Opacity joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): each selected object gets its own opacity at random between a minimum and a maximum percent, with a seed that repeats the result, as one undo step (`addon.arrange.randomizeOpacity`, #4925).
|
||||
- 2026-11-01: Sort Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects are sorted by width, height, area, position, opacity or stacking order (small to large, large to small or at random) and take another of those in that order, trading their values or stepping them evenly, as one undo step (`addon.arrange.sort`, #4917).
|
||||
- 2026-11-29: Match Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the other selected objects take the width, the height or both, the bounding-box angle and the stacking place of the key object, or of the top or the bottom selected object, about a reference point, with Preview, as one undo step (`addon.arrange.match`). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-29: Offset Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects are chained one after another in a row or a column with a set gap (negative to overlap them), in stacking order or by position, either way; the first stays in place and the others move only along the row or column, as one undo step (`addon.arrange.offset`). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-15: Tangent Circle joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the circles that touch two selected paths or compound paths at a set radius, or three of them (up to eight for three circles), touching each outline without crossing it; circles, rotated ellipses and other paths alike. A dialog that previews every circle or one picked by number, the current paint, one undo step (`addon.pathtools.tangentCircle`). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-17: Add Bounding Rectangle and Add Bounding Circle join the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): a live rectangle on the selection's geometric bounding box, or the smallest live circle that holds its outlines, around the whole selection or around each object, with the current paint and one undo step; the menu items open a dialog with Offset, One per Object and Preview (`addon.pathtools.boundingRectangle`, `addon.pathtools.boundingCircle`, #6966). A VectorCraft addition: headline numbers unchanged.
|
||||
|
||||
@@ -28,7 +28,7 @@ egui_extras = { workspace = true }
|
||||
# `wgpu` pulls egui-wgpu's defaults: WebGPU plus the WebGL2 fallback.
|
||||
eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit"] }
|
||||
# The page command API (storytold/craft-libs#413): the request plumbing behind window.vectorcraft.
|
||||
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735", version = "0.1.0" }
|
||||
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d", version = "0.1.0" }
|
||||
|
||||
wasm-bindgen = "0.2"
|
||||
serde_json = { workspace = true }
|
||||
|
||||
@@ -5,6 +5,10 @@ dist = "../../dist/web"
|
||||
public_url = "./"
|
||||
filehash = true
|
||||
|
||||
[tools]
|
||||
# Binaryen 123 crashes while optimizing the release bundle; keep the optimizer explicit.
|
||||
wasm_opt = "version_133"
|
||||
|
||||
[serve]
|
||||
addresses = ["127.0.0.1"]
|
||||
port = 8766
|
||||
|
||||
@@ -22,6 +22,7 @@ vectorcraft-text = { workspace = true }
|
||||
# frame policy and placement store (so VectorCraft matches the rest on Linux, see #217), printing and
|
||||
# the update client.
|
||||
craft = { workspace = true, features = ["ui", "ui-app", "settings", "automation", "platform", "window", "dialogs", "print", "update"] }
|
||||
craft-nightly = { workspace = true }
|
||||
eframe = { workspace = true, features = ["clipboard", "default_fonts", "wayland", "x11"] }
|
||||
egui = { workspace = true }
|
||||
egui_extras = { workspace = true }
|
||||
|
||||
@@ -1,30 +1,13 @@
|
||||
//! Build-time channel is distinct from a launch selector. A runtime environment cannot promote a
|
||||
//! stable build, and a nightly build refuses to start without its profile.
|
||||
use crate::launch_profile::Profile;
|
||||
use std::ffi::OsString;
|
||||
//! stable build, and a nightly build self-isolates into its canonical nightly profile root (or the
|
||||
//! profile root supplied by ArtCraft Launcher).
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum BuildFlavor {
|
||||
Stable,
|
||||
NightlyV1,
|
||||
}
|
||||
pub use craft_nightly::BuildFlavor;
|
||||
|
||||
pub const COMPILED: BuildFlavor = if cfg!(vectorcraft_nightly_v1) { BuildFlavor::NightlyV1 } else { BuildFlavor::Stable };
|
||||
|
||||
pub fn require_profile(flavor: BuildFlavor, profile: &Profile) -> Result<(), String> {
|
||||
match (flavor, profile.is_nightly()) {
|
||||
(BuildFlavor::NightlyV1, false) => Err("Open VectorCraft Nightly from ArtCraft Launcher".to_string()),
|
||||
(BuildFlavor::Stable, true) => Err("This is a stable VectorCraft build; nightly-v1 requires the nightly build".to_string()),
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn needs_native_error(flavor: BuildFlavor, desktop_session: bool) -> bool {
|
||||
desktop_session && flavor == BuildFlavor::NightlyV1
|
||||
}
|
||||
|
||||
/// `--version` and `-V` on their own, before any other argument is read.
|
||||
pub fn version_query(args: &[OsString]) -> bool {
|
||||
/// An exact plain version query, before resolving any profile or environment paths.
|
||||
pub fn version_query(args: &[std::ffi::OsString]) -> bool {
|
||||
matches!(args, [arg] if arg == "--version" || arg == "-V")
|
||||
}
|
||||
|
||||
@@ -37,40 +20,19 @@ pub fn version(flavor: BuildFlavor, stable: &str) -> String {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use super::{BuildFlavor, version, version_query};
|
||||
|
||||
#[test]
|
||||
fn only_a_nightly_desktop_refusal_requests_a_native_dialog() {
|
||||
assert!(needs_native_error(BuildFlavor::NightlyV1, true));
|
||||
assert!(!needs_native_error(BuildFlavor::NightlyV1, false));
|
||||
assert!(!needs_native_error(BuildFlavor::Stable, true));
|
||||
assert!(!needs_native_error(BuildFlavor::Stable, false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nightly_build_without_a_profile_is_refused_before_startup() {
|
||||
let started = std::cell::Cell::new(false);
|
||||
let result = require_profile(BuildFlavor::NightlyV1, &Profile::Stable).map(|()| started.set(true));
|
||||
assert!(result.unwrap_err().contains("ArtCraft Launcher"));
|
||||
assert!(!started.get());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stable_and_nightly_flavors_accept_only_their_own_profile() {
|
||||
let nightly = Profile::NightlyV1(std::path::PathBuf::from("already validated root"));
|
||||
assert!(require_profile(BuildFlavor::Stable, &Profile::Stable).is_ok());
|
||||
assert!(require_profile(BuildFlavor::Stable, &nightly).is_err());
|
||||
assert!(require_profile(BuildFlavor::NightlyV1, &nightly).is_ok());
|
||||
assert!(require_profile(BuildFlavor::NightlyV1, &Profile::Stable).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nightly_version_query_is_unambiguous_and_never_reinterprets_file_arguments() {
|
||||
assert_eq!(version(BuildFlavor::Stable, "0.24.1"), "0.24.1");
|
||||
assert_eq!(version(BuildFlavor::NightlyV1, "0.24.1"), "0.24.1 (nightly-v1)");
|
||||
fn plain_version_query_is_exact() {
|
||||
assert!(version_query(&["--version".into()]));
|
||||
assert!(version_query(&["-V".into()]));
|
||||
assert!(!version_query(&["--".into(), "--version".into()]));
|
||||
assert!(!version_query(&[]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn version_labels_nightly_without_changing_stable() {
|
||||
assert_eq!(version(BuildFlavor::Stable, "0.24.1"), "0.24.1");
|
||||
assert_eq!(version(BuildFlavor::NightlyV1, "0.24.1"), "0.24.1 (nightly-v1)");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,130 +1,28 @@
|
||||
//! Launcher-owned nightly-v1 bootstrap. Selected before logging, updates, fonts or saved state.
|
||||
//! Stable launches retain their original arguments and directory policy.
|
||||
//!
|
||||
//! The protocol is `vectorcraft --launch-profile nightly-v1 --profile-root <abs> -- [files…]`: the
|
||||
//! selector and the root are separate tokens, exactly once each, and everything after `--` is a file
|
||||
//! even when it looks like one of them. The Launcher's version check
|
||||
//! (`… --version`) is answered before the root is validated or touched.
|
||||
//! Nightly-v1 bootstrap backed by [`craft_nightly`]. Selected before logging, updates, fonts or
|
||||
//! saved state. Stable launches retain their original arguments and directory policy; direct
|
||||
//! nightly launches self-isolate into [`craft_nightly::canonical_profile_root`], while ArtCraft
|
||||
//! Launcher can supply `--launch-profile nightly-v1 --profile-root <abs> -- [args…]`.
|
||||
|
||||
use std::ffi::OsString;
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
use std::sync::OnceLock;
|
||||
|
||||
pub const VERSION: &str = "nightly-v1";
|
||||
pub use craft_nightly::NIGHTLY_V1_CONTRACT as VERSION;
|
||||
use craft_nightly::{BuildFlavor, Launch, Profile, ProfileError, StartupOptions};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum Profile {
|
||||
Stable,
|
||||
NightlyV1(PathBuf),
|
||||
}
|
||||
|
||||
impl Profile {
|
||||
pub fn is_nightly(&self) -> bool {
|
||||
matches!(self, Self::NightlyV1(_))
|
||||
}
|
||||
|
||||
pub fn root(&self) -> Option<&Path> {
|
||||
match self {
|
||||
Self::Stable => None,
|
||||
Self::NightlyV1(root) => Some(root),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub struct Launch {
|
||||
pub profile: Profile,
|
||||
pub args: Vec<OsString>,
|
||||
}
|
||||
|
||||
static PROFILE: OnceLock<Profile> = OnceLock::new();
|
||||
static STABLE: Profile = Profile::Stable;
|
||||
|
||||
pub fn current() -> &'static Profile {
|
||||
PROFILE.get().unwrap_or(&Profile::Stable)
|
||||
craft_nightly::current().unwrap_or(&STABLE)
|
||||
}
|
||||
|
||||
pub fn install(profile: Profile) -> Result<(), String> {
|
||||
PROFILE.set(profile).map_err(|_| "the launch profile was already selected".to_string())
|
||||
}
|
||||
|
||||
/// Recognize only the agreed literal selector/root pair before `--`. No filesystem or startup hook
|
||||
/// runs here.
|
||||
pub fn parse(args: Vec<OsString>) -> Result<Launch, String> {
|
||||
let mut selector = None;
|
||||
let mut root = None;
|
||||
let mut other = Vec::new();
|
||||
let mut files = Vec::new();
|
||||
let mut iter = args.iter();
|
||||
let mut delimiter = false;
|
||||
while let Some(arg) = iter.next() {
|
||||
if arg == "--" {
|
||||
delimiter = true;
|
||||
files.extend(iter.cloned());
|
||||
break;
|
||||
}
|
||||
if arg == "--launch-profile" || arg == "--profile-root" {
|
||||
let slot = if arg == "--launch-profile" { &mut selector } else { &mut root };
|
||||
if slot.is_some() {
|
||||
return Err("the profile selector and root must each occur exactly once".to_string());
|
||||
}
|
||||
let value = iter.next().filter(|v| !v.is_empty()).ok_or_else(|| "the profile selector/root needs a value".to_string())?;
|
||||
if value.to_string_lossy().starts_with("--") {
|
||||
return Err("the profile selector/root needs a value".to_string());
|
||||
}
|
||||
*slot = Some(value.clone());
|
||||
} else if arg.to_string_lossy().starts_with("--launch-profile=") || arg.to_string_lossy().starts_with("--profile-root=") {
|
||||
return Err("the nightly protocol requires separate literal selector/root argument tokens".to_string());
|
||||
} else {
|
||||
other.push(arg.clone());
|
||||
}
|
||||
}
|
||||
match (selector, root) {
|
||||
(None, None) => Ok(Launch { profile: Profile::Stable, args }),
|
||||
(Some(version), Some(root)) if version == VERSION => {
|
||||
if !delimiter || !other.is_empty() {
|
||||
return Err("nightly-v1 accepts only its selector/root followed by -- and file names".to_string());
|
||||
}
|
||||
let root = PathBuf::from(root);
|
||||
if !root.is_absolute() || root.components().any(|c| matches!(c, Component::ParentDir)) {
|
||||
return Err("the nightly profile root must be absolute and contain no parent traversal".to_string());
|
||||
}
|
||||
Ok(Launch { profile: Profile::NightlyV1(root), args: std::iter::once(OsString::from("--")).chain(files).collect() })
|
||||
}
|
||||
(Some(_), Some(_)) => Err("unsupported launch profile (expected nightly-v1)".to_string()),
|
||||
_ => Err("--launch-profile and --profile-root must be supplied together".to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The Launcher's version check: the selector/root pair followed by exactly `--version` (or `-V`),
|
||||
/// answered like a plain version query. Only [`parse`]'s lexical checks apply; the root is never
|
||||
/// validated or touched, and `-- --version` stays a file name.
|
||||
pub fn version_query(args: &[OsString]) -> bool {
|
||||
let Some((last, pair)) = args.split_last() else { return false };
|
||||
if last != "--version" && last != "-V" {
|
||||
return false;
|
||||
}
|
||||
let lexical = pair.iter().cloned().chain(std::iter::once(OsString::from("--"))).collect();
|
||||
matches!(parse(lexical), Ok(Launch { profile: Profile::NightlyV1(_), args }) if args.len() == 1)
|
||||
}
|
||||
|
||||
/// Validation finishes before the caller's first startup effect. Stable never calls the nightly root
|
||||
/// validator, so its portable and config resolution stays unchanged.
|
||||
pub fn prepare(mut launch: Launch, validate: impl FnOnce(&Path) -> Result<PathBuf, String>) -> Result<Launch, String> {
|
||||
if let Profile::NightlyV1(root) = &launch.profile {
|
||||
launch.profile = Profile::NightlyV1(validate(root)?);
|
||||
}
|
||||
Ok(launch)
|
||||
}
|
||||
|
||||
/// Resolve the selected private root before the caller's first startup effect.
|
||||
pub fn validate_root(root: &Path, env: impl Fn(&str) -> Option<OsString>, exe: Option<&Path>) -> Result<PathBuf, String> {
|
||||
crate::profile_root::validate(root, env, exe, crate::prefs_dir::profile::ensure_writable)
|
||||
pub fn prepare_launch(flavor: BuildFlavor, args: impl IntoIterator<Item = OsString>) -> Result<Launch, ProfileError> {
|
||||
let spec = crate::profile_root::app_profile_spec();
|
||||
craft_nightly::prepare_launch(flavor, &spec, args, &StartupOptions::default())
|
||||
}
|
||||
|
||||
/// The arguments a child of this process starts with: a nightly launch hands its profile on, so the
|
||||
/// child opens the same private profile instead of being refused ("Open VectorCraft Nightly…"), and
|
||||
/// `--` keeps a file whose name starts with '-' a file. Stable's child arguments are unchanged.
|
||||
/// Only `single_instance` starts a child, and macOS does not build it.
|
||||
/// child opens the same private profile, and `--` keeps a file whose name starts with '-' a file.
|
||||
/// Stable's child arguments are unchanged. Only `single_instance` starts a child, and macOS does
|
||||
/// not build it.
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
pub fn child_args(files: &[String]) -> Vec<OsString> {
|
||||
child_args_for(current(), files)
|
||||
@@ -132,21 +30,24 @@ pub fn child_args(files: &[String]) -> Vec<OsString> {
|
||||
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
fn child_args_for(profile: &Profile, files: &[String]) -> Vec<OsString> {
|
||||
let mut args: Vec<OsString> = match profile {
|
||||
Profile::Stable => Vec::new(),
|
||||
Profile::NightlyV1(root) => {
|
||||
vec![OsString::from("--launch-profile"), OsString::from(VERSION), OsString::from("--profile-root"), root.clone().into_os_string()]
|
||||
}
|
||||
};
|
||||
args.push(OsString::from("--"));
|
||||
args.extend(files.iter().map(OsString::from));
|
||||
args
|
||||
let delimited: Vec<OsString> = std::iter::once(OsString::from("--")).chain(files.iter().map(OsString::from)).collect();
|
||||
match profile {
|
||||
Profile::Stable => delimited,
|
||||
Profile::NightlyV1(root) => craft_nightly::launch_arguments(root, &delimited),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::cell::Cell;
|
||||
use std::ffi::OsString;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use craft_nightly::{BuildFlavor, Profile, ProfileError, StartupOptions, canonical_profile_root, parse_startup};
|
||||
|
||||
use super::VERSION;
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
use super::child_args_for;
|
||||
use crate::profile_root::app_profile_spec;
|
||||
|
||||
fn args(values: &[&str]) -> Vec<OsString> {
|
||||
values.iter().map(OsString::from).collect()
|
||||
@@ -156,95 +57,72 @@ mod tests {
|
||||
if cfg!(windows) { r"C:\NightlyData\profiles\vectorcraft" } else { "/nightly-data/profiles/vectorcraft" }
|
||||
}
|
||||
|
||||
fn nightly() -> Vec<OsString> {
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--"])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stable_arguments_and_directory_policy_are_unchanged() {
|
||||
fn stable_arguments_are_unchanged_and_nightly_flags_are_refused() {
|
||||
let spec = app_profile_spec();
|
||||
for argv in [args(&[]), args(&["--new-instance", "a.svg"]), args(&["--", "--launch-profile", "file.svg"])] {
|
||||
let launch = prepare(parse(argv.clone()).unwrap(), |_| panic!("stable must never validate a nightly root")).unwrap();
|
||||
assert_eq!(launch, Launch { profile: Profile::Stable, args: argv });
|
||||
let launch = parse_startup(BuildFlavor::Stable, &spec, argv.clone(), &StartupOptions::default()).unwrap();
|
||||
assert_eq!(launch.profile, Profile::Stable);
|
||||
assert_eq!(launch.passthrough_args, argv);
|
||||
}
|
||||
|
||||
let nightly_flags = args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--"]);
|
||||
let err = parse_startup(BuildFlavor::Stable, &spec, nightly_flags, &StartupOptions::default()).unwrap_err();
|
||||
assert!(matches!(err, ProfileError::NightlyFlagsInStableBuild));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exact_version_and_root_are_parsed_without_reinterpreting_file_names() {
|
||||
let mut argv = nightly();
|
||||
argv.extend(args(&["--profile-root", "art with spaces.svg"]));
|
||||
let launch = parse(argv).unwrap();
|
||||
fn nightly_direct_launch_self_isolates_into_canonical_profile_root() {
|
||||
let spec = app_profile_spec();
|
||||
let expected_root = canonical_profile_root("vectorcraft").unwrap();
|
||||
|
||||
let empty = parse_startup(BuildFlavor::NightlyV1, &spec, Vec::new(), &StartupOptions::default()).unwrap();
|
||||
assert_eq!(empty.profile, Profile::NightlyV1(expected_root.clone()));
|
||||
assert!(empty.passthrough_args.is_empty());
|
||||
|
||||
let with_args = parse_startup(BuildFlavor::NightlyV1, &spec, args(&["--safe-mode", "art.svg"]), &StartupOptions::default()).unwrap();
|
||||
assert_eq!(with_args.profile, Profile::NightlyV1(expected_root));
|
||||
assert_eq!(with_args.passthrough_args, args(&["--safe-mode", "art.svg"]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_launcher_arguments_preserve_profile_root_and_user_args() {
|
||||
let spec = app_profile_spec();
|
||||
let argv = args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--", "--profile-root", "art with spaces.svg"]);
|
||||
let launch = parse_startup(BuildFlavor::NightlyV1, &spec, argv, &StartupOptions::default()).unwrap();
|
||||
assert_eq!(launch.profile, Profile::NightlyV1(PathBuf::from(absolute())));
|
||||
assert_eq!(launch.args, args(&["--", "--profile-root", "art with spaces.svg"]));
|
||||
assert_eq!(launch.passthrough_args, args(&["--profile-root", "art with spaces.svg"]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_duplicate_unknown_and_conflicting_profile_arguments_are_refused() {
|
||||
for argv in [
|
||||
args(&["--launch-profile", VERSION]),
|
||||
args(&["--profile-root", absolute()]),
|
||||
args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--"]),
|
||||
args(&["--launch-profile", VERSION, "--launch-profile", VERSION, "--profile-root", absolute(), "--"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--profile-root", absolute(), "--"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", "relative", "--"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", "../escape", "--"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", "", "--"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--new-instance", "--"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute()]),
|
||||
] {
|
||||
assert!(parse(argv.clone()).is_err(), "{argv:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_launcher_version_check_is_a_version_query_only_in_its_exact_form() {
|
||||
let pair = &["--launch-profile", VERSION, "--profile-root", absolute()];
|
||||
let reversed = &["--profile-root", absolute(), "--launch-profile", VERSION];
|
||||
fn version_queries_are_recognized_plain_and_via_launcher() {
|
||||
let spec = app_profile_spec();
|
||||
for flag in ["--version", "-V"] {
|
||||
for form in [pair, reversed] {
|
||||
let mut argv = args(form);
|
||||
argv.push(flag.into());
|
||||
assert!(version_query(&argv), "{argv:?}");
|
||||
for argv in [
|
||||
args(&[flag]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), flag]),
|
||||
args(&["--profile-root", absolute(), "--launch-profile", VERSION, flag]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--", flag]),
|
||||
] {
|
||||
let launch = parse_startup(BuildFlavor::NightlyV1, &spec, argv.clone(), &StartupOptions::default()).unwrap();
|
||||
assert!(launch.is_version_query(), "{argv:?}");
|
||||
}
|
||||
}
|
||||
for argv in [
|
||||
args(&["--version"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--", "--version"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--new-instance", "--version"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--version"]),
|
||||
args(&["--version", "--launch-profile", VERSION, "--profile-root", absolute()]),
|
||||
args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--version"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", "relative", "--version"]),
|
||||
args(&["--launch-profile", VERSION, "--version"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--help"]),
|
||||
] {
|
||||
assert!(!version_query(&argv), "{argv:?}");
|
||||
}
|
||||
// Outside the query the strict protocol still refuses the version flag.
|
||||
assert!(parse(args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version"])).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_root_validation_never_reaches_startup_or_falls_back_to_stable() {
|
||||
let reached = Cell::new(false);
|
||||
let result = prepare(parse(nightly()).unwrap(), |_| Err("read-only or unsafe profile".to_string())).map(|_| reached.set(true));
|
||||
assert!(result.is_err());
|
||||
assert!(!reached.get());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn successful_root_validation_keeps_the_persistent_root_not_the_binary_tag() {
|
||||
let checked = PathBuf::from(absolute()).join("checked");
|
||||
let launch = prepare(parse(nightly()).unwrap(), |_| Ok(checked.clone())).unwrap();
|
||||
assert_eq!(launch.profile.root(), Some(checked.as_path()));
|
||||
assert!(launch.profile.is_nightly());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_joined_flag_form_is_refused() {
|
||||
for joined in [format!("--launch-profile={VERSION}"), format!("--profile-root={}", absolute())] {
|
||||
let argv = vec![OsString::from(joined), OsString::from("--")];
|
||||
assert!(parse(argv).is_err());
|
||||
fn version_and_document_arguments_are_not_a_version_only_query() {
|
||||
let spec = app_profile_spec();
|
||||
for flag in ["--version", "-V"] {
|
||||
for argv in [
|
||||
args(&[flag, "art with spaces.svg"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), flag, "art with spaces.svg"]),
|
||||
args(&["--profile-root", absolute(), "--launch-profile", VERSION, flag, "art with spaces.svg"]),
|
||||
] {
|
||||
let launch = parse_startup(BuildFlavor::NightlyV1, &spec, argv, &StartupOptions::default()).unwrap();
|
||||
assert!(!launch.is_version_query());
|
||||
assert_eq!(launch.passthrough_args, args(&[flag, "art with spaces.svg"]));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -258,6 +136,7 @@ mod tests {
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
#[test]
|
||||
fn a_nightly_child_inherits_the_selected_profile() {
|
||||
let spec = app_profile_spec();
|
||||
let root = PathBuf::from(absolute());
|
||||
let child = child_args_for(&Profile::NightlyV1(root.clone()), &["art.svg".to_string()]);
|
||||
let expected = vec![
|
||||
@@ -266,12 +145,12 @@ mod tests {
|
||||
OsString::from("--profile-root"),
|
||||
root.into_os_string(),
|
||||
OsString::from("--"),
|
||||
OsString::from("--"),
|
||||
OsString::from("art.svg"),
|
||||
];
|
||||
assert_eq!(child, expected);
|
||||
// The child's own parse finds the same profile and the file list.
|
||||
let launch = parse(child).unwrap();
|
||||
let launch = parse_startup(BuildFlavor::NightlyV1, &spec, child, &StartupOptions::default()).unwrap();
|
||||
assert!(launch.profile.is_nightly());
|
||||
assert_eq!(launch.args, args(&["--", "art.svg"]));
|
||||
assert_eq!(launch.passthrough_args, args(&["--", "art.svg"]));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -112,6 +112,43 @@ use prefs::{load_prefs, log_dir, open_store, prefs_enabled};
|
||||
const DEFAULT_SIZE: [f32; 2] = [1440.0, 900.0];
|
||||
const MIN_SIZE: [f32; 2] = [800.0, 500.0];
|
||||
|
||||
/// Apply the saved main-window placement before the first frame. On a first launch the
|
||||
/// framework maximizes the window when its default size would not fit the current screen.
|
||||
fn restore_main_window(window: &winit::window::Window, store: &Store, legacy: Option<vectorcraft_ui_egui::state::LegacyWindow>, wayland: bool) {
|
||||
use craft::behavior::placement::{Defaults, Placement, place};
|
||||
use craft::behavior::{Monitor, MonitorKey};
|
||||
use winit::dpi::{LogicalSize, PhysicalPosition};
|
||||
|
||||
let handles: Vec<_> = window.available_monitors().collect();
|
||||
let monitors: Vec<_> = handles
|
||||
.iter()
|
||||
.map(|monitor| {
|
||||
let size = monitor.size();
|
||||
let size = [size.width, size.height];
|
||||
let position = monitor.position();
|
||||
Monitor::new(MonitorKey::new(monitor.name().unwrap_or_default(), size), [position.x, position.y], size, monitor.scale_factor() as f32)
|
||||
})
|
||||
.collect();
|
||||
let home = window.current_monitor().or_else(|| window.primary_monitor()).and_then(|monitor| handles.iter().position(|m| *m == monitor));
|
||||
let defaults = Defaults::new(DEFAULT_SIZE, MIN_SIZE).with_no_position(wayland);
|
||||
let saved = store.get(craft::window::restore::MAIN).or_else(|| {
|
||||
let old = legacy?;
|
||||
let mut placement = Placement::new(old.size, window.scale_factor() as f32);
|
||||
placement.position_px = old.pos;
|
||||
placement.maximized = old.maximized;
|
||||
placement.repaired()
|
||||
});
|
||||
let placement = place(saved.as_ref(), &monitors, home, &defaults);
|
||||
if let Some([x, y]) = placement.position_px {
|
||||
window.set_outer_position(PhysicalPosition::new(x, y));
|
||||
}
|
||||
let [width, height] = placement.normal.size;
|
||||
let _ = window.request_inner_size(LogicalSize::new(width, height));
|
||||
if placement.maximized {
|
||||
window.set_maximized(true);
|
||||
}
|
||||
}
|
||||
|
||||
/// The window, Dock, taskbar and app-switcher icon (`assets/app-icon/`, see its README). macOS gets
|
||||
/// the version with Apple's transparent margin; elsewhere the full-bleed tile. The app ID matches
|
||||
/// `packaging/linux/ai.storyteller.vectorcraft.desktop` so Wayland docks find the launcher icon.
|
||||
@@ -384,58 +421,47 @@ fn channel_name() -> &'static str {
|
||||
|
||||
/// Says why a nightly launch was refused, then exits 2. A window could not have shown it yet: this
|
||||
/// app has no message box of its own before eframe starts (its dialogs are egui windows), so the
|
||||
/// text goes to standard error, which a Launcher launch records. The desktop-session test still
|
||||
/// decides whether a daily user would have seen it, for the message's wording.
|
||||
/// text goes to standard error, which a Launcher launch records.
|
||||
fn report_launch_profile_error(error: &str) {
|
||||
eprintln!("VectorCraft launch profile: {error}");
|
||||
let desktop_session = cfg!(windows)
|
||||
|| cfg!(target_os = "macos")
|
||||
|| (cfg!(target_os = "linux") && ["DISPLAY", "WAYLAND_DISPLAY"].into_iter().any(|key| std::env::var_os(key).is_some_and(|v| !v.is_empty())));
|
||||
if build_flavor::needs_native_error(build_flavor::COMPILED, desktop_session) {
|
||||
eprintln!("VectorCraft Nightly: open it from ArtCraft Launcher, which starts it in its own profile");
|
||||
}
|
||||
}
|
||||
|
||||
fn write_nightly_version() {
|
||||
use std::io::Write as _;
|
||||
let line = format!("VectorCraft {}\n", build_flavor::version(build_flavor::COMPILED, env!("VECTORCRAFT_BUILT_VERSION")));
|
||||
let _ = std::io::stdout().write_all(line.as_bytes());
|
||||
}
|
||||
|
||||
/// Selects the immutable launch profile before any startup service or side effect, and returns the
|
||||
/// arguments the rest of `main` reads. `None` means the process ends here (`--version` answered).
|
||||
fn prepare_launch() -> Option<Vec<std::ffi::OsString>> {
|
||||
// The trusted Launcher protocol is decided before the logger, updates, fonts or any saved state.
|
||||
// The launch profile is decided before the logger, updates, fonts or any saved state.
|
||||
let argv: Vec<_> = std::env::args_os().skip(1).collect();
|
||||
// A nightly answers its version before root validation, process identity, IPC or any window:
|
||||
// plain `--version`/`-V`, or the Launcher's `--launch-profile nightly-v1 --profile-root <dir>
|
||||
// --version`. A stable build leaves the answer to `read_command_line`, exactly as before.
|
||||
if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && (build_flavor::version_query(&argv) || launch_profile::version_query(&argv))
|
||||
{
|
||||
use std::io::Write as _;
|
||||
let line = format!("VectorCraft {}\n", build_flavor::version(build_flavor::COMPILED, env!("VECTORCRAFT_BUILT_VERSION")));
|
||||
let _ = std::io::stdout().write_all(line.as_bytes());
|
||||
// A plain nightly version query does not even need the OS home/data root to resolve.
|
||||
if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && build_flavor::version_query(&argv) {
|
||||
write_nightly_version();
|
||||
return None;
|
||||
}
|
||||
let early = launch_profile::prepare_launch(build_flavor::COMPILED, argv).unwrap_or_else(|error| {
|
||||
report_launch_profile_error(&error.to_string());
|
||||
std::process::exit(2)
|
||||
});
|
||||
// A launcher version query also exits before process identity, IPC or any window.
|
||||
// `craft_nightly::prepare_launch` skips root preparation for version queries.
|
||||
// A stable build leaves the answer to `read_command_line`, exactly as before.
|
||||
if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && early.is_version_query() {
|
||||
write_nightly_version();
|
||||
return None;
|
||||
}
|
||||
let early = launch_profile::parse(argv)
|
||||
.and_then(|launch| {
|
||||
build_flavor::require_profile(build_flavor::COMPILED, &launch.profile)?;
|
||||
Ok(launch)
|
||||
})
|
||||
.and_then(|launch| {
|
||||
launch_profile::prepare(launch, |root| {
|
||||
launch_profile::validate_root(root, |key| std::env::var_os(key), std::env::current_exe().ok().as_deref())
|
||||
})
|
||||
})
|
||||
.unwrap_or_else(|error| {
|
||||
report_launch_profile_error(&error);
|
||||
std::process::exit(2)
|
||||
});
|
||||
let nightly = early.profile.is_nightly();
|
||||
let identity =
|
||||
if nightly { vectorcraft_ui_egui::os_window::LaunchIdentity::NightlyV1 } else { vectorcraft_ui_egui::os_window::LaunchIdentity::Stable };
|
||||
let install = launch_profile::install(early.profile).and_then(|()| {
|
||||
// Every data path follows the selected profile from here on: settings, logs, recovery, the
|
||||
// user's libraries, plug-ins, caches and the single-instance record.
|
||||
if let Some(root) = launch_profile::current().root() {
|
||||
prefs_dir::profile::install_data_root(root.to_path_buf())?;
|
||||
}
|
||||
vectorcraft_ui_egui::os_window::select_identity(identity)
|
||||
});
|
||||
// Every data path follows the selected profile from here on: settings, logs, recovery, the
|
||||
// user's libraries, plug-ins, caches and the single-instance record.
|
||||
let install = launch_profile::current()
|
||||
.root()
|
||||
.map_or(Ok(()), |root| prefs_dir::profile::install_data_root(root.to_path_buf()))
|
||||
.and_then(|()| vectorcraft_ui_egui::os_window::select_identity(identity));
|
||||
if let Err(error) = install {
|
||||
report_launch_profile_error(&error);
|
||||
std::process::exit(2);
|
||||
@@ -453,11 +479,11 @@ fn prepare_launch() -> Option<Vec<std::ffi::OsString>> {
|
||||
// The window's identity, not the profile, failed: main's own failure status (1).
|
||||
std::process::exit(1);
|
||||
}
|
||||
Some(early.args)
|
||||
Some(early.passthrough_args)
|
||||
}
|
||||
|
||||
/// The arguments the rest of `main` reads: a nightly's profile tokens were consumed by
|
||||
/// `prepare_launch`, so what is left is `--` and the files to open. A stable launch reads its
|
||||
/// `prepare_launch`, leaving any user flags and files to open. A stable launch reads its
|
||||
/// arguments exactly as it always did.
|
||||
fn launch_arguments(nightly: bool, arguments: &[std::ffi::OsString]) -> Vec<String> {
|
||||
if nightly { arguments.iter().map(|a| a.to_string_lossy().into_owned()).collect() } else { std::env::args().skip(1).collect() }
|
||||
@@ -520,8 +546,9 @@ fn finish_pending_update(nightly: bool) {
|
||||
}
|
||||
|
||||
fn main() -> std::process::ExitCode {
|
||||
// The launch profile first: a nightly build without one is refused here, before the update
|
||||
// helper, the logger, fonts or any saved state, and `--version` is answered here too.
|
||||
// The launch profile first: a nightly build self-isolates or uses the Launcher's profile here,
|
||||
// before the update helper, the logger, fonts or any saved state, and `--version` is answered
|
||||
// here too.
|
||||
let Some(arguments) = prepare_launch() else { return std::process::ExitCode::SUCCESS };
|
||||
let nightly = launch_profile::current().is_nightly();
|
||||
#[cfg(windows)]
|
||||
@@ -791,9 +818,13 @@ fn main() -> std::process::ExitCode {
|
||||
Box::new(move |cc| {
|
||||
let ctx = &cc.egui_ctx;
|
||||
let winit_window = cc.winit_window().cloned();
|
||||
let placement = placement_store();
|
||||
if let Some(window) = &winit_window {
|
||||
restore_main_window(window, &placement, settings.lock().get().ui.legacy_window, wayland);
|
||||
}
|
||||
let spec = InstallSpec::new(shell_info, Arc::new(SystemWindows))
|
||||
.app_id(vectorcraft_ui_egui::os_window::app_id())
|
||||
.placement(Arc::new(Mutex::new(placement_store())))
|
||||
.placement(Arc::new(Mutex::new(placement)))
|
||||
.frame(decision);
|
||||
let spec = match start_pen(&winit_window) {
|
||||
Some(pen) => spec.pen(pen),
|
||||
@@ -808,7 +839,7 @@ fn main() -> std::process::ExitCode {
|
||||
};
|
||||
let (files, file_panels) = file_service(wake, folders);
|
||||
let files = Arc::new(files);
|
||||
craft::host::Host::builder(AppInfo {
|
||||
let host = craft::host::Host::builder(AppInfo {
|
||||
id: vectorcraft_ui_egui::os_window::SETTINGS_APP_ID,
|
||||
name: vectorcraft_ui_egui::os_window::name(),
|
||||
version: vectorcraft_ui_egui::os_window::version(),
|
||||
@@ -816,7 +847,8 @@ fn main() -> std::process::ExitCode {
|
||||
.i18n(vectorcraft_ui_egui::i18n::shared())
|
||||
.settings(Arc::new(settings.clone()))
|
||||
.files(files.clone())
|
||||
.install(ctx);
|
||||
.build();
|
||||
host.clone().install(ctx);
|
||||
let mut session = Session::new();
|
||||
// The profiles loaded before come back before the preferences name any of them.
|
||||
prefs_dir::attach_profile_store(&mut session);
|
||||
@@ -841,6 +873,7 @@ fn main() -> std::process::ExitCode {
|
||||
prefs_dir::attach_proof_setups(&mut session);
|
||||
prefs_dir::attach_script_data(&mut session);
|
||||
let mut app = VectorcraftApp::new(session, services(winit_window.clone()));
|
||||
app.host = Arc::new(host);
|
||||
app.adopt_context(&cc.egui_ctx);
|
||||
// A nightly is updated by the Launcher: it never checks for a stable release, which
|
||||
// would install this program's own updater over the nightly build.
|
||||
|
||||
@@ -1,264 +1,17 @@
|
||||
//! App-owned nightly profile fences: a profile every one of VectorCraft's data paths is redirected
|
||||
//! into ([`crate::prefs_dir::profile::install_data_root`]), and that never overlaps stable's folders, a portable
|
||||
//! copy or an installation.
|
||||
//! App-owned nightly profile specification for [`craft_nightly`]: describes VectorCraft's stable
|
||||
//! directories, forbidden environment variables, portable markers, folder-only profile entries, and
|
||||
//! extra installation/package boundaries so a nightly profile never overlaps stable state.
|
||||
|
||||
use std::ffi::OsString;
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use crate::prefs_dir::profile::PORTABLE_DATA_DIR;
|
||||
use craft_nightly::AppProfileSpec;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Platform {
|
||||
Windows,
|
||||
Linux,
|
||||
Mac,
|
||||
}
|
||||
use crate::prefs_dir::profile::{PORTABLE_DATA_DIR, PORTABLE_MARKERS};
|
||||
|
||||
impl Platform {
|
||||
fn current() -> Result<Self, String> {
|
||||
match std::env::consts::OS {
|
||||
"windows" => Ok(Self::Windows),
|
||||
"linux" => Ok(Self::Linux),
|
||||
"macos" => Ok(Self::Mac),
|
||||
other => Err(format!("nightly-v1 is not defined for this operating system ({other})")),
|
||||
}
|
||||
}
|
||||
const STABLE_DIR_NAMES: [&str; 2] = ["VectorCraft", "vectorcraft"];
|
||||
|
||||
fn ignores_case(self) -> bool {
|
||||
self != Self::Linux
|
||||
}
|
||||
}
|
||||
|
||||
fn absolute(path: PathBuf, label: &str) -> Result<PathBuf, String> {
|
||||
if !path.is_absolute() || path.components().any(|c| matches!(c, Component::ParentDir)) {
|
||||
return Err(format!("{label} must be absolute and contain no parent traversal"));
|
||||
}
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
fn required_base(env: &impl Fn(&str) -> Option<OsString>, key: &str) -> Result<PathBuf, String> {
|
||||
let value = env(key).filter(|v| !v.is_empty()).ok_or_else(|| format!("cannot establish the stable {key} boundary"))?;
|
||||
absolute(PathBuf::from(value), key)
|
||||
}
|
||||
|
||||
fn xdg_base(env: &impl Fn(&str) -> Option<OsString>, key: &str, fallback: &str) -> Result<PathBuf, String> {
|
||||
match env(key).filter(|v| !v.is_empty()) {
|
||||
Some(value) => absolute(PathBuf::from(value), key),
|
||||
None => Ok(required_base(env, "HOME")?.join(fallback)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolve existing ancestors before creating anything. A dangling link or an inaccessible ancestor
|
||||
/// is not a missing directory that may be replaced or followed later.
|
||||
fn canonical_future(path: &Path) -> Result<PathBuf, String> {
|
||||
let mut parent = path;
|
||||
let mut missing = Vec::new();
|
||||
loop {
|
||||
match std::fs::symlink_metadata(parent) {
|
||||
Ok(_) => break,
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
|
||||
missing.push(parent.file_name().ok_or_else(|| "the profile root has no existing ancestor".to_string())?.to_os_string());
|
||||
parent = parent.parent().ok_or_else(|| "the profile root has no existing ancestor".to_string())?;
|
||||
}
|
||||
Err(error) => return Err(format!("cannot inspect the profile boundary: {error}")),
|
||||
}
|
||||
}
|
||||
let mut resolved = std::fs::canonicalize(parent).map_err(|e| format!("cannot resolve the profile boundary: {e}"))?;
|
||||
for part in missing.into_iter().rev() {
|
||||
resolved.push(part);
|
||||
}
|
||||
Ok(resolved)
|
||||
}
|
||||
|
||||
/// A stable entry point may be a dangling link once its target is uninstalled. Its own name is still
|
||||
/// the fence, so only the folder it lives in is resolved: a link that cannot be resolved would refuse
|
||||
/// every launch, a valid private profile included.
|
||||
fn canonical_future_entry(path: &Path) -> Result<PathBuf, String> {
|
||||
let parent = path.parent().ok_or_else(|| "an entry point has no folder".to_string())?;
|
||||
let name = path.file_name().ok_or_else(|| "an entry point has no name".to_string())?;
|
||||
Ok(canonical_future(parent)?.join(name))
|
||||
}
|
||||
|
||||
fn overlaps(a: &Path, b: &Path, platform: Platform) -> bool {
|
||||
let parts = |p: &Path| {
|
||||
p.components()
|
||||
.map(|c| {
|
||||
let value = c.as_os_str().to_string_lossy().into_owned();
|
||||
if platform.ignores_case() { value.to_lowercase() } else { value }
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
let (a, b) = (parts(a), parts(b));
|
||||
a.starts_with(&b) || b.starts_with(&a)
|
||||
}
|
||||
|
||||
fn installation_boundary(platform: Platform, exe: &Path) -> Result<PathBuf, String> {
|
||||
let parent = exe.parent().ok_or_else(|| "cannot establish the installation boundary".to_string())?;
|
||||
if platform == Platform::Mac {
|
||||
// A profile in Resources is still inside the versioned install, not beside MacOS.
|
||||
if let Some(bundle) = exe.ancestors().find(|p| p.extension().is_some_and(|ext| ext.eq_ignore_ascii_case("app"))) {
|
||||
return Ok(bundle.to_path_buf());
|
||||
}
|
||||
}
|
||||
Ok(parent.to_path_buf())
|
||||
}
|
||||
|
||||
/// Every folder a stable VectorCraft keeps user state in, on `platform`: the settings folder each
|
||||
/// platform convention and the portable layout use, the eframe window state, the logs, the recovery
|
||||
/// copies, the plug-ins, the caches, the install folders and the entry points. A nightly profile that
|
||||
/// overlapped any of them would read, rewrite or prune stable's own state.
|
||||
fn forbidden_roots(platform: Platform, env: &impl Fn(&str) -> Option<OsString>, exe: &Path) -> Result<Vec<PathBuf>, String> {
|
||||
let mut roots = match platform {
|
||||
Platform::Windows => {
|
||||
// The settings folder (`profile.rs`) and the eframe window state, which eframe puts under
|
||||
// `%APPDATA%\ai.storyteller.vectorcraft\data` (the window id).
|
||||
let mut roots = ["APPDATA", "LOCALAPPDATA"]
|
||||
.into_iter()
|
||||
.map(|key| required_base(env, key).map(|p| p.join("VectorCraft")))
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
roots.push(required_base(env, "APPDATA")?.join("ai.storyteller.vectorcraft"));
|
||||
// The MSI's default per-user and per-machine folders (install-policy.wxi). A custom
|
||||
// install folder is not known here; the executable's own folder is fenced below.
|
||||
roots.push(required_base(env, "LOCALAPPDATA")?.join("Programs").join("ArtCraft").join("VectorCraft"));
|
||||
for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] {
|
||||
if let Some(base) = env(key).filter(|v| !v.is_empty()) {
|
||||
roots.push(absolute(PathBuf::from(base), key)?.join("ArtCraft").join("VectorCraft"));
|
||||
}
|
||||
}
|
||||
roots
|
||||
}
|
||||
Platform::Linux => {
|
||||
let mut roots =
|
||||
[("XDG_CONFIG_HOME", ".config"), ("XDG_DATA_HOME", ".local/share"), ("XDG_CACHE_HOME", ".cache"), ("XDG_STATE_HOME", ".local/state")]
|
||||
.into_iter()
|
||||
.map(|(key, fallback)| xdg_base(env, key, fallback).map(|p| p.join("vectorcraft")))
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
// The eframe window state, under the lowercased window id.
|
||||
roots.push(xdg_base(env, "XDG_DATA_HOME", ".local/share")?.join("ai.storyteller.vectorcraft"));
|
||||
roots.push(required_base(env, "HOME")?.join(".config").join("VectorCraft"));
|
||||
// The same folders at their HOME defaults: an XDG override moves this launch's own paths,
|
||||
// not stable's, which stays where a launch without the override finds it.
|
||||
for (directory, app) in
|
||||
[(".config", "vectorcraft"), (".local/share", "vectorcraft"), (".cache", "vectorcraft"), (".local/state", "vectorcraft")]
|
||||
{
|
||||
roots.push(required_base(env, "HOME")?.join(directory).join(app));
|
||||
}
|
||||
// The stable Flatpak keeps its data in its own per-app folder.
|
||||
roots.push(required_base(env, "HOME")?.join(".var/app/ai.storyteller.vectorcraft"));
|
||||
roots
|
||||
}
|
||||
Platform::Mac => {
|
||||
let home = required_base(env, "HOME")?;
|
||||
let library = home.join("Library");
|
||||
vec![
|
||||
library.join("Application Support/VectorCraft"),
|
||||
library.join("Application Support/ai.storyteller.vectorcraft"),
|
||||
library.join("Caches/VectorCraft"),
|
||||
library.join("Caches/ai.storyteller.vectorcraft"),
|
||||
library.join("Preferences/VectorCraft"),
|
||||
library.join("Preferences/ai.storyteller.vectorcraft.plist"),
|
||||
library.join("Saved Application State/ai.storyteller.vectorcraft.savedState"),
|
||||
home.join("Applications/VectorCraft.app"),
|
||||
PathBuf::from("/Applications/VectorCraft.app"),
|
||||
]
|
||||
}
|
||||
};
|
||||
roots.push(installation_boundary(platform, exe)?);
|
||||
let mut fences = roots.into_iter().map(|p| canonical_future(&p)).collect::<Result<Vec<_>, _>>()?;
|
||||
if platform == Platform::Linux {
|
||||
for entry in ["/usr/bin/vectorcraft", "/usr/local/bin/vectorcraft", "/opt/vectorcraft"] {
|
||||
fences.push(canonical_future_entry(Path::new(entry))?);
|
||||
}
|
||||
}
|
||||
Ok(fences)
|
||||
}
|
||||
|
||||
fn private_subdirectory(root: &Path, name: impl AsRef<Path>, label: &str) -> Result<PathBuf, String> {
|
||||
let chosen = canonical_future(&absolute(root.to_path_buf(), "the nightly profile root")?)?;
|
||||
let target = chosen.join(name);
|
||||
match std::fs::symlink_metadata(&target) {
|
||||
Ok(metadata) if !metadata.is_dir() => {
|
||||
return Err(format!("the nightly {label} must be a directory inside its selected profile"));
|
||||
}
|
||||
Ok(_) => {}
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
|
||||
Err(error) => return Err(format!("cannot inspect the nightly {label}: {error}")),
|
||||
}
|
||||
let child = canonical_future(&target)?;
|
||||
if child == chosen || !child.starts_with(&chosen) {
|
||||
return Err(format!("the nightly {label} must stay inside its selected profile"));
|
||||
}
|
||||
Ok(child)
|
||||
}
|
||||
|
||||
/// Every existing entry directly in the profile (settings, logs, the user's libraries and so on) must
|
||||
/// resolve inside it, so a link there cannot point Nightly's writes at another app's data.
|
||||
fn entries_stay_inside(root: &Path) -> Result<(), String> {
|
||||
let entries = match std::fs::read_dir(root) {
|
||||
Ok(entries) => entries,
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
|
||||
Err(error) => return Err(format!("cannot inspect the nightly profile: {error}")),
|
||||
};
|
||||
for entry in entries {
|
||||
let entry = entry.map_err(|e| format!("cannot inspect the nightly profile: {e}"))?;
|
||||
let path = entry.path();
|
||||
let metadata = std::fs::symlink_metadata(&path).map_err(|e| format!("cannot inspect the nightly profile: {e}"))?;
|
||||
// Settings and session state are ordinary files, not directories. Keep the existing
|
||||
// directory-boundary check for folders (including the known folder-only entries).
|
||||
let folder_only = PROFILE_FOLDERS.iter().any(|name| entry.file_name().eq_ignore_ascii_case(name));
|
||||
if metadata.is_file() && !folder_only {
|
||||
private_regular_file(&path, &metadata)?;
|
||||
} else {
|
||||
private_subdirectory(root, entry.file_name(), "profile entry")?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Persisted files must have their own ordinary file identity, not an alias to other data.
|
||||
fn private_regular_file(path: &Path, metadata: &std::fs::Metadata) -> Result<(), String> {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::MetadataExt as _;
|
||||
if metadata.nlink() != 1 {
|
||||
return Err("the nightly profile file must not be shared".into());
|
||||
}
|
||||
}
|
||||
#[cfg(all(windows, feature = "wgpu"))]
|
||||
{
|
||||
use winsafe::{HFILE, co};
|
||||
let (file, _) = HFILE::CreateFile(
|
||||
path.to_str().ok_or("the nightly profile file path is not textual")?,
|
||||
co::GENERIC::default(),
|
||||
Some(co::FILE_SHARE::READ | co::FILE_SHARE::WRITE | co::FILE_SHARE::DELETE),
|
||||
None,
|
||||
co::DISPOSITION::OPEN_EXISTING,
|
||||
co::FILE_ATTRIBUTE::NORMAL,
|
||||
Some(co::FILE_FLAG::OPEN_REPARSE_POINT),
|
||||
None,
|
||||
None,
|
||||
)
|
||||
.map_err(|e| e.to_string())?;
|
||||
let info = file.GetFileInformationByHandle().map_err(|e| e.to_string())?;
|
||||
if info.dwFileAttributes.has(co::FILE_ATTRIBUTE::REPARSE_POINT) || info.dwFileAttributes.has(co::FILE_ATTRIBUTE::DIRECTORY) {
|
||||
return Err("the nightly profile file must not be an alias or directory".into());
|
||||
}
|
||||
if info.nNumberOfLinks != 1 {
|
||||
return Err("the nightly profile file must not be shared".into());
|
||||
}
|
||||
}
|
||||
#[cfg(all(windows, not(feature = "wgpu")))]
|
||||
{
|
||||
use std::os::windows::fs::MetadataExt as _;
|
||||
const FILE_ATTRIBUTE_DIRECTORY: u32 = 0x10;
|
||||
const FILE_ATTRIBUTE_REPARSE_POINT: u32 = 0x400;
|
||||
if metadata.file_attributes() & (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_REPARSE_POINT) != 0 {
|
||||
return Err("the nightly profile file must not be an alias or directory".into());
|
||||
}
|
||||
}
|
||||
let _ = (path, metadata);
|
||||
Ok(())
|
||||
}
|
||||
const FORBIDDEN_ENV_VARS: [&str; 2] = ["VECTORCRAFT_CONFIG_DIR", "VECTORCRAFT_NO_PREFS"];
|
||||
|
||||
const PROFILE_FOLDERS: [&str; 18] = [
|
||||
"Data Recovery",
|
||||
@@ -281,397 +34,207 @@ const PROFILE_FOLDERS: [&str; 18] = [
|
||||
"Libraries",
|
||||
];
|
||||
|
||||
/// Recognise the shared portable data namespace in both the supplied and the resolved path. Up to
|
||||
/// the chosen folder itself, a marker only counts beside a VectorCraft executable, so an unrelated
|
||||
/// `portable.txt` higher up (in a user folder or at a drive root) does not refuse the profile.
|
||||
fn is_portable_layout(path: &Path, platform: Platform) -> bool {
|
||||
path.ancestors().enumerate().any(|(depth, ancestor)| {
|
||||
crate::prefs_dir::profile::PORTABLE_MARKERS.iter().any(|marker| ancestor.join(marker).is_file())
|
||||
&& (depth == 0 || ["vectorcraft.exe", "vectorcraft"].iter().any(|exe| ancestor.join(exe).is_file()))
|
||||
}) || path.components().any(|component| match component {
|
||||
Component::Normal(name) if platform.ignores_case() => name.to_string_lossy().eq_ignore_ascii_case(PORTABLE_DATA_DIR),
|
||||
Component::Normal(name) => name == PORTABLE_DATA_DIR,
|
||||
_ => false,
|
||||
})
|
||||
/// Builds VectorCraft's [`AppProfileSpec`] for [`craft_nightly`].
|
||||
pub fn app_profile_spec() -> AppProfileSpec {
|
||||
AppProfileSpec {
|
||||
app_id: vectorcraft_ui_egui::os_window::SETTINGS_APP_ID,
|
||||
display_name: vectorcraft_ui_egui::os_window::APP_NAME,
|
||||
stable_dir_names: &STABLE_DIR_NAMES,
|
||||
stable_package_id: vectorcraft_ui_egui::os_window::APP_ID,
|
||||
nightly_package_id: vectorcraft_ui_egui::os_window::NIGHTLY_PACKAGE_ID,
|
||||
profile_root_env: None,
|
||||
forbidden_env_vars: &FORBIDDEN_ENV_VARS,
|
||||
portable_markers: &PORTABLE_MARKERS,
|
||||
folder_only_entries: &PROFILE_FOLDERS,
|
||||
extra_forbidden_roots: extra_forbidden_roots(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The writable hook is the app's own exclusive probe ([`crate::prefs_dir::profile::ensure_writable`]). Keeping
|
||||
/// it injected lets the boundary tests exercise the real policy without starting the app.
|
||||
pub fn validate(
|
||||
root: &Path,
|
||||
env: impl Fn(&str) -> Option<OsString>,
|
||||
exe: Option<&Path>,
|
||||
writable: impl FnOnce(&Path) -> std::io::Result<()>,
|
||||
) -> Result<PathBuf, String> {
|
||||
validate_for(Platform::current()?, root, env, exe, writable)
|
||||
fn non_empty_abs(env: &impl Fn(&str) -> Option<OsString>, key: &str) -> Option<PathBuf> {
|
||||
let value = env(key)?;
|
||||
if value.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let path = PathBuf::from(value);
|
||||
path.is_absolute().then_some(path)
|
||||
}
|
||||
|
||||
fn validate_for(
|
||||
platform: Platform,
|
||||
root: &Path,
|
||||
env: impl Fn(&str) -> Option<OsString>,
|
||||
exe: Option<&Path>,
|
||||
writable: impl FnOnce(&Path) -> std::io::Result<()>,
|
||||
) -> Result<PathBuf, String> {
|
||||
absolute(root.to_path_buf(), "the nightly profile root")?;
|
||||
if env("VECTORCRAFT_CONFIG_DIR").is_some_and(|v| !v.is_empty()) {
|
||||
return Err("nightly-v1 cannot be combined with VECTORCRAFT_CONFIG_DIR".to_string());
|
||||
}
|
||||
// The app turns preferences off whenever the variable is present, empty value included.
|
||||
if env("VECTORCRAFT_NO_PREFS").is_some() {
|
||||
// A run without preferences keeps nothing: its own profile would stay unused and the app
|
||||
// would log to standard error only, so it is never a nightly launch.
|
||||
return Err("nightly-v1 cannot inherit VECTORCRAFT_NO_PREFS".to_string());
|
||||
}
|
||||
let nightly_flatpak = vectorcraft_ui_egui::os_window::NIGHTLY_PACKAGE_ID;
|
||||
if platform != Platform::Windows
|
||||
&& let Some(id) = env("FLATPAK_ID").filter(|value| !value.is_empty())
|
||||
&& id.to_string_lossy().as_ref() != nightly_flatpak
|
||||
fn extra_forbidden_roots() -> Vec<PathBuf> {
|
||||
extra_forbidden_roots_with(|key| std::env::var_os(key), std::env::current_exe().ok().as_deref())
|
||||
}
|
||||
|
||||
fn extra_forbidden_roots_with(env: impl Fn(&str) -> Option<OsString>, exe: Option<&Path>) -> Vec<PathBuf> {
|
||||
let mut roots = Vec::new();
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
// `packaging/linux/flatpak-bundle.sh` builds VectorCraft Nightly as its own Flatpak
|
||||
// (`ai.storyteller.vectorcraft.nightly`), whose sandbox is already a private home. Any other
|
||||
// instance, the stable app's included, would put this profile inside another app's tree.
|
||||
return Err(format!("nightly-v1 can only run inside its own Flatpak instance ({nightly_flatpak}), not {}", id.to_string_lossy()));
|
||||
if let Some(local) = non_empty_abs(&env, "LOCALAPPDATA") {
|
||||
roots.push(local.join("Programs").join("ArtCraft").join("VectorCraft"));
|
||||
}
|
||||
for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] {
|
||||
if let Some(base) = non_empty_abs(&env, key) {
|
||||
roots.push(base.join("ArtCraft").join("VectorCraft"));
|
||||
}
|
||||
}
|
||||
}
|
||||
let chosen = canonical_future(root)?;
|
||||
if is_portable_layout(root, platform) || is_portable_layout(&chosen, platform) {
|
||||
return Err("the nightly root must not use a portable VectorCraft installation or its VectorCraftData settings folder".to_string());
|
||||
}
|
||||
let exe = absolute(exe.ok_or_else(|| "cannot establish the installation boundary".to_string())?.to_path_buf(), "the executable")?;
|
||||
let forbidden = forbidden_roots(platform, &env, &exe)?;
|
||||
if forbidden.iter().any(|stable| overlaps(&chosen, stable, platform)) {
|
||||
return Err("the nightly root must not overlap stable data or an installation".to_string());
|
||||
}
|
||||
// Data Recovery can read, adopt, overwrite and sweep entries: never let its alias leave the
|
||||
// private profile.
|
||||
private_subdirectory(&chosen, "Data Recovery", "recovery folder")?;
|
||||
entries_stay_inside(&chosen)?;
|
||||
let mut create = std::fs::DirBuilder::new();
|
||||
create.recursive(true);
|
||||
#[cfg(unix)]
|
||||
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
{
|
||||
use std::os::unix::fs::DirBuilderExt as _;
|
||||
create.mode(0o700);
|
||||
if let Some(home) = non_empty_abs(&env, "HOME") {
|
||||
roots.push(home.join(".var").join("app").join(vectorcraft_ui_egui::os_window::APP_ID));
|
||||
}
|
||||
for entry in ["/usr/bin/vectorcraft", "/usr/local/bin/vectorcraft", "/opt/vectorcraft"] {
|
||||
roots.push(PathBuf::from(entry));
|
||||
}
|
||||
}
|
||||
create.create(&chosen).map_err(|e| format!("cannot create the nightly profile: {e}"))?;
|
||||
let confirmed = std::fs::canonicalize(&chosen).map_err(|e| format!("cannot resolve the created nightly profile: {e}"))?;
|
||||
if confirmed != chosen || forbidden.iter().any(|stable| overlaps(&confirmed, stable, platform)) {
|
||||
return Err("the nightly profile changed while it was being validated".to_string());
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
if let Some(home) = non_empty_abs(&env, "HOME") {
|
||||
let library = home.join("Library");
|
||||
roots.push(library.join("Preferences").join(format!("{}.plist", vectorcraft_ui_egui::os_window::APP_ID)));
|
||||
roots.push(library.join("Saved Application State").join(format!("{}.savedState", vectorcraft_ui_egui::os_window::APP_ID)));
|
||||
roots.push(home.join("Applications").join("VectorCraft.app"));
|
||||
}
|
||||
roots.push(PathBuf::from("/Applications/VectorCraft.app"));
|
||||
}
|
||||
private_subdirectory(&confirmed, "Data Recovery", "recovery folder")?;
|
||||
entries_stay_inside(&confirmed)?;
|
||||
writable(&confirmed).map_err(|e| format!("the nightly profile is not writable: {e}"))?;
|
||||
Ok(confirmed)
|
||||
|
||||
if let Some(exe) = exe {
|
||||
if let Some(parent) = exe.parent() {
|
||||
roots.push(parent.join(PORTABLE_DATA_DIR));
|
||||
}
|
||||
#[cfg(target_os = "macos")]
|
||||
if let Some(bundle_parent) = exe.ancestors().find(|p| p.extension().is_some_and(|ext| ext.eq_ignore_ascii_case("app"))).and_then(Path::parent)
|
||||
{
|
||||
roots.push(bundle_parent.join(PORTABLE_DATA_DIR));
|
||||
}
|
||||
}
|
||||
|
||||
roots
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::cell::Cell;
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::ffi::OsString;
|
||||
use std::fs;
|
||||
#[cfg(unix)]
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// An owned fixture tree: a home, a roaming/local app-data pair and an install folder, so the
|
||||
/// fence can be checked for every platform on any host.
|
||||
struct Fixture {
|
||||
root: PathBuf,
|
||||
env: BTreeMap<String, OsString>,
|
||||
exe: PathBuf,
|
||||
}
|
||||
use craft_nightly::validate_and_prepare_root;
|
||||
|
||||
impl Fixture {
|
||||
fn new() -> Self {
|
||||
static NEXT: AtomicU64 = AtomicU64::new(0);
|
||||
let root = loop {
|
||||
let candidate =
|
||||
std::env::temp_dir().join(format!("vectorcraft-profile-policy-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
|
||||
match std::fs::create_dir(&candidate) {
|
||||
Ok(()) => break std::fs::canonicalize(candidate).unwrap(),
|
||||
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
|
||||
Err(error) => panic!("cannot create owned fixture: {error}"),
|
||||
}
|
||||
};
|
||||
let home = root.join("home");
|
||||
let exe = root.join("install/vectorcraft");
|
||||
std::fs::create_dir_all(&home).unwrap();
|
||||
std::fs::create_dir_all(exe.parent().unwrap()).unwrap();
|
||||
std::fs::write(&exe, b"fixture executable, never run").unwrap();
|
||||
let env = [("HOME", home), ("APPDATA", root.join("roaming")), ("LOCALAPPDATA", root.join("local"))]
|
||||
.into_iter()
|
||||
.map(|(key, value)| (key.into(), value.into_os_string()))
|
||||
.collect();
|
||||
Self { root, env, exe }
|
||||
}
|
||||
|
||||
fn get(&self, key: &str) -> Option<OsString> {
|
||||
self.env.get(key).cloned()
|
||||
}
|
||||
|
||||
fn home(&self) -> PathBuf {
|
||||
PathBuf::from(self.get("HOME").unwrap())
|
||||
}
|
||||
|
||||
fn check(&self, platform: Platform, root: &Path) -> Result<PathBuf, String> {
|
||||
self.check_with(platform, root, |_| Ok(()))
|
||||
}
|
||||
|
||||
fn check_with(&self, platform: Platform, root: &Path, writable: impl FnOnce(&Path) -> std::io::Result<()>) -> Result<PathBuf, String> {
|
||||
validate_for(platform, root, |key| self.get(key), Some(&self.exe), writable)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Fixture {
|
||||
fn drop(&mut self) {
|
||||
// Only the directory this fixture created is owned for removal.
|
||||
std::fs::remove_dir_all(&self.root).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
const PLATFORMS: [Platform; 3] = [Platform::Windows, Platform::Linux, Platform::Mac];
|
||||
use super::{FORBIDDEN_ENV_VARS, PROFILE_FOLDERS, STABLE_DIR_NAMES, app_profile_spec, extra_forbidden_roots_with};
|
||||
use crate::prefs_dir::profile::{PORTABLE_DATA_DIR, PORTABLE_MARKERS};
|
||||
|
||||
#[test]
|
||||
fn a_private_profile_is_accepted_on_every_platform() {
|
||||
let fixture = Fixture::new();
|
||||
for platform in PLATFORMS {
|
||||
let root = fixture.root.join(format!("nightly profiles/{platform:?}/vectorcraft"));
|
||||
let resolved = fixture.check(platform, &root).unwrap();
|
||||
assert!(resolved.is_dir(), "{platform:?}");
|
||||
assert_eq!(resolved, std::fs::canonicalize(root).unwrap(), "{platform:?}");
|
||||
std::fs::remove_dir_all(fixture.root.join("nightly profiles")).unwrap();
|
||||
}
|
||||
fn spec_preserves_vectorcraft_invariants() {
|
||||
let spec = app_profile_spec();
|
||||
assert_eq!(spec.app_id, "vectorcraft");
|
||||
assert_eq!(spec.display_name, "VectorCraft");
|
||||
assert_eq!(spec.stable_dir_names, &STABLE_DIR_NAMES);
|
||||
assert_eq!(spec.stable_package_id, "ai.storyteller.vectorcraft");
|
||||
assert_eq!(spec.nightly_package_id, "ai.storyteller.vectorcraft.nightly");
|
||||
assert_eq!(spec.profile_root_env, None);
|
||||
assert_eq!(spec.forbidden_env_vars, &FORBIDDEN_ENV_VARS);
|
||||
assert_eq!(spec.portable_markers, &PORTABLE_MARKERS);
|
||||
assert_eq!(spec.folder_only_entries, &PROFILE_FOLDERS);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stable_settings_folders_are_refused_on_every_platform() {
|
||||
let fixture = Fixture::new();
|
||||
let stable = [
|
||||
(Platform::Windows, fixture.get("APPDATA").map(|v| PathBuf::from(v).join("VectorCraft"))),
|
||||
(Platform::Windows, fixture.get("APPDATA").map(|v| PathBuf::from(v).join("ai.storyteller.vectorcraft"))),
|
||||
(Platform::Windows, fixture.get("LOCALAPPDATA").map(|v| PathBuf::from(v).join("VectorCraft"))),
|
||||
(Platform::Windows, fixture.get("LOCALAPPDATA").map(|v| PathBuf::from(v).join("Programs/ArtCraft/VectorCraft"))),
|
||||
(Platform::Linux, Some(fixture.home().join(".config/vectorcraft"))),
|
||||
(Platform::Linux, Some(fixture.home().join(".local/share/vectorcraft"))),
|
||||
(Platform::Linux, Some(fixture.home().join(".local/share/ai.storyteller.vectorcraft"))),
|
||||
(Platform::Linux, Some(fixture.home().join(".cache/vectorcraft"))),
|
||||
(Platform::Linux, Some(fixture.home().join(".var/app/ai.storyteller.vectorcraft"))),
|
||||
(Platform::Mac, Some(fixture.home().join("Library/Application Support/VectorCraft"))),
|
||||
(Platform::Mac, Some(fixture.home().join("Library/Application Support/ai.storyteller.vectorcraft"))),
|
||||
(Platform::Mac, Some(fixture.home().join("Library/Preferences/ai.storyteller.vectorcraft.plist"))),
|
||||
];
|
||||
for (platform, stable) in stable {
|
||||
let stable = stable.unwrap();
|
||||
for candidate in [stable.clone(), stable.join("nested nightly")] {
|
||||
let probed = Cell::new(false);
|
||||
let result = fixture.check_with(platform, &candidate, |_| {
|
||||
probed.set(true);
|
||||
Ok(())
|
||||
});
|
||||
assert!(result.is_err(), "{platform:?} accepted {candidate:?}");
|
||||
assert!(!probed.get(), "a refused root is rejected before the writable probe");
|
||||
}
|
||||
}
|
||||
}
|
||||
fn extra_forbidden_roots_fences_platform_installs_and_portable_data() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let home = tmp.path().join("home");
|
||||
let exe = tmp.path().join("install/vectorcraft");
|
||||
let roots = extra_forbidden_roots_with(
|
||||
|key| match key {
|
||||
"HOME" | "LOCALAPPDATA" | "ProgramFiles" => Some(home.clone().into_os_string()),
|
||||
_ => None,
|
||||
},
|
||||
Some(&exe),
|
||||
);
|
||||
assert!(roots.contains(&tmp.path().join("install").join(PORTABLE_DATA_DIR)));
|
||||
|
||||
#[test]
|
||||
fn the_install_folder_and_the_entry_points_are_refused() {
|
||||
let fixture = Fixture::new();
|
||||
for platform in PLATFORMS {
|
||||
let install = fixture.exe.parent().unwrap();
|
||||
assert!(fixture.check(platform, install).is_err(), "{platform:?}: the install folder");
|
||||
assert!(fixture.check(platform, &install.join("NightlyData")).is_err(), "{platform:?}: inside the install");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_inherited_config_or_no_prefs_override_is_refused() {
|
||||
let fixture = Fixture::new();
|
||||
let root = fixture.root.join("nightly");
|
||||
for (key, value) in [
|
||||
("VECTORCRAFT_CONFIG_DIR", "/elsewhere"),
|
||||
("VECTORCRAFT_NO_PREFS", "1"),
|
||||
// The app turns preferences off on presence, so an empty value is a run too.
|
||||
("VECTORCRAFT_NO_PREFS", ""),
|
||||
("FLATPAK_ID", "ai.storyteller.vectorcraft"),
|
||||
] {
|
||||
for platform in PLATFORMS {
|
||||
let result = validate_for(
|
||||
platform,
|
||||
&root,
|
||||
|name| if name == key { Some(value.into()) } else { fixture.get(name) },
|
||||
Some(&fixture.exe),
|
||||
|_| Ok(()),
|
||||
);
|
||||
let refused = result.is_err();
|
||||
// A Flatpak instance only keeps the stable app's sockets on native Unix packages.
|
||||
assert_eq!(refused, !(key == "FLATPAK_ID" && platform == Platform::Windows), "{key} on {platform:?}");
|
||||
if refused {
|
||||
assert!(!root.exists(), "a refused launch creates nothing ({key} on {platform:?})");
|
||||
} else if root.exists() {
|
||||
// The accepted case validated the root, which creates it: start the next one clean.
|
||||
std::fs::remove_dir_all(&root).expect("remove the accepted launch's root");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_the_nightly_s_own_flatpak_instance_may_carry_a_profile() {
|
||||
let fixture = Fixture::new();
|
||||
let root = fixture.root.join("flatpak profile");
|
||||
for (id, accepted) in
|
||||
[(vectorcraft_ui_egui::os_window::NIGHTLY_PACKAGE_ID, true), ("ai.storyteller.vectorcraft", false), ("io.other.App", false)]
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
let result = validate_for(
|
||||
Platform::Linux,
|
||||
&root,
|
||||
|name| if name == "FLATPAK_ID" { Some(id.into()) } else { fixture.get(name) },
|
||||
Some(&fixture.exe),
|
||||
|_| Ok(()),
|
||||
);
|
||||
assert_eq!(result.is_ok(), accepted, "{id}");
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
assert!(roots.contains(&home.join("Programs").join("ArtCraft").join("VectorCraft")));
|
||||
assert!(roots.contains(&home.join("ArtCraft").join("VectorCraft")));
|
||||
}
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
{
|
||||
assert!(roots.contains(&home.join(".var/app/ai.storyteller.vectorcraft")));
|
||||
assert!(roots.contains(&PathBuf::from("/usr/bin/vectorcraft")));
|
||||
assert!(roots.contains(&PathBuf::from("/usr/local/bin/vectorcraft")));
|
||||
assert!(roots.contains(&PathBuf::from("/opt/vectorcraft")));
|
||||
}
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
assert!(roots.contains(&home.join("Library/Preferences/ai.storyteller.vectorcraft.plist")));
|
||||
assert!(roots.contains(&home.join("Library/Saved Application State/ai.storyteller.vectorcraft.savedState")));
|
||||
assert!(roots.contains(&home.join("Applications/VectorCraft.app")));
|
||||
assert!(roots.contains(&PathBuf::from("/Applications/VectorCraft.app")));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_portable_copy_and_its_data_folder_are_refused() {
|
||||
let fixture = Fixture::new();
|
||||
let portable = fixture.root.join("portable copy");
|
||||
let data = portable.join(crate::prefs_dir::profile::PORTABLE_DATA_DIR);
|
||||
std::fs::create_dir_all(&data).unwrap();
|
||||
std::fs::write(portable.join("portable.txt"), b"owned portable fixture").unwrap();
|
||||
std::fs::write(data.join("config.toml"), b"stable settings must not change").unwrap();
|
||||
for platform in PLATFORMS {
|
||||
for candidate in [&data, &data.join("nested nightly")] {
|
||||
let probed = Cell::new(false);
|
||||
let result = fixture.check_with(platform, candidate, |_| {
|
||||
probed.set(true);
|
||||
Ok(())
|
||||
});
|
||||
assert!(result.is_err(), "{platform:?} accepted {candidate:?}");
|
||||
assert!(!probed.get());
|
||||
assert!(!data.join("nested nightly").exists());
|
||||
assert_eq!(std::fs::read(data.join("config.toml")).unwrap(), b"stable settings must not change");
|
||||
}
|
||||
fn nightly_profile_reopens_after_saving_settings_and_enforces_folder_only_entries() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let private = tmp.path().join("nightly-reopen");
|
||||
let mut spec = app_profile_spec();
|
||||
spec.forbidden_env_vars = &[];
|
||||
|
||||
let canonical = validate_and_prepare_root(&private, &spec).unwrap();
|
||||
assert_eq!(canonical, fs::canonicalize(&private).unwrap());
|
||||
|
||||
for name in ["config.toml", "instance.json", "Color Settings.json", "app.ron"] {
|
||||
fs::write(canonical.join(name), b"saved profile data").unwrap();
|
||||
}
|
||||
for name in PROFILE_FOLDERS {
|
||||
fs::create_dir(canonical.join(name)).unwrap();
|
||||
}
|
||||
assert_eq!(validate_and_prepare_root(&private, &spec).unwrap(), canonical);
|
||||
for name in ["config.toml", "instance.json", "Color Settings.json", "app.ron"] {
|
||||
assert_eq!(fs::read(canonical.join(name)).unwrap(), b"saved profile data", "{name} remains intact after reopen");
|
||||
}
|
||||
|
||||
for name in PROFILE_FOLDERS {
|
||||
let path = canonical.join(name);
|
||||
fs::remove_dir(&path).unwrap();
|
||||
fs::write(&path, b"not a directory").unwrap();
|
||||
assert!(validate_and_prepare_root(&private, &spec).is_err(), "{name} must stay a directory");
|
||||
fs::remove_file(&path).unwrap();
|
||||
fs::create_dir(&path).unwrap();
|
||||
}
|
||||
// A merely similar name is not the portable settings folder.
|
||||
let similar = fixture.root.join("VectorCraftData-backup-name/nightly");
|
||||
assert!(fixture.check(Platform::Linux, &similar).is_ok());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_link_inside_the_profile_cannot_redirect_recovery_or_a_library() {
|
||||
let fixture = Fixture::new();
|
||||
let root = fixture.root.join("nightly");
|
||||
std::fs::create_dir_all(&root).unwrap();
|
||||
let external = fixture.root.join("stable-document");
|
||||
std::fs::write(&external, b"stable bytes").unwrap();
|
||||
fn symlink_inside_profile_is_refused() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let private = tmp.path().join("nightly");
|
||||
fs::create_dir_all(&private).unwrap();
|
||||
let external = tmp.path().join("stable-document");
|
||||
fs::write(&external, b"stable bytes").unwrap();
|
||||
|
||||
let mut spec = app_profile_spec();
|
||||
spec.forbidden_env_vars = &[];
|
||||
|
||||
for name in ["Data Recovery", "Swatches"] {
|
||||
let alias = root.join(name);
|
||||
let alias = private.join(name);
|
||||
std::os::unix::fs::symlink(&external, &alias).unwrap();
|
||||
assert!(fixture.check(Platform::Linux, &root).is_err(), "{name} alias");
|
||||
std::fs::remove_file(&alias).unwrap();
|
||||
assert!(validate_and_prepare_root(&private, &spec).is_err(), "{name} alias");
|
||||
fs::remove_file(&alias).unwrap();
|
||||
}
|
||||
assert_eq!(std::fs::read(&external).unwrap(), b"stable bytes");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_dangling_link_or_a_linked_ancestor_is_refused() {
|
||||
let fixture = Fixture::new();
|
||||
let elsewhere = fixture.root.join("elsewhere");
|
||||
std::fs::create_dir_all(&elsewhere).unwrap();
|
||||
let linked = fixture.root.join("nightly");
|
||||
std::os::unix::fs::symlink(&elsewhere, &linked).unwrap();
|
||||
// Canonical resolution keeps a link's target: a profile reached through one is fine, but it
|
||||
// is judged (and named) as its target, so nothing is written under the link.
|
||||
let resolved = fixture.check(Platform::Linux, &linked).unwrap();
|
||||
assert_eq!(resolved, std::fs::canonicalize(&elsewhere).unwrap());
|
||||
std::fs::remove_file(&linked).unwrap();
|
||||
let dangling = fixture.root.join("dangling/nightly");
|
||||
std::fs::create_dir_all(dangling.parent().unwrap()).unwrap();
|
||||
std::os::unix::fs::symlink(fixture.root.join("missing"), dangling.parent().unwrap().join("nightly")).unwrap();
|
||||
assert!(fixture.check(Platform::Linux, &dangling).is_err());
|
||||
assert_eq!(fs::read(&external).unwrap(), b"stable bytes");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_home_settings_folder_is_fenced_even_when_the_xdg_override_moves_elsewhere() {
|
||||
let fixture = Fixture::new();
|
||||
let xdg = fixture.root.join("override");
|
||||
std::fs::create_dir_all(&xdg).unwrap();
|
||||
let config = fixture.home().join(".config/vectorcraft");
|
||||
let data = fixture.home().join(".local/share/vectorcraft");
|
||||
for stable in [config.clone(), data.clone()] {
|
||||
for candidate in [stable.clone(), stable.join("nested nightly")] {
|
||||
let result = validate_for(
|
||||
Platform::Linux,
|
||||
&candidate,
|
||||
|name| match name {
|
||||
"XDG_CONFIG_HOME" | "XDG_DATA_HOME" => Some(xdg.clone().into_os_string()),
|
||||
_ => fixture.get(name),
|
||||
},
|
||||
Some(&fixture.exe),
|
||||
|_| Ok(()),
|
||||
);
|
||||
assert!(result.is_err(), "accepted {candidate:?} with the XDG folders moved to {xdg:?}");
|
||||
}
|
||||
}
|
||||
assert!(!config.exists() && !data.exists(), "a refused root creates nothing");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_dangling_entry_point_keeps_its_fence_instead_of_refusing_every_launch() {
|
||||
let fixture = Fixture::new();
|
||||
let bin = fixture.root.join("entry/bin");
|
||||
std::fs::create_dir_all(&bin).unwrap();
|
||||
let entry = bin.join("vectorcraft");
|
||||
std::os::unix::fs::symlink(fixture.root.join("uninstalled target"), &entry).unwrap();
|
||||
// The shared resolver refuses the dangling link, as a profile root must be.
|
||||
assert!(canonical_future(&entry).is_err());
|
||||
assert_eq!(canonical_future_entry(&entry).unwrap(), std::fs::canonicalize(&bin).unwrap().join("vectorcraft"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unwritable_profile_is_refused_after_the_probe_and_never_used() {
|
||||
let fixture = Fixture::new();
|
||||
let root = fixture.root.join("nightly");
|
||||
let result = fixture.check_with(Platform::Linux, &root, |_| Err(std::io::Error::other("read-only")));
|
||||
assert!(result.unwrap_err().contains("not writable"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nightly_profile_reopens_after_saving_settings_and_session_state() {
|
||||
let fixture = Fixture::new();
|
||||
for platform in PLATFORMS {
|
||||
let private = fixture.root.join(format!("nightly-reopen-{platform:?}"));
|
||||
assert_eq!(fixture.check(platform, &private).unwrap(), private);
|
||||
for name in ["config.toml", "instance.json", "Color Settings.json", "app.ron"] {
|
||||
std::fs::write(private.join(name), b"saved profile data").unwrap();
|
||||
}
|
||||
for name in PROFILE_FOLDERS {
|
||||
std::fs::create_dir(private.join(name)).unwrap();
|
||||
}
|
||||
assert_eq!(fixture.check(platform, &private).unwrap(), private);
|
||||
assert_eq!(std::fs::read(private.join("config.toml")).unwrap(), b"saved profile data");
|
||||
for name in PROFILE_FOLDERS {
|
||||
let path = private.join(name);
|
||||
std::fs::remove_dir(&path).unwrap();
|
||||
std::fs::write(&path, b"not a directory").unwrap();
|
||||
assert!(fixture.check(platform, &private).is_err(), "{name} must stay a directory");
|
||||
std::fs::remove_file(&path).unwrap();
|
||||
std::fs::create_dir(&path).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_platform_case_rules_are_the_file_systems_ones() {
|
||||
let fixture = Fixture::new();
|
||||
let upper = fixture.root.join("NIGHTLY");
|
||||
assert!(fixture.check(Platform::Linux, &upper).is_ok());
|
||||
let stable_mac = fixture.home().join("library/application support/vectorcraft");
|
||||
assert!(fixture.check(Platform::Mac, &stable_mac).is_err(), "macOS compares folders case-insensitively");
|
||||
fn non_empty_abs_ignores_empty_and_relative_values() {
|
||||
let env = |key: &str| match key {
|
||||
"EMPTY" => Some(OsString::new()),
|
||||
"RELATIVE" => Some(OsString::from("relative/path")),
|
||||
_ => None,
|
||||
};
|
||||
assert!(super::non_empty_abs(&env, "EMPTY").is_none());
|
||||
assert!(super::non_empty_abs(&env, "RELATIVE").is_none());
|
||||
assert!(super::non_empty_abs(&env, "MISSING").is_none());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -155,8 +155,8 @@ pub fn launch_with_plug_ins(files: &[String]) -> io::Result<()> {
|
||||
}
|
||||
|
||||
/// The command [`launch_with_plug_ins`] runs: `exe -- files…`, so a file whose name starts with '-'
|
||||
/// stays a file. A nightly launch hands its profile on first (`launch_profile::child_args`), or the
|
||||
/// child would refuse to start without one.
|
||||
/// stays a file. A nightly launch hands its profile on first (`launch_profile::child_args`), so the
|
||||
/// child opens the same private profile.
|
||||
fn app_with_plug_ins(exe: &Path, files: &[String]) -> std::process::Command {
|
||||
let mut command = std::process::Command::new(exe);
|
||||
command.args(super::launch_profile::child_args(files));
|
||||
|
||||
+15
-11
@@ -2,6 +2,7 @@
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::ops::ControlFlow;
|
||||
use std::rc::Rc;
|
||||
use std::sync::{Arc, OnceLock};
|
||||
|
||||
@@ -403,6 +404,8 @@ thread_local! {
|
||||
thread_local! {
|
||||
/// How many objects' drawn art [`drawn`] evaluated on this thread.
|
||||
static DRAWN_EVALUATED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
/// How many times [`has_own_effects`] read an object's effects on this thread.
|
||||
static OWN_EFFECTS_READ: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// While a guard lives, [`drawn`] gives no art: the art it gave already has every geometry effect
|
||||
@@ -527,7 +530,7 @@ fn plain<T>(mask: bool, f: impl FnOnce() -> T) -> T {
|
||||
/// kept alone.
|
||||
fn drawn(symbols: &SymbolBoxes, n: &Node) -> Option<(Rc<Vec<Node>>, Option<Rect>)> {
|
||||
let f = DRAWN_ART.get()?;
|
||||
if DRAWN_OFF.get() || !evaluates(n) || !(has_own_effects(n) || draws_effects(symbols, n)) {
|
||||
if DRAWN_OFF.get() || !evaluates(n) || !draws_effects(symbols, n) {
|
||||
return None;
|
||||
}
|
||||
let doc = symbols.document();
|
||||
@@ -568,7 +571,7 @@ fn evaluates(n: &Node) -> bool {
|
||||
match &n.kind {
|
||||
NodeKind::Path { guide, .. } => !guide,
|
||||
NodeKind::Compound { .. } => true,
|
||||
NodeKind::Group { .. } | NodeKind::Layer { .. } => has_own_effects(n) || !n.appearance.items.is_empty(),
|
||||
NodeKind::Group { .. } | NodeKind::Layer { .. } => !n.appearance.items.is_empty() || has_own_effects(n),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
@@ -1188,23 +1191,24 @@ pub(crate) fn clip_region_inputs() -> (u64, bool) {
|
||||
/// Does `clip`, or anything it holds, have a visible effect of its own or on a fill or stroke? Only
|
||||
/// then can the registered [`ClipRegion`] find a geometry effect in it.
|
||||
fn has_effects(clip: &Node) -> bool {
|
||||
let mut found = false;
|
||||
clip.walk(&mut |n| found |= has_own_effects(n));
|
||||
found
|
||||
clip.try_walk(&mut |n| if has_own_effects(n) { ControlFlow::Break(()) } else { ControlFlow::Continue(()) }).is_break()
|
||||
}
|
||||
|
||||
/// Does `n`, anything it holds, or the art of a symbol an instance in it shows have a visible
|
||||
/// effect? Only then can the registered [`DrawnArt`] find a geometry effect in it.
|
||||
/// effect? Only then can the registered [`DrawnArt`] find a geometry effect in it. The walk starts
|
||||
/// at `n`, so its own effects are read once, here, and it ends at the first object with an effect.
|
||||
fn draws_effects(symbols: &SymbolBoxes, n: &Node) -> bool {
|
||||
let mut found = false;
|
||||
n.walk(&mut |c| {
|
||||
found = found || has_own_effects(c) || matches!(&c.kind, NodeKind::SymbolInstance { symbol, .. } if symbols.has_effects(symbol));
|
||||
});
|
||||
found
|
||||
n.try_walk(&mut |c| {
|
||||
let has = has_own_effects(c) || matches!(&c.kind, NodeKind::SymbolInstance { symbol, .. } if symbols.has_effects(symbol));
|
||||
if has { ControlFlow::Break(()) } else { ControlFlow::Continue(()) }
|
||||
})
|
||||
.is_break()
|
||||
}
|
||||
|
||||
/// Does `n` itself have a visible effect, of its own or on one of its own fills or strokes?
|
||||
fn has_own_effects(n: &Node) -> bool {
|
||||
#[cfg(test)]
|
||||
OWN_EFFECTS_READ.with(|c| c.set(c.get() + 1));
|
||||
let visible = |e: &crate::Effect| e.visible;
|
||||
n.appearance.effects.iter().any(visible) || n.appearance.items.iter().any(|i| i.effects().iter().any(visible))
|
||||
}
|
||||
|
||||
@@ -3652,6 +3652,48 @@ fn a_shaper_groups_original_shapes_in_symbol_art_are_not_picked() {
|
||||
assert_eq!(symbol_part_at(&d, n, Point::new(50.0, 50.0), opt), Some(vec![0, 1]), "over the shown face");
|
||||
}
|
||||
|
||||
/// A hover over empty canvas past many plain paths reads each path's effects once, and the layer's
|
||||
/// once.
|
||||
#[test]
|
||||
fn hovers_past_plain_paths_read_each_paths_effects_once() {
|
||||
set_drawn_art(shifted_art);
|
||||
let mut d = Document::new(1000.0, 1000.0);
|
||||
let l = d.layers[0].id;
|
||||
let paths = 100;
|
||||
for i in 0..paths {
|
||||
let n = square(&mut d, (i % 10) as f64 * 60.0, (i / 10) as f64 * 60.0);
|
||||
d.insert(Some(l), 0, n).unwrap();
|
||||
}
|
||||
let reads = || OWN_EFFECTS_READ.with(std::cell::Cell::get);
|
||||
let before = reads();
|
||||
assert!(hit_test(&d, Point::new(900.0, 900.0), HitOptions::default()).is_none());
|
||||
let read = reads() - before;
|
||||
assert_eq!(read, paths + 1, "each path's effects and the layer's are read once");
|
||||
assert!(hit_at(&d, 25.0, 25.0, HitOptions::default()).is_some(), "a square is still hit");
|
||||
}
|
||||
|
||||
/// Whether a compound clipping path, or a compound path, has a live effect is settled by the first
|
||||
/// object found with one: the members after it are not read.
|
||||
#[test]
|
||||
fn an_effect_on_a_compound_path_is_found_without_reading_its_members() {
|
||||
set_clip_region(moved_clip_region);
|
||||
set_drawn_art(shifted_art);
|
||||
let mut d = Document::new(1000.0, 1000.0);
|
||||
let members: Vec<_> = (0..100)
|
||||
.map(|i| Arc::new(Node::path(d.alloc_id(), shapes::rectangle(Rect::new(i as f64, 0.0, i as f64 + 5.0, 5.0)), Default::default())))
|
||||
.collect();
|
||||
let mut mask = Node::new(d.alloc_id(), NodeKind::Compound { children: members, rule: FillRule::NonZero });
|
||||
mask.appearance.effects.push(test_move());
|
||||
let reads = || OWN_EFFECTS_READ.with(std::cell::Cell::get);
|
||||
let before = reads();
|
||||
assert!(has_effects(&mask));
|
||||
assert_eq!(reads() - before, 1, "the clipping path's own effect ends the search");
|
||||
let symbols = d.symbol_boxes();
|
||||
let before = reads();
|
||||
assert!(draws_effects(&symbols, &mask));
|
||||
assert_eq!(reads() - before, 1, "the compound path's own effect ends the search");
|
||||
}
|
||||
|
||||
/// The pointer resting over empty canvas past many paths reads their anchors for their culling
|
||||
/// boxes on the first hover only: the next hovers use the boxes the paths keep.
|
||||
#[test]
|
||||
|
||||
@@ -308,16 +308,8 @@ fn resolve_kids(
|
||||
layout: &mut dyn FnMut(&mut TextObject),
|
||||
changed: &mut Vec<NodeId>,
|
||||
) -> Vec<(usize, Arc<Node>)> {
|
||||
let mut by_id: Option<HashMap<NodeId, &Arc<Node>>> = None;
|
||||
let mut out = vec![];
|
||||
for (i, c) in kids.iter().enumerate() {
|
||||
let o = old.and_then(|old| match old.get(i) {
|
||||
Some(b) if b.id == c.id => Some(b),
|
||||
_ => by_id.get_or_insert_with(|| old.iter().map(|b| (b.id, b)).collect()).get(&c.id).copied(),
|
||||
});
|
||||
if o.is_some_and(|o| Arc::ptr_eq(o, c)) {
|
||||
continue;
|
||||
}
|
||||
for (i, c, o) in crate::changed_nodes(old.unwrap_or_default(), kids) {
|
||||
let mut c = c.clone();
|
||||
if resolve_since(o.map(|o| &**o), &mut c, bounds, layout, changed) {
|
||||
out.push((i, c));
|
||||
|
||||
@@ -116,6 +116,7 @@ pub use live_paint::{GapOptions, GapSize};
|
||||
pub use metadata::{CopyrightStatus, DocMetadata};
|
||||
pub use node::Knockout;
|
||||
pub use node::Scaling;
|
||||
pub use node::changed_nodes;
|
||||
pub use node::{Extras, ExtrasMut, ImageObject, LAYER_COLORS, LayerColor, LiveShape, Node, NodeExtras, NodeId, NodeKind, OpacityMask};
|
||||
pub use node::{ForeignAttribute, ImageMap, MAX_SVG_SCRIPTS, MAX_TAG_TEXT, MAX_TAGS, ObjectAttributes, ObjectTag, SVG_EVENTS};
|
||||
pub use orient::OrientedBox;
|
||||
|
||||
@@ -15,6 +15,7 @@ use crate::symbols::{SYMBOL_SQUARE, SymbolBoxes};
|
||||
use crate::text::TextObject;
|
||||
|
||||
mod attributes;
|
||||
mod changed;
|
||||
mod clip;
|
||||
mod extras;
|
||||
mod ids;
|
||||
@@ -25,6 +26,9 @@ mod ops;
|
||||
mod wire;
|
||||
|
||||
pub use attributes::{ForeignAttribute, ImageMap, MAX_SVG_SCRIPTS, MAX_TAG_TEXT, MAX_TAGS, ObjectAttributes, ObjectTag, SVG_EVENTS};
|
||||
#[cfg(test)]
|
||||
pub(crate) use changed::COUNTERPART_LOOKUPS;
|
||||
pub use changed::changed_nodes;
|
||||
pub use clip::{ClipPaint, Uniter};
|
||||
pub use extras::{Extras, ExtrasMut, NodeExtras};
|
||||
pub use ids::{LAYER_COLORS, LayerColor, NodeId};
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
use super::{Arc, Node, NodeId};
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// Tests: how many nodes [`changed_nodes`] looked up a counterpart for on this thread.
|
||||
pub(crate) static COUNTERPART_LOOKUPS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// The nodes of `after` that are not the same nodes as their counterparts in `before` (the same
|
||||
/// list before an edit), with their positions in `after`. A node's counterpart is the node at the
|
||||
/// same position when it has the same id, else the node in `before` with its id, else `None` (the
|
||||
/// node is new). A node that is the same node as the one at its position in `before` is skipped
|
||||
/// without reading it, so a list of many unchanged nodes costs one pointer comparison per node.
|
||||
pub fn changed_nodes<'a>(before: &'a [Arc<Node>], after: &'a [Arc<Node>]) -> impl Iterator<Item = (usize, &'a Arc<Node>, Option<&'a Arc<Node>>)> {
|
||||
let mut by_id: Option<HashMap<NodeId, &'a Arc<Node>>> = None;
|
||||
after.iter().enumerate().filter_map(move |(i, a)| {
|
||||
if before.get(i).is_some_and(|b| Arc::ptr_eq(b, a)) {
|
||||
return None;
|
||||
}
|
||||
#[cfg(test)]
|
||||
COUNTERPART_LOOKUPS.with(|c| c.set(c.get() + 1));
|
||||
let b = match before.get(i) {
|
||||
Some(b) if b.id == a.id => Some(b),
|
||||
_ => by_id.get_or_insert_with(|| before.iter().map(|b| (b.id, b)).collect()).get(&a.id).copied(),
|
||||
};
|
||||
if b.is_some_and(|b| Arc::ptr_eq(b, a)) {
|
||||
return None;
|
||||
}
|
||||
Some((i, a, b))
|
||||
})
|
||||
}
|
||||
@@ -947,3 +947,37 @@ fn try_walk_ends_at_the_break() {
|
||||
assert_eq!(flow, ControlFlow::Break(NodeId(3)));
|
||||
assert_eq!(seen, [NodeId(1), NodeId(2), NodeId(3)]);
|
||||
}
|
||||
|
||||
/// After an edit of one node in a list of 1,000, `changed_nodes` gives that node and a new one
|
||||
/// with their counterparts, and looks a counterpart up for those two only: the 999 nodes that are
|
||||
/// the same nodes in the same places are passed over by their pointers.
|
||||
#[test]
|
||||
fn changed_nodes_looks_up_only_the_nodes_that_changed() {
|
||||
let leaf = |id| Arc::new(Node::group(NodeId(id), vec![]));
|
||||
let before: Vec<Arc<Node>> = (0..1000).map(leaf).collect();
|
||||
let mut after = before.clone();
|
||||
let mut edited = (*after[500]).clone();
|
||||
edited.name = Some("edited".into());
|
||||
after[500] = Arc::new(edited);
|
||||
after.push(leaf(5000));
|
||||
COUNTERPART_LOOKUPS.with(|c| c.set(0));
|
||||
let changed: Vec<_> = changed_nodes(&before, &after).map(|(i, a, b)| (i, a.id, b.map(|b| b.id))).collect();
|
||||
assert_eq!(changed, [(500, NodeId(500), Some(NodeId(500))), (1000, NodeId(5000), None)]);
|
||||
assert_eq!(COUNTERPART_LOOKUPS.with(|c| c.get()), 2);
|
||||
}
|
||||
|
||||
/// A node that moved to another place in the list is paired with itself by its id and left out
|
||||
/// when it is the same node; a changed node that moved is paired with its old node, and a node
|
||||
/// that is gone from the list gives nothing.
|
||||
#[test]
|
||||
fn changed_nodes_pairs_moved_nodes_by_id() {
|
||||
let leaf = |id| Arc::new(Node::group(NodeId(id), vec![]));
|
||||
let before = vec![leaf(1), leaf(2), leaf(3), leaf(4)];
|
||||
let mut edited = (*before[0]).clone();
|
||||
edited.locked = true;
|
||||
let after = vec![Arc::clone(&before[2]), Arc::clone(&before[1]), Arc::new(edited)];
|
||||
let changed: Vec<_> = changed_nodes(&before, &after).map(|(i, a, b)| (i, a.id, b.map(|b| b.id))).collect();
|
||||
assert_eq!(changed, [(2, NodeId(1), Some(NodeId(1)))]);
|
||||
assert!(changed_nodes(&[], &after).map(|(_, _, b)| b).all(|b| b.is_none()), "every node is new against an empty list");
|
||||
assert_eq!(changed_nodes(&[], &after).count(), 3);
|
||||
}
|
||||
|
||||
@@ -3,7 +3,8 @@
|
||||
//! row or a column with a set gap, the first staying in place; Swap Objects swaps the places (and sizes) of two;
|
||||
//! Replace with Top Object puts a copy of the topmost selected object in place of each of the
|
||||
//! others; and Set Size of Each gives every selected object an exact width and height. Places and
|
||||
//! sizes are measured and set as `object.setBounds` does. Group Overlapping Objects groups the
|
||||
//! sizes are measured and set as `object.setBounds` does. Match Objects gives the other selected
|
||||
//! objects the size, bounding-box angle and stacking place of one of them. Group Overlapping Objects groups the
|
||||
//! objects whose visual bounds overlap, Randomize Opacity gives each selected object a random
|
||||
//! opacity, and Sort Objects sorts the selected objects by one attribute and gives them another in
|
||||
//! that order. Its submenu (Object › Plug-ins › Arrange Tools), its dialogs and Zoom to Selection
|
||||
@@ -89,6 +90,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_selection,
|
||||
size
|
||||
),
|
||||
cmd!(
|
||||
"addon.arrange.match",
|
||||
"Match Objects",
|
||||
["Object", "Plug-ins", "Arrange Tools"],
|
||||
None,
|
||||
"{source?: \"key\" (the key object, select.key) | \"top\" (the frontmost selected object) | \"bottom\" (the backmost) (default: the key object when the selection has one, else \"top\"), size?: \"none\" | \"width\" (each target takes the source's width, its height following in proportion) | \"height\" (the source's height, the width following in proportion) | \"both\" (the source's width and height, each on its own) (\"none\"), rotate?: false (true: each target takes the source's bounding-box angle, measured counter-clockwise, turning the shorter way, at most 180°), stacking?: false (true: the targets go directly above the source in the stacking order, in its layer or group, in the order they had), reference?: 0..8 (the 9-point grid row by row from the top-left; 4, the center: the point of each target that stays put as it is sized and turned), scaleStrokes?: the Scale Strokes & Effects preference, patterns?: the Transform Pattern Tiles preference (at least one of size, rotate and stacking)} make the other selected objects (the top-level ones, at most 20000) match the source, which stays as it is, as one undo step (none when nothing changes). Sizes are measured and set as object.setBounds measures them (Use Preview Bounds), each in the object's own bounding-box frame, and a size that a target has no width or height to take is refused, as is a stacking match that would move a clipping path; to match places, use object.align {to: \"key\"} → {source, count}",
|
||||
has_multi,
|
||||
match_objects
|
||||
),
|
||||
cmd!(
|
||||
"addon.arrange.groupOverlapping",
|
||||
"Group Overlapping Objects",
|
||||
@@ -177,6 +187,14 @@ fn transform_each(s: &mut Session, label: &str, strokes: bool, xfs: &[(NodeId, A
|
||||
})
|
||||
}
|
||||
|
||||
/// The `scaleStrokes` param, else the Scale Strokes & Effects preference. The value joins the
|
||||
/// command's journal entry, so replaying it scales the same way whatever the preference is then.
|
||||
fn scale_strokes(s: &mut Session, p: &Value, cmd: &str) -> Result<bool> {
|
||||
let on = switch_or(p, "scaleStrokes", s.prefs.scale_strokes, cmd)?;
|
||||
s.note_journal("scaleStrokes", json!(on));
|
||||
Ok(on)
|
||||
}
|
||||
|
||||
/// The box of object `id` as `object.setBounds` measures it.
|
||||
fn box_of(s: &Session, id: NodeId) -> Result<OrientedBox> {
|
||||
s.transform_box(&[id]).ok_or_else(|| EngineError::Other("no bounds".into()))
|
||||
@@ -277,7 +295,7 @@ fn offset(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
fn swap(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "addon.arrange.swap";
|
||||
let size = switch_or(p, "size", false, C)?;
|
||||
let strokes = switch_or(p, "scaleStrokes", s.prefs.scale_strokes, C)?;
|
||||
let strokes = scale_strokes(s, p, C)?;
|
||||
let roots = selected_roots(s)?;
|
||||
let &[a, b] = roots.as_slice() else { return Err(bad(C, "select exactly two objects")) };
|
||||
let (ba, bb) = (box_of(s, a)?, box_of(s, b)?);
|
||||
@@ -290,7 +308,7 @@ fn swap(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
fn replace(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "addon.arrange.replace";
|
||||
let fit = choice(p, C, "fit", &["keep", "bounds", "proportional"])?.unwrap_or("keep");
|
||||
let strokes = switch_or(p, "scaleStrokes", s.prefs.scale_strokes, C)?;
|
||||
let strokes = scale_strokes(s, p, C)?;
|
||||
let keep = switch_or(p, "keep", false, C)?;
|
||||
let roots = selected_roots(s)?;
|
||||
let Some((&top, others)) = roots.split_last().filter(|(_, others)| !others.is_empty()) else {
|
||||
@@ -341,7 +359,7 @@ fn size(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let proportional = switch_or(p, "proportional", false, C)?;
|
||||
let reference = whole_in(p, "reference", (0, 8), C)?.unwrap_or(4);
|
||||
let strokes = switch_or(p, "scaleStrokes", s.prefs.scale_strokes, C)?;
|
||||
let strokes = scale_strokes(s, p, C)?;
|
||||
let mut q = json!({ "reference": reference, "strokes": strokes, "proportional": proportional && (width.is_none() || height.is_none()) });
|
||||
if let Some(w) = width {
|
||||
q["width"] = json!(w);
|
||||
@@ -359,6 +377,158 @@ fn size(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "count": xfs.len() }))
|
||||
}
|
||||
|
||||
/// The source Match Objects matches `roots` (the selected roots, in stacking order) to, from its
|
||||
/// `source` param: the selected root that is the key object or holds it, the frontmost or the backmost.
|
||||
fn match_source(s: &Session, p: &Value, roots: &[NodeId], cmd: &str) -> Result<NodeId> {
|
||||
let st = s.doc()?;
|
||||
let key = st.selection.key.and_then(|k| st.doc.ancestry(k)).and_then(|up| roots.iter().copied().find(|id| up.contains(id)));
|
||||
let picked = match choice(p, cmd, "source", &["key", "top", "bottom"])? {
|
||||
Some("key") => Some(key.ok_or_else(|| bad(cmd, "no key object: set one with select.key"))?),
|
||||
Some("bottom") => roots.first().copied(),
|
||||
Some(_) => roots.last().copied(),
|
||||
None => key.or_else(|| roots.last().copied()),
|
||||
};
|
||||
picked.ok_or_else(|| bad(cmd, "select at least two objects"))
|
||||
}
|
||||
|
||||
/// Whether `targets` (in stacking order) are directly above `source` in its layer or group, in that order.
|
||||
fn stacked_above(d: &vectorcraft_doc::Document, source: NodeId, targets: &[NodeId]) -> bool {
|
||||
let paths = d.index_paths(targets.iter().copied().chain([source]));
|
||||
let Some((&at, up)) = paths.get(&source).and_then(|p| p.split_last()) else { return false };
|
||||
targets.iter().enumerate().all(|(i, id)| paths.get(id).and_then(|p| p.split_last()) == Some((&(at + 1 + i), up)))
|
||||
}
|
||||
|
||||
fn match_objects(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "addon.arrange.match";
|
||||
let size = choice(p, C, "size", &["none", "width", "height", "both"])?.unwrap_or("none");
|
||||
let rotate = switch_or(p, "rotate", false, C)?;
|
||||
let stacking = switch_or(p, "stacking", false, C)?;
|
||||
let reference = whole_in(p, "reference", (0, 8), C)?.unwrap_or(4);
|
||||
let strokes = scale_strokes(s, p, C)?;
|
||||
let patterns = switch_or(p, "patterns", s.prefs.transform_pattern_tiles, C)?;
|
||||
if size == "none" && !rotate && !stacking {
|
||||
return Err(bad(C, "give `size`, `rotate` or `stacking`"));
|
||||
}
|
||||
let roots = selected_roots(s)?;
|
||||
if roots.len() > MAX_OBJECTS {
|
||||
return Err(bad(C, "too many objects selected (at most 20000)"));
|
||||
}
|
||||
let source = match_source(s, p, &roots, C)?;
|
||||
let targets: Vec<NodeId> = roots.iter().copied().filter(|id| *id != source).collect();
|
||||
if targets.is_empty() {
|
||||
return Err(bad(C, "select at least two objects"));
|
||||
}
|
||||
// Only sizing measures the source; a stacking or rotate match doesn't need its bounds.
|
||||
let (w, h) = if size == "none" {
|
||||
(0.0, 0.0)
|
||||
} else {
|
||||
let sb = box_of(s, source)?;
|
||||
(sb.rect.width(), sb.rect.height())
|
||||
};
|
||||
let wanted = match size {
|
||||
"width" if w < LEAST => return Err(bad(C, "the source object has no width")),
|
||||
"height" if h < LEAST => return Err(bad(C, "the source object has no height")),
|
||||
"both" if w < LEAST || h < LEAST => return Err(bad(C, "the source object has no width or no height")),
|
||||
"width" => Some(json!({ "width": w, "proportional": true })),
|
||||
"height" => Some(json!({ "height": h, "proportional": true })),
|
||||
"both" => Some(json!({ "width": w, "height": h })),
|
||||
_ => None,
|
||||
};
|
||||
let angle = s.doc()?.doc.bbox_angle(&[source]);
|
||||
let mut xfs = Vec::with_capacity(targets.len());
|
||||
for &id in &targets {
|
||||
let turn = if rotate { vectorcraft_geom::normalize_deg(angle - s.doc()?.doc.bbox_angle(&[id])) } else { 0.0 };
|
||||
let Some(b) = s.transform_box(&[id]) else {
|
||||
if wanted.is_some() {
|
||||
return Err(bad(C, format!("object {} has no bounds to size", id.0)));
|
||||
}
|
||||
if turn.abs() > 1e-9 {
|
||||
return Err(bad(C, format!("object {} has no bounds to rotate", id.0)));
|
||||
}
|
||||
continue;
|
||||
};
|
||||
let mut xf = Affine::IDENTITY;
|
||||
if let Some(q) = &wanted {
|
||||
let mut q = q.clone();
|
||||
q["reference"] = json!(reference);
|
||||
q["strokes"] = json!(strokes);
|
||||
xf = object_bounds_transform(s, &q, id)?;
|
||||
}
|
||||
if turn.abs() > 1e-9 {
|
||||
// Rotation uses the reference point that sizing keeps in place.
|
||||
let at = b.to_doc() * vectorcraft_geom::reference_point(b.rect, reference as usize);
|
||||
xf = Affine::rotate_about(-turn.to_radians(), at) * xf;
|
||||
}
|
||||
if wanted.is_some() {
|
||||
let sc = scaling(s, &json!({ "strokes": strokes }));
|
||||
let d = &s.doc()?.doc;
|
||||
let symbols = d.symbol_boxes();
|
||||
let measure = |xf| {
|
||||
d.node(id).and_then(|n| {
|
||||
let mut n = n.clone();
|
||||
transform_node(&mut n, xf, sc, true);
|
||||
let frame = OrientedBox { angle: n.bbox_angle, rect: Rect::ZERO };
|
||||
effects::preview::bounds_in_with(&symbols, &n, frame.to_doc().inverse(), s.bounds_measure())
|
||||
})
|
||||
};
|
||||
let misses = |measured: Option<Rect>| {
|
||||
measured.is_none_or(|r| match size {
|
||||
"width" => (r.width() - w).abs() > 1e-6,
|
||||
"height" => (r.height() - h).abs() > 1e-6,
|
||||
_ => (r.width() - w).abs() > 1e-6 || (r.height() - h).abs() > 1e-6,
|
||||
})
|
||||
};
|
||||
// The sized and turned object, measured in its final frame, must have the size asked for.
|
||||
if misses(measure(xf)) {
|
||||
return Err(bad(C, format!("object {} can't take the requested size", id.0)));
|
||||
}
|
||||
}
|
||||
xfs.push((id, xf));
|
||||
}
|
||||
let still = |xf: &Affine| xf.as_coeffs().iter().zip(Affine::IDENTITY.as_coeffs()).all(|(a, b)| (a - b).abs() <= 1e-9);
|
||||
xfs.retain(|(_, xf)| !still(xf));
|
||||
let restack = stacking && !stacked_above(&s.doc()?.doc, source, &targets);
|
||||
let (mut placed, mut left) = (vec![], vec![]);
|
||||
if restack {
|
||||
let d = &s.doc()?.doc;
|
||||
// In a clip group or a clipping layer the bottom child is the clipping path: it stays there.
|
||||
let is_clip =
|
||||
|id: &NodeId| d.position(*id).is_some_and(|(_, idx, _)| idx == 0) && d.parent_of(*id).and_then(|p| d.node(p)).is_some_and(Node::clips);
|
||||
if targets.iter().any(is_clip) {
|
||||
return Err(bad(C, "a clipping path can't change its place in the stacking order"));
|
||||
}
|
||||
let parent = d.parent_of(source);
|
||||
if let Some(what) = targets.iter().filter_map(|id| d.node(*id)).find_map(|n| crate::cmd::intertwine::refused_in(d, parent, n)) {
|
||||
return Err(bad(C, format!("{what} can't be intertwined")));
|
||||
}
|
||||
placed = targets.iter().map(|i| (*i, d.parent_of(*i))).collect::<Vec<(NodeId, Option<NodeId>)>>();
|
||||
left = crate::cmd::intertwine::groups_of(d, &targets);
|
||||
}
|
||||
let count = json!({ "source": source.0, "count": targets.len() });
|
||||
if xfs.is_empty() && !restack {
|
||||
return Ok(count);
|
||||
}
|
||||
let q = json!({ "strokes": strokes, "patterns": patterns });
|
||||
let ids: Vec<NodeId> = xfs.iter().map(|(id, _)| *id).collect();
|
||||
let mut sc = scaling(s, &q);
|
||||
sc.patterns = transform_patterns(s, &q, &ids)?;
|
||||
s.edit("Match Objects", |d, _| {
|
||||
for (id, xf) in &xfs {
|
||||
if let Some(n) = d.node_mut(*id) {
|
||||
transform_node(n, *xf, sc, true);
|
||||
}
|
||||
}
|
||||
if restack {
|
||||
let moved = d.remove_many(&targets)?;
|
||||
d.insert_beside(vec![(source, moved.into_iter().map(Arc::unwrap_or_clone).collect())], false)?;
|
||||
// Targets moved out of an Intertwine group leave it as ordinary art.
|
||||
crate::cmd::intertwine::settle_members(d, &placed, &left)?;
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(count)
|
||||
}
|
||||
|
||||
/// The sets of two or more of `items` (each in the order given) whose rects overlap or touch,
|
||||
/// chains included, among items of the same key (parent). A sweep along x: only the rects still
|
||||
/// open where each one starts are compared with it.
|
||||
@@ -505,7 +675,7 @@ fn sort(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let order = choice(p, C, "order", &["ascending", "descending", "random"])?.unwrap_or("ascending");
|
||||
let distribute = switch_or(p, "distribute", false, C)?;
|
||||
let mut rng = Rng::new(whole_or(p, "seed", 0, C)?);
|
||||
let strokes = switch_or(p, "scaleStrokes", s.prefs.scale_strokes, C)?;
|
||||
let strokes = scale_strokes(s, p, C)?;
|
||||
let ids = checked_ids_or_selection(s, p, C)?;
|
||||
if ids.len() > MAX_OBJECTS {
|
||||
return Err(bad(C, "too many objects selected (at most 20000)"));
|
||||
|
||||
@@ -343,6 +343,394 @@ fn size_gives_each_object_a_width_and_height() {
|
||||
assert!(near(bounds(&s, a), (30.0, 8.0, 10.0, 12.0)), "both given: both set, {:?}", bounds(&s, a));
|
||||
}
|
||||
|
||||
/// Three rectangles from the back, all selected: `a` 20 × 10 at the origin, `b` 40 × 40 at
|
||||
/// (100, 100) and `c` 10 × 30 at (200, 0).
|
||||
fn three(s: &mut Session) -> (NodeId, NodeId, NodeId) {
|
||||
let a = rect(s, 0.0, 0.0, 20.0, 10.0);
|
||||
let b = rect(s, 100.0, 100.0, 40.0, 40.0);
|
||||
let c = rect(s, 200.0, 0.0, 10.0, 30.0);
|
||||
select(s, &[a, b, c]);
|
||||
(a, b, c)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_gives_the_others_the_key_objects_size() {
|
||||
let mut s = session();
|
||||
let (a, b, c) = three(&mut s);
|
||||
s.execute("select.key", &json!({"id": b.0})).unwrap();
|
||||
let n = steps(&s);
|
||||
let r = s.execute("addon.arrange.match", &json!({"size": "both"})).unwrap();
|
||||
assert_eq!(r, json!({"source": b.0, "count": 2}));
|
||||
assert_eq!(steps(&s), n + 1, "one undo step");
|
||||
// About each center; the key object stays.
|
||||
assert!(near(bounds(&s, a), (-10.0, -15.0, 40.0, 40.0)), "{:?}", bounds(&s, a));
|
||||
assert!(near(bounds(&s, c), (185.0, -5.0, 40.0, 40.0)), "{:?}", bounds(&s, c));
|
||||
assert!(near(bounds(&s, b), (100.0, 100.0, 40.0, 40.0)), "{:?}", bounds(&s, b));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(near(bounds(&s, a), (0.0, 0.0, 20.0, 10.0)));
|
||||
// The width, with the height in proportion, about the top-left corner.
|
||||
s.execute("addon.arrange.match", &json!({"size": "width", "reference": 0})).unwrap();
|
||||
assert!(near(bounds(&s, a), (0.0, 0.0, 40.0, 20.0)), "{:?}", bounds(&s, a));
|
||||
assert!(near(bounds(&s, c), (200.0, 0.0, 40.0, 120.0)), "{:?}", bounds(&s, c));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("addon.arrange.match", &json!({"size": "height", "reference": 8})).unwrap();
|
||||
assert!(near(bounds(&s, a), (-60.0, -30.0, 80.0, 40.0)), "{:?}", bounds(&s, a));
|
||||
assert!(near(bounds(&s, c), (196.6666666666667, -10.0, 13.333333333333334, 40.0)), "{:?}", bounds(&s, c));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_takes_the_top_or_the_bottom_object_without_a_key() {
|
||||
let mut s = session();
|
||||
let (a, b, c) = three(&mut s);
|
||||
// No key object: the frontmost, c.
|
||||
let r = s.execute("addon.arrange.match", &json!({"size": "both"})).unwrap();
|
||||
assert_eq!(r["source"], json!(c.0));
|
||||
assert!(near(bounds(&s, a), (5.0, -10.0, 10.0, 30.0)), "{:?}", bounds(&s, a));
|
||||
assert!(near(bounds(&s, b), (115.0, 105.0, 10.0, 30.0)), "{:?}", bounds(&s, b));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
let r = s.execute("addon.arrange.match", &json!({"source": "bottom", "size": "both"})).unwrap();
|
||||
assert_eq!(r["source"], json!(a.0));
|
||||
assert!(near(bounds(&s, b), (110.0, 115.0, 20.0, 10.0)), "{:?}", bounds(&s, b));
|
||||
assert!(near(bounds(&s, c), (195.0, 10.0, 20.0, 10.0)), "{:?}", bounds(&s, c));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
// "top" names the frontmost even while a key object is set.
|
||||
s.execute("select.key", &json!({"id": a.0})).unwrap();
|
||||
let r = s.execute("addon.arrange.match", &json!({"source": "top", "size": "both"})).unwrap();
|
||||
assert_eq!(r["source"], json!(c.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_turns_the_others_to_the_sources_angle() {
|
||||
let mut s = session();
|
||||
let (a, b, c) = three(&mut s);
|
||||
select(&mut s, &[b]);
|
||||
s.execute("object.rotate", &json!({"angle": 30})).unwrap();
|
||||
select(&mut s, &[a, b, c]);
|
||||
s.execute("select.key", &json!({"id": b.0})).unwrap();
|
||||
let n = steps(&s);
|
||||
s.execute("addon.arrange.match", &json!({"rotate": true, "size": "both"})).unwrap();
|
||||
assert_eq!(steps(&s), n + 1, "one undo step");
|
||||
for (id, center) in [(a, (10.0, 5.0)), (c, (205.0, 15.0))] {
|
||||
let o = s.transform_box(&[id]).unwrap();
|
||||
assert!((o.angle - 30.0).abs() < 1e-6, "{id:?} turned to {}", o.angle);
|
||||
assert!((o.rect.width() - 40.0).abs() < 1e-6 && (o.rect.height() - 40.0).abs() < 1e-6, "{id:?} sized {:?}", o.rect);
|
||||
let at = o.center();
|
||||
assert!((at.x - center.0).abs() < 1e-6 && (at.y - center.1).abs() < 1e-6, "{id:?} turned about its center: {at:?}");
|
||||
}
|
||||
// Turned back to the angle of an unturned source.
|
||||
let d = rect(&mut s, 300.0, 0.0, 10.0, 10.0);
|
||||
select(&mut s, &[a, d]);
|
||||
s.execute("addon.arrange.match", &json!({"rotate": true, "source": "top"})).unwrap();
|
||||
assert!(s.transform_box(&[a]).unwrap().angle.abs() < 1e-6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_size_and_rotation_measure_pixel_aligned_art_in_its_final_frame() {
|
||||
for size in ["width", "height", "both"] {
|
||||
let mut s = session();
|
||||
let target = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
|
||||
select(&mut s, &[target]);
|
||||
s.execute("object.setPixelAligned", &json!({"on": true})).unwrap();
|
||||
let source = rect(&mut s, 100.0, 0.0, 10.5, 10.5);
|
||||
select(&mut s, &[source]);
|
||||
s.execute("object.rotate", &json!({"angle": 30})).unwrap();
|
||||
let wanted = s.transform_box(&[source]).unwrap();
|
||||
select(&mut s, &[target, source]);
|
||||
s.execute("select.key", &json!({"id": source.0})).unwrap();
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let n = steps(&s);
|
||||
let r = s.execute("addon.arrange.match", &json!({"size": size, "rotate": true})).unwrap();
|
||||
assert_eq!(r, json!({"source": source.0, "count": 1}));
|
||||
let measured = s.transform_box(&[target]).unwrap();
|
||||
assert!((measured.angle - wanted.angle).abs() < 1e-6, "{size}: {measured:?}");
|
||||
assert!((measured.rect.width() - wanted.rect.width()).abs() < 1e-6, "{size}: {measured:?}");
|
||||
assert!((measured.rect.height() - wanted.rect.height()).abs() < 1e-6, "{size}: {measured:?}");
|
||||
assert_eq!(steps(&s), n + 1);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(*s.doc().unwrap().doc == *before);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_rotation_refuses_a_target_without_bounds_when_its_angle_differs() {
|
||||
for angle in [0, 30] {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
|
||||
let target = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
select(&mut s, &[a]);
|
||||
s.execute("edit.clear", &json!({})).unwrap();
|
||||
let b = rect(&mut s, 100.0, 0.0, 10.0, 10.0);
|
||||
let source = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("object.rotate", &json!({"angle": angle})).unwrap();
|
||||
select(&mut s, &[b]);
|
||||
s.execute("edit.clear", &json!({})).unwrap();
|
||||
assert!(s.transform_box(&[target]).is_none());
|
||||
assert!(s.transform_box(&[source]).is_none());
|
||||
assert!((s.doc().unwrap().doc.bbox_angle(&[source]) - f64::from(angle)).abs() < 1e-6);
|
||||
select(&mut s, &[target, source]);
|
||||
s.execute("select.key", &json!({"id": source.0})).unwrap();
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let n = steps(&s);
|
||||
let result = s.execute("addon.arrange.match", &json!({"rotate": true}));
|
||||
if angle == 0 {
|
||||
assert_eq!(result.unwrap(), json!({"source": source.0, "count": 1}));
|
||||
} else {
|
||||
let error = result.unwrap_err().to_string();
|
||||
assert!(error.contains(&format!("object {} has no bounds to rotate", target.0)), "{error}");
|
||||
}
|
||||
assert_eq!(steps(&s), n);
|
||||
assert!(*s.doc().unwrap().doc == *before);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_puts_the_others_directly_above_the_source() {
|
||||
let mut s = session();
|
||||
let (a, b, c) = three(&mut s);
|
||||
let d = rect(&mut s, 300.0, 0.0, 10.0, 10.0);
|
||||
select(&mut s, &[d, a, c]);
|
||||
s.execute("select.key", &json!({"id": a.0})).unwrap();
|
||||
let n = steps(&s);
|
||||
s.execute("addon.arrange.match", &json!({"stacking": true})).unwrap();
|
||||
assert_eq!(steps(&s), n + 1, "one undo step");
|
||||
assert_eq!(layer_order(&s), [a, c, d, b], "in the order they had, above the key object");
|
||||
assert!(near(bounds(&s, c), (200.0, 0.0, 10.0, 30.0)), "nothing else changes");
|
||||
s.execute("addon.arrange.match", &json!({"stacking": true})).unwrap();
|
||||
assert_eq!(steps(&s), n + 1, "already above it: no step");
|
||||
// An object in another layer goes into the source's.
|
||||
s.execute("layer.new", &json!({})).unwrap();
|
||||
let e = rect(&mut s, 0.0, 200.0, 10.0, 10.0);
|
||||
select(&mut s, &[b, e]);
|
||||
s.execute("select.key", &json!({"id": b.0})).unwrap();
|
||||
s.execute("addon.arrange.match", &json!({"stacking": true})).unwrap();
|
||||
assert_eq!(layer_order(&s), [a, c, d, b, e]);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(layer_order(&s), [a, c, d, b]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_makes_no_step_when_everything_matches() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 20.0, 10.0);
|
||||
let b = rect(&mut s, 100.0, 100.0, 20.0, 10.0);
|
||||
select(&mut s, &[a, b]);
|
||||
let n = steps(&s);
|
||||
let r = s.execute("addon.arrange.match", &json!({"size": "both", "rotate": true})).unwrap();
|
||||
assert_eq!(r["count"], json!(1));
|
||||
assert_eq!(steps(&s), n, "the same size and angle: no step");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_turns_the_others_about_their_reference_point() {
|
||||
let mut s = session();
|
||||
let (a, b, c) = three(&mut s);
|
||||
select(&mut s, &[b]);
|
||||
s.execute("object.rotate", &json!({"angle": 30})).unwrap();
|
||||
select(&mut s, &[a, b, c]);
|
||||
s.execute("select.key", &json!({"id": b.0})).unwrap();
|
||||
s.execute("addon.arrange.match", &json!({"rotate": true, "reference": 0})).unwrap();
|
||||
// Each top-left corner stays where it was.
|
||||
for (id, corner) in [(a, (0.0, 0.0)), (c, (200.0, 0.0))] {
|
||||
let o = s.transform_box(&[id]).unwrap();
|
||||
assert!((o.angle - 30.0).abs() < 1e-6, "{id:?} turned to {}", o.angle);
|
||||
let at = o.to_doc() * vectorcraft_geom::reference_point(o.rect, 0);
|
||||
assert!((at.x - corner.0).abs() < 1e-6 && (at.y - corner.1).abs() < 1e-6, "{id:?} turned about its top-left corner: {at:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_scales_strokes_as_asked() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
|
||||
let b = rect(&mut s, 100.0, 0.0, 20.0, 20.0);
|
||||
select(&mut s, &[a, b]);
|
||||
s.execute("paint.setStroke", &json!({"color": "#000000"})).unwrap();
|
||||
s.execute("stroke.set", &json!({"weight": 2})).unwrap();
|
||||
let weight = |s: &Session, id| s.doc().unwrap().doc.node(id).unwrap().appearance.stroke_width();
|
||||
s.execute("addon.arrange.match", &json!({"size": "both"})).unwrap();
|
||||
assert_eq!(weight(&s, a), 2.0, "off by default (the preference)");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("addon.arrange.match", &json!({"size": "both", "scaleStrokes": true})).unwrap();
|
||||
assert!((weight(&s, a) - 4.0).abs() < 1e-9, "{}", weight(&s, a));
|
||||
assert!(near(bounds(&s, a), (-5.0, -5.0, 20.0, 20.0)), "{:?}", bounds(&s, a));
|
||||
}
|
||||
|
||||
/// Running `cmd` with Scale Strokes & Effects on doubles the 2 pt stroke of a 10 pt square, and
|
||||
/// replaying its journal entry after the preference is turned off scales the stroke the same way.
|
||||
fn replays_the_stroke_scaling_it_ran_with(cmd: &str, p: Value) {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
|
||||
let b = rect(&mut s, 100.0, 0.0, 20.0, 20.0);
|
||||
select(&mut s, &[a, b]);
|
||||
s.execute("paint.setStroke", &json!({"color": "#000000"})).unwrap();
|
||||
s.execute("stroke.set", &json!({"weight": 2})).unwrap();
|
||||
let weight = |s: &Session| s.doc().unwrap().doc.node(a).unwrap().appearance.stroke_width();
|
||||
s.execute("prefs.set", &json!({"key": "scaleStrokes", "value": true})).unwrap();
|
||||
s.execute(cmd, &p).unwrap();
|
||||
assert!((weight(&s) - 4.0).abs() < 1e-9, "{cmd}: {}", weight(&s));
|
||||
let (id, q) = s.journal.last().unwrap().clone();
|
||||
assert_eq!(id, cmd);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("prefs.set", &json!({"key": "scaleStrokes", "value": false})).unwrap();
|
||||
select(&mut s, &[a, b]);
|
||||
s.replay(&id, &q).unwrap();
|
||||
assert!((weight(&s) - 4.0).abs() < 1e-9, "{cmd} replayed: {}", weight(&s));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_stacking_leaves_a_clipping_path_in_place() {
|
||||
let mut s = session();
|
||||
let art = rect(&mut s, 0.0, 0.0, 40.0, 40.0);
|
||||
let mask = rect(&mut s, 10.0, 10.0, 10.0, 10.0);
|
||||
select(&mut s, &[art, mask]);
|
||||
s.execute("object.clippingMask.make", &json!({})).unwrap();
|
||||
let x = rect(&mut s, 200.0, 0.0, 10.0, 10.0);
|
||||
select(&mut s, &[mask, x]);
|
||||
s.execute("select.key", &json!({"id": x.0})).unwrap();
|
||||
refuses(&mut s, "addon.arrange.match", &[json!({"stacking": true})]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_size_refuses_a_target_with_no_width() {
|
||||
let mut s = session();
|
||||
let line = NodeId(s.execute("shape.line", &json!({"x1": 0, "y1": 0, "x2": 0, "y2": 50})).unwrap()["id"].as_u64().unwrap());
|
||||
let b = rect(&mut s, 100.0, 0.0, 20.0, 20.0);
|
||||
select(&mut s, &[line, b]);
|
||||
s.execute("select.key", &json!({"id": b.0})).unwrap();
|
||||
refuses(&mut s, "addon.arrange.match", &[json!({"size": "width"}), json!({"size": "both"})]);
|
||||
// Its height can still take the source's.
|
||||
s.execute("addon.arrange.match", &json!({"size": "height"})).unwrap();
|
||||
assert!((bounds(&s, line).height() - 20.0).abs() < 1e-6, "{:?}", bounds(&s, line));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_size_uses_preview_bounds_for_a_target_with_no_geometric_width() {
|
||||
let mut s = session();
|
||||
s.execute("prefs.set", &json!({"key": "usePreviewBounds", "value": true})).unwrap();
|
||||
let line = NodeId(s.execute("shape.line", &json!({"x1": 0, "y1": 0, "x2": 0, "y2": 50})).unwrap()["id"].as_u64().unwrap());
|
||||
select(&mut s, &[line]);
|
||||
s.execute("paint.setStroke", &json!({"color": "#000000"})).unwrap();
|
||||
s.execute("stroke.set", &json!({"weight": 2, "cap": "butt"})).unwrap();
|
||||
let b = rect(&mut s, 100.0, 0.0, 2.0, 100.0);
|
||||
select(&mut s, &[b]);
|
||||
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
|
||||
select(&mut s, &[line, b]);
|
||||
s.execute("select.key", &json!({"id": b.0})).unwrap();
|
||||
s.execute("addon.arrange.match", &json!({"size": "both", "scaleStrokes": false})).unwrap();
|
||||
let measured = s.transform_box(&[line]).unwrap().rect;
|
||||
let wanted = s.transform_box(&[b]).unwrap().rect;
|
||||
assert!((measured.width() - wanted.width()).abs() < 1e-6, "{measured:?}");
|
||||
assert!((measured.height() - wanted.height()).abs() < 1e-6, "{measured:?}");
|
||||
select(&mut s, &[b]);
|
||||
s.execute("object.setBounds", &json!({"width": 4})).unwrap();
|
||||
select(&mut s, &[line, b]);
|
||||
s.execute("select.key", &json!({"id": b.0})).unwrap();
|
||||
refuses(&mut s, "addon.arrange.match", &[json!({"size": "both", "scaleStrokes": false})]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_stacking_takes_a_member_out_of_its_intertwine_group() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 40.0, 40.0);
|
||||
let b = rect(&mut s, 20.0, 20.0, 40.0, 40.0);
|
||||
select(&mut s, &[a, b]);
|
||||
let g = NodeId(s.execute("object.intertwine.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("object.intertwine.arrange", &json!({"at": [30, 30], "order": "front", "member": a.0})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.node(a).unwrap().extras().intertwine.is_some(), "a is drawn over b in their overlap");
|
||||
let c = rect(&mut s, 200.0, 0.0, 10.0, 10.0);
|
||||
select(&mut s, &[a, c]);
|
||||
s.execute("select.key", &json!({"id": c.0})).unwrap();
|
||||
s.execute("addon.arrange.match", &json!({"stacking": true})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_ne!(d.parent_of(a), Some(g), "a left the Intertwine group");
|
||||
let e = d.node(a).unwrap().extras();
|
||||
assert!(e.intertwine.is_none() && e.intertwine_tiers.is_empty(), "a keeps no Intertwine areas");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(a), Some(g), "undo puts a back in its group");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_stacking_needs_no_bounds_on_the_source() {
|
||||
let mut s = session();
|
||||
let b = rect(&mut s, 100.0, 0.0, 20.0, 20.0);
|
||||
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
|
||||
let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
|
||||
s.execute("edit.clear", &json!({})).unwrap();
|
||||
select(&mut s, &[b, g]);
|
||||
s.execute("select.key", &json!({"id": g.0})).unwrap();
|
||||
s.execute("addon.arrange.match", &json!({"stacking": true})).unwrap();
|
||||
assert_eq!(layer_order(&s), [g, b], "b goes directly above the empty group");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_stacking_refuses_intertwine_nesting_beside_an_empty_group() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 40.0, 40.0);
|
||||
let source = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
let b = rect(&mut s, 20.0, 20.0, 40.0, 40.0);
|
||||
select(&mut s, &[source, b]);
|
||||
let parent = NodeId(s.execute("object.intertwine.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
select(&mut s, &[a]);
|
||||
s.execute("edit.clear", &json!({})).unwrap();
|
||||
assert!(s.transform_box(&[source]).is_none());
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(source), Some(parent));
|
||||
let c = rect(&mut s, 100.0, 0.0, 40.0, 40.0);
|
||||
let d = rect(&mut s, 120.0, 20.0, 40.0, 40.0);
|
||||
select(&mut s, &[c, d]);
|
||||
let target = NodeId(s.execute("object.intertwine.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
select(&mut s, &[source, target]);
|
||||
s.execute("select.key", &json!({"id": source.0})).unwrap();
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let n = steps(&s);
|
||||
let error = s.execute("addon.arrange.match", &json!({"stacking": true})).unwrap_err().to_string();
|
||||
assert!(error.contains("can't be intertwined"), "{error}");
|
||||
assert_eq!(steps(&s), n);
|
||||
assert!(*s.doc().unwrap().doc == *before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_replays_with_the_stroke_scaling_it_ran_with() {
|
||||
replays_the_stroke_scaling_it_ran_with("addon.arrange.match", json!({"size": "both"}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_size_of_each_replays_with_the_stroke_scaling_it_ran_with() {
|
||||
replays_the_stroke_scaling_it_ran_with("addon.arrange.size", json!({"width": 20, "height": 20}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn swap_replays_with_the_stroke_scaling_it_ran_with() {
|
||||
replays_the_stroke_scaling_it_ran_with("addon.arrange.swap", json!({"size": true}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_refuses_bad_params() {
|
||||
let mut s = session();
|
||||
let (a, _, _) = three(&mut s);
|
||||
refuses(
|
||||
&mut s,
|
||||
"addon.arrange.match",
|
||||
&[
|
||||
json!({}),
|
||||
json!({"size": "none"}),
|
||||
json!({"size": "area"}),
|
||||
json!({"size": 1}),
|
||||
json!({"rotate": 1}),
|
||||
json!({"stacking": "yes"}),
|
||||
json!({"size": "both", "reference": 9}),
|
||||
json!({"size": "both", "reference": 1.5}),
|
||||
json!({"size": "both", "source": "left"}),
|
||||
json!({"size": "both", "scaleStrokes": "no"}),
|
||||
json!({"size": "both", "patterns": 0}),
|
||||
],
|
||||
);
|
||||
let e = s.execute("addon.arrange.match", &json!({"source": "key", "rotate": true})).unwrap_err().to_string();
|
||||
assert!(e.contains("no key object"), "{e}");
|
||||
select(&mut s, &[a]);
|
||||
assert!(!enabled(&s, "addon.arrange.match"), "one object selected");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_params_are_refused() {
|
||||
let mut s = session();
|
||||
@@ -389,6 +777,7 @@ fn off_without_a_selection() {
|
||||
"addon.arrange.swap",
|
||||
"addon.arrange.replace",
|
||||
"addon.arrange.size",
|
||||
"addon.arrange.match",
|
||||
"addon.arrange.groupOverlapping",
|
||||
"addon.arrange.randomizeOpacity",
|
||||
"addon.arrange.sort",
|
||||
|
||||
@@ -14,7 +14,7 @@ use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::color_mask::{ColorMask, MaskBackground, MaskMatch};
|
||||
use vectorcraft_doc::{Document, ImageBlob, Node, NodeId, NodeKind};
|
||||
use vectorcraft_doc::{Document, ImageBlob, Node, NodeId, NodeKind, changed_nodes};
|
||||
use vectorcraft_geom::Affine;
|
||||
|
||||
use super::super::super::paint::{PROCESS_ON_TRANSPARENCY, colorized_with_process};
|
||||
@@ -367,14 +367,7 @@ fn stale_in(doc: &Document, n: &Arc<Node>, old: Option<&Arc<Node>>) -> bool {
|
||||
}
|
||||
let Some(children) = n.children() else { return false };
|
||||
let before = old.and_then(|o| o.children()).map_or(&[][..], Vec::as_slice);
|
||||
let mut by_id: Option<HashMap<NodeId, &Arc<Node>>> = None;
|
||||
children.iter().enumerate().any(|(i, c)| {
|
||||
let b = match before.get(i) {
|
||||
Some(b) if b.id == c.id => Some(b),
|
||||
_ => by_id.get_or_insert_with(|| before.iter().map(|b| (b.id, b)).collect()).get(&c.id).copied(),
|
||||
};
|
||||
stale_in(doc, c, b)
|
||||
})
|
||||
changed_nodes(before, children).any(|(_, c, b)| stale_in(doc, c, b))
|
||||
}
|
||||
|
||||
/// Whether `n` is an image whose color mask was not made from its own pixels (or whose masked
|
||||
|
||||
@@ -162,7 +162,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Cut",
|
||||
["Edit"],
|
||||
Some("Cmd+X"),
|
||||
"{selectedArtboards?: [n…], art?: bool, lockedAndHidden?: bool (the Artboard tool chosen, as artboard.cut)} (as edit.copy) removes the objects it copies, in one undo step: a compound-path member selected on its own leaves the compound's other members in the compound (selected ruler guides go too; the Artboard tool chosen, or selectedArtboards given: artboard.cut); refused while an object of a symbol instance's art is selected",
|
||||
"{artboard?: index (the source artboard for copied objects), selectedArtboards?: [n…], art?: bool, lockedAndHidden?: bool (the Artboard tool chosen, as artboard.cut)} (as edit.copy) removes the objects it copies, in one undo step: a compound-path member selected on its own leaves the compound's other members in the compound (selected ruler guides go too; the Artboard tool chosen, or selectedArtboards given: artboard.cut); refused while an object of a symbol instance's art is selected",
|
||||
has_selection_guides_or_artboard_tool,
|
||||
cut
|
||||
),
|
||||
@@ -171,7 +171,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Copy",
|
||||
["Edit"],
|
||||
Some("Cmd+C"),
|
||||
"{selectedArtboards?: [n…] (the artboards the Artboard tool had selected, which the journal records for a replay; it runs artboard.copy with any tool chosen), art?: bool (default: the Artboard tool's moveArt option; the journal records it beside selectedArtboards), lockedAndHidden?: bool (the Artboard tool chosen, as artboard.copy)} the selection with what it uses (a compound-path member selected on its own, whole or in part, with Direct or Group Selection, is copied as an ordinary path with the compound's paint, transparency, opacity mask, fill rule and graphic style link (while it has that style's look), a gradient keeping the compound's fit; the compound is copied when it is selected, or when every member is selected whole outside isolation mode), and the selected ruler guides (pasted on the layer new art goes to, moved as the objects are; alone, where they were); the Artboard tool chosen: artboard.copy; with an object of a symbol instance's art selected, the instance is copied whole → {copied, guides}",
|
||||
"{artboard?: index (the source artboard for copied objects; without it, the artboard containing the selection center), selectedArtboards?: [n…] (the artboards the Artboard tool had selected, which the journal records for a replay; it runs artboard.copy with any tool chosen), art?: bool (default: the Artboard tool's moveArt option; the journal records it beside selectedArtboards), lockedAndHidden?: bool (the Artboard tool chosen, as artboard.copy)} the selection with what it uses (a compound-path member selected on its own, whole or in part, with Direct or Group Selection, is copied as an ordinary path with the compound's paint, transparency, opacity mask, fill rule and graphic style link (while it has that style's look), a gradient keeping the compound's fit; the compound is copied when it is selected, or when every member is selected whole outside isolation mode), and the selected ruler guides (pasted on the layer new art goes to, moved as the objects are; alone, where they were); the Artboard tool chosen: artboard.copy; with an object of a symbol instance's art selected, the instance is copied whole → {copied, guides}",
|
||||
has_selection_guides_or_artboard_tool,
|
||||
copy
|
||||
),
|
||||
@@ -1163,6 +1163,13 @@ fn copy(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
});
|
||||
clip.source_artboard = board.map(|a| a.rect);
|
||||
}
|
||||
if let Some(value) = p.get("artboard") {
|
||||
let board = value
|
||||
.as_u64()
|
||||
.and_then(|v| st.doc.artboards.get(index(v)))
|
||||
.ok_or_else(|| bad("edit.copy", "`artboard` must be the index of an artboard of the document"))?;
|
||||
clip.source_artboard = Some(board.rect);
|
||||
}
|
||||
clip.guides = guides;
|
||||
s.clipboard = clip;
|
||||
Ok(json!({ "copied": s.clipboard.nodes.len(), "guides": s.clipboard.guides.len() }))
|
||||
|
||||
@@ -114,7 +114,17 @@ pub fn missing_fonts(d: &Document) -> Vec<MissingFont> {
|
||||
/// `text.missingFonts`'s answer for the open document `st`, where searches go by `rules` (this
|
||||
/// computer's when `None`).
|
||||
pub fn missing_fonts_of(st: &DocState, rules: Option<&findfiles::Rules>) -> Value {
|
||||
let fonts: Vec<Value> = missing_fonts(&st.doc)
|
||||
let fonts = missing_font_rows(&st.doc);
|
||||
let mut out = json!({ "count": fonts.len(), "fonts": fonts });
|
||||
if let Some(dir) = fonts_next_to_document(st, rules) {
|
||||
out["fontsNextToDocument"] = json!(dir);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// `text.missingFonts`'s `fonts` rows for `d` ([`missing_fonts`]).
|
||||
pub fn missing_font_rows(d: &Document) -> Vec<Value> {
|
||||
missing_fonts(d)
|
||||
.into_iter()
|
||||
.map(|m| {
|
||||
json!({
|
||||
@@ -122,26 +132,26 @@ pub fn missing_fonts_of(st: &DocState, rules: Option<&findfiles::Rules>) -> Valu
|
||||
"resolved": m.resolved.map(|(family, style)| json!({ "family": family, "style": style })),
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let mut out = json!({ "count": fonts.len(), "fonts": fonts });
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// `text.missingFonts`'s `fontsNextToDocument` for the open document `st`, where searches go by
|
||||
/// `rules` (this computer's when `None`).
|
||||
pub fn fonts_next_to_document(st: &DocState, rules: Option<&findfiles::Rules>) -> Option<String> {
|
||||
// File › Package puts the fonts in a `Fonts` folder next to the packaged document. The folder
|
||||
// is made absolute against the working folder when the document's path is relative. It is
|
||||
// offered when a search may start there, as far as the rules tell without listing a folder.
|
||||
if let Some(dir) = st.path.as_deref().and_then(|p| Path::new(p).parent()).map(|d| d.join("Fonts")).filter(|d| d.is_dir()) {
|
||||
let dir = super::fileio::absolute_path(&dir.to_string_lossy());
|
||||
let system;
|
||||
let rules = match rules {
|
||||
Some(rules) => rules,
|
||||
None => {
|
||||
system = findfiles::Rules::system();
|
||||
&system
|
||||
}
|
||||
};
|
||||
if std::fs::canonicalize(&dir).is_ok_and(|c| rules.refusal_unlisted(&c).is_none()) {
|
||||
out["fontsNextToDocument"] = json!(dir);
|
||||
let dir = st.path.as_deref().and_then(|p| Path::new(p).parent()).map(|d| d.join("Fonts")).filter(|d| d.is_dir())?;
|
||||
let dir = super::fileio::absolute_path(&dir.to_string_lossy());
|
||||
let system;
|
||||
let rules = match rules {
|
||||
Some(rules) => rules,
|
||||
None => {
|
||||
system = findfiles::Rules::system();
|
||||
&system
|
||||
}
|
||||
}
|
||||
out
|
||||
};
|
||||
std::fs::canonicalize(&dir).is_ok_and(|c| rules.refusal_unlisted(&c).is_none()).then_some(dir)
|
||||
}
|
||||
|
||||
fn missing(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
|
||||
@@ -267,6 +267,8 @@ thread_local! {
|
||||
pub(crate) static FORMS_MADE: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
/// Tests: how many times [`outlines`] made the outline of a highlighted object on this thread.
|
||||
pub(crate) static OUTLINES_MADE: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
/// Tests: how many objects [`matches`] looked at on this thread.
|
||||
pub(crate) static OBJECTS_WALKED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
impl Form {
|
||||
@@ -527,6 +529,8 @@ fn matches(s: &Session, o: &Options) -> Result<Vec<(NodeId, Affine)>> {
|
||||
let mut cache = st.global_edit_forms.0.borrow_mut();
|
||||
let mut pass = cache.forms.pass();
|
||||
super::select::walk_selectable(d, st.isolation, |n| {
|
||||
#[cfg(test)]
|
||||
OBJECTS_WALKED.with(|c| c.set(c.get() + 1));
|
||||
if n.id == *id || out.len() >= MAX_MEMBERS {
|
||||
return false;
|
||||
}
|
||||
@@ -1075,34 +1079,178 @@ pub fn highlights(s: &Session) -> std::sync::Arc<Highlights> {
|
||||
out
|
||||
}
|
||||
|
||||
/// [`similar`]'s outlines as of a document revision and the options they were found with.
|
||||
pub type SimilarCache = std::cell::RefCell<Option<(u64, Options, std::sync::Arc<Highlights>)>>;
|
||||
/// [`similar`]'s outlines as of a document revision, with what they were found from.
|
||||
pub type SimilarCache = std::cell::RefCell<Option<Similar>>;
|
||||
|
||||
/// [`similar`]'s outlines and what they were found from.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Similar {
|
||||
revision: u64,
|
||||
options: Options,
|
||||
/// The document, the one selected object and the isolated object they were found with.
|
||||
doc: Arc<Document>,
|
||||
key: NodeId,
|
||||
isolation: Option<NodeId>,
|
||||
out: Arc<Highlights>,
|
||||
}
|
||||
|
||||
/// Before Global Edit starts: with one supported object selected, the outlines of the other
|
||||
/// objects Start Global Edit would take now with the session's Global Edit Options, so the canvas
|
||||
/// shows them as soon as the object is selected. None while an interaction (a drag) is in
|
||||
/// progress, or when fewer than two objects would be taken. Kept per document revision and
|
||||
/// options, as finding them walks the whole document.
|
||||
/// options, as finding them walks the whole document. After an edit that replaced only the
|
||||
/// selected object, and left what the others are compared with as it was (a move), the outlines
|
||||
/// found before are kept without a walk.
|
||||
pub fn similar(s: &Session) -> std::sync::Arc<Highlights> {
|
||||
let Some(st) = s.active() else { return NO_HIGHLIGHTS.clone() };
|
||||
if st.global_edit.is_some() || st.interaction.is_some() || st.selection.objects.len() != 1 {
|
||||
// Global Edit is refused while an object of a dynamic symbol instance's art is selected.
|
||||
if st.global_edit.is_some() || st.interaction.is_some() || st.selection.objects.len() != 1 || super::edit::refuse_symbol_part(s).is_err() {
|
||||
return NO_HIGHLIGHTS.clone();
|
||||
}
|
||||
let o = &s.global_edit_options;
|
||||
if let Some((rev, opts, out)) = &*st.similar_outlines.borrow()
|
||||
&& *rev == st.revision
|
||||
&& opts == o
|
||||
let key = st.selection.objects[0];
|
||||
if let Some(c) = &mut *st.similar_outlines.borrow_mut()
|
||||
&& c.options == *o
|
||||
&& c.key == key
|
||||
&& c.isolation == st.isolation
|
||||
&& (c.revision == st.revision || Arc::ptr_eq(&c.doc, &st.doc) || only_key_changed(&c.doc, &st.doc, key))
|
||||
{
|
||||
return out.clone();
|
||||
c.revision = st.revision;
|
||||
c.doc = st.doc.clone();
|
||||
return c.out.clone();
|
||||
}
|
||||
let out = Highlights::new(match matches(s, o) {
|
||||
Ok(m) if m.len() >= 2 => outlines(st, &m),
|
||||
_ => vec![],
|
||||
});
|
||||
*st.similar_outlines.borrow_mut() = Some((st.revision, o.clone(), out.clone()));
|
||||
*st.similar_outlines.borrow_mut() =
|
||||
Some(Similar { revision: st.revision, options: o.clone(), doc: st.doc.clone(), key, isolation: st.isolation, out: out.clone() });
|
||||
out
|
||||
}
|
||||
|
||||
/// Would [`matches`] find the same objects in `now` as in `then`, with `key` selected in both?
|
||||
/// True when the layers differ only in `key` and in the layers and groups that hold it (the same
|
||||
/// apart from their contents), `key` is compared with the others as before ([`same_key`]), and the
|
||||
/// rest of the document is the same. A group that holds `key` is never like it (its form holds
|
||||
/// `key`'s and more), so the walk looks into it before and after alike.
|
||||
fn only_key_changed(then: &Document, now: &Document, key: NodeId) -> bool {
|
||||
let mut found = None;
|
||||
let same_symbol = |a: &vectorcraft_doc::Symbol, b: &vectorcraft_doc::Symbol| {
|
||||
a.name == b.name && a.dynamic == b.dynamic && (Arc::ptr_eq(&a.art, &b.art) || a.art == b.art)
|
||||
};
|
||||
// Everything else in the document (artboards, symbol settings, editing modes) as it was: the
|
||||
// symbols' art is compared on its own, as one copy when no edit changed it.
|
||||
let rest = |d: &Document| {
|
||||
let mut d = d.clone();
|
||||
d.layers.clear();
|
||||
d.symbols.clear();
|
||||
d
|
||||
};
|
||||
if then.symbols.len() != now.symbols.len()
|
||||
|| !then.symbols.iter().zip(&now.symbols).all(|(a, b)| same_symbol(a, b))
|
||||
|| rest(then) != rest(now)
|
||||
|| !changed_only(&then.layers, &now.layers, key, &mut found)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
found.is_none_or(|(a, b)| same_key(a, b, &now.symbol_boxes()))
|
||||
}
|
||||
|
||||
/// Do `then` and `now` hold the same objects, apart from `key` and the layers and groups on the way
|
||||
/// to it? `found` takes the two versions of `key` when it changed.
|
||||
fn changed_only<'a>(then: &'a [Arc<Node>], now: &'a [Arc<Node>], key: NodeId, found: &mut Option<(&'a Node, &'a Node)>) -> bool {
|
||||
if then.len() != now.len() {
|
||||
return false;
|
||||
}
|
||||
then.iter().zip(now).all(|(a, b)| {
|
||||
if Arc::ptr_eq(a, b) {
|
||||
return true;
|
||||
}
|
||||
if a.id != b.id {
|
||||
return false;
|
||||
}
|
||||
if a.id == key {
|
||||
return found.replace((a, b)).is_none();
|
||||
}
|
||||
match (holder_children(a), holder_children(b)) {
|
||||
(Some(x), Some(y)) => same_holder(a, b) && changed_only(x, y, key, found),
|
||||
_ => false,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// The objects in a layer or a group.
|
||||
fn holder_children(n: &Node) -> Option<&[Arc<Node>]> {
|
||||
match &n.kind {
|
||||
NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => Some(children),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Are two versions of a layer or a group the same apart from the objects in them?
|
||||
fn same_holder(a: &Node, b: &Node) -> bool {
|
||||
let Node { id, name, visible, locked, opacity, blend, isolate, knockout, knockout_shape, appearance, kind, bbox_angle, extras } = a;
|
||||
let kinds = match (kind, &b.kind) {
|
||||
(
|
||||
NodeKind::Layer { color, template, printable, children: _, clip, preview, dim_images },
|
||||
NodeKind::Layer { color: c, template: t, printable: p, children: _, clip: cl, preview: pv, dim_images: di },
|
||||
) => color == c && template == t && printable == p && clip == cl && preview == pv && dim_images == di,
|
||||
(NodeKind::Group { children: _, clip }, NodeKind::Group { children: _, clip: c }) => clip == c,
|
||||
_ => false,
|
||||
};
|
||||
kinds
|
||||
&& *id == b.id
|
||||
&& *name == b.name
|
||||
&& *visible == b.visible
|
||||
&& *locked == b.locked
|
||||
&& *opacity == b.opacity
|
||||
&& *blend == b.blend
|
||||
&& *isolate == b.isolate
|
||||
&& *knockout == b.knockout
|
||||
&& *knockout_shape == b.knockout_shape
|
||||
&& *appearance == b.appearance
|
||||
&& *bbox_angle == b.bbox_angle
|
||||
&& *extras == b.extras
|
||||
}
|
||||
|
||||
/// How far apart two versions of the selected object's form may lie, in its unit box, and how much
|
||||
/// their sizes may differ (relative), for [`similar`] to keep the objects found like the first: a
|
||||
/// millionth of [`SAME`]. A move leaves the form the same but for rounding (the form is placed in
|
||||
/// its unit box by a transform that includes the move), well within this.
|
||||
const KEPT: f64 = 1e-12;
|
||||
|
||||
/// Are two versions of the selected object compared with the other objects in the same way by
|
||||
/// [`matches`]: the same form in a box of the same size and the same geometric size (a perspective
|
||||
/// projection changes that alone), within [`KEPT`], and the same fill and stroke in each object in
|
||||
/// them?
|
||||
fn same_key(a: &Node, b: &Node, symbols: &vectorcraft_doc::SymbolBoxes<'_>) -> bool {
|
||||
let near = |x: f64, y: f64| (x - y).abs() <= KEPT * x.abs().max(y.abs()).max(1.0);
|
||||
fn same_look(a: &Node, b: &Node) -> bool {
|
||||
fill_of(a) == fill_of(b)
|
||||
&& stroke_of(a) == stroke_of(b)
|
||||
&& match (a.children(), b.children()) {
|
||||
(Some(x), Some(y)) => x.len() == y.len() && x.iter().zip(y).all(|(p, q)| same_look(p, q)),
|
||||
(x, y) => x.is_none() && y.is_none(),
|
||||
}
|
||||
}
|
||||
if !(supported(a) && supported(b)) {
|
||||
return false;
|
||||
}
|
||||
let (Some(f), Some(g)) = (Form::of(a), Form::of(b)) else { return false };
|
||||
let (fl, gl) = (f.frame.as_coeffs(), g.frame.as_coeffs());
|
||||
let sizes = match (a.geometric_bounds_with(symbols), b.geometric_bounds_with(symbols)) {
|
||||
(Some(x), Some(y)) => near(x.width(), y.width()) && near(x.height(), y.height()),
|
||||
(x, y) => x.is_none() && y.is_none(),
|
||||
};
|
||||
f.tag == g.tag
|
||||
&& f.symbols == g.symbols
|
||||
&& f.points.len() == g.points.len()
|
||||
&& f.points.iter().zip(&g.points).all(|(p, q)| p.distance(*q) <= KEPT)
|
||||
&& fl[..4].iter().zip(&gl[..4]).all(|(x, y)| near(*x, *y))
|
||||
&& sizes
|
||||
&& same_look(a, b)
|
||||
}
|
||||
|
||||
/// The outlines of `members` that are not selected, hold no selected object and sit inside no
|
||||
/// selected object, in their layer's color.
|
||||
fn outlines(st: &crate::DocState, members: &[(NodeId, Affine)]) -> Outlines {
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use vectorcraft_doc::{AppearanceItem, LiveShape, StrokeAlign};
|
||||
use vectorcraft_doc::{AppearanceItem, LiveShape, StrokeAlign, changed_nodes};
|
||||
|
||||
use super::{
|
||||
Affine, Arc, Document, EngineError, Node, NodeId, NodeKind, Paint, PathData, Rect, Result, Scaling, Session, Value, Vec2, bad, json,
|
||||
@@ -226,15 +226,7 @@ fn refresh_symbols(before: &Document, doc: &mut Document) {
|
||||
/// groups too: the instances of the symbols in `natural` (`ids`), and the objects whose opacity
|
||||
/// mask art holds such instances (`masked`).
|
||||
fn changed_instances(before: &[Arc<Node>], after: &[Arc<Node>], natural: &HashMap<String, Affine>, ids: &mut Vec<NodeId>, masked: &mut Vec<NodeId>) {
|
||||
let mut by_id: Option<HashMap<NodeId, &Arc<Node>>> = None;
|
||||
for (i, a) in after.iter().enumerate() {
|
||||
let b = match before.get(i) {
|
||||
Some(b) if b.id == a.id => Some(b),
|
||||
_ => by_id.get_or_insert_with(|| before.iter().map(|b| (b.id, b)).collect()).get(&a.id).copied(),
|
||||
};
|
||||
if b.is_some_and(|b| Arc::ptr_eq(b, a)) {
|
||||
continue;
|
||||
}
|
||||
for (_, a, b) in changed_nodes(before, after) {
|
||||
if a.extras().mask.as_ref().is_some_and(|m| holds_instance(&m.art, natural)) {
|
||||
masked.push(a.id);
|
||||
}
|
||||
@@ -423,15 +415,7 @@ pub(crate) fn keep_aligned_in(doc: &mut Document, ids: &[NodeId]) {
|
||||
/// pixel-aligned or hold pixel-aligned art in a linked opacity mask. Inside such an object the
|
||||
/// walk stops: [`keep_pixel_aligned`] visits what it holds.
|
||||
fn changed_aligned(before: &[Arc<Node>], after: &[Arc<Node>], out: &mut Vec<NodeId>) {
|
||||
let mut by_id: Option<std::collections::HashMap<NodeId, &Arc<Node>>> = None;
|
||||
for (i, a) in after.iter().enumerate() {
|
||||
let b = match before.get(i) {
|
||||
Some(b) if b.id == a.id => Some(b),
|
||||
_ => by_id.get_or_insert_with(|| before.iter().map(|b| (b.id, b)).collect()).get(&a.id).copied(),
|
||||
};
|
||||
if b.is_some_and(|b| Arc::ptr_eq(b, a)) {
|
||||
continue;
|
||||
}
|
||||
for (_, a, b) in changed_nodes(before, after) {
|
||||
if a.extras().pixel_aligned || a.extras().mask.as_ref().is_some_and(|m| m.linked && holds_aligned(&m.art)) {
|
||||
out.push(a.id);
|
||||
} else if let Some(children) = a.children() {
|
||||
|
||||
@@ -192,7 +192,11 @@ fn apply_transform_moving_guides(
|
||||
if copy { vec![] } else { ids }
|
||||
} else {
|
||||
let kept = if copy { preview_copies(s, &ids, with_guides, below)? } else { None };
|
||||
s.edit(label, |d, sel| {
|
||||
// A move of whole objects, not of copies (which `reindex` covers): the document before it,
|
||||
// and the moved objects as the transform left them, for [`moved_by`] to check after the edit.
|
||||
let from = (objects && !areas && !reindex && c[..4] == [1.0, 0.0, 0.0, 1.0]).then(|| s.doc().map(|st| st.doc.clone())).transpose()?;
|
||||
let mut held: Vec<(NodeId, Arc<Node>)> = vec![];
|
||||
let targets = s.edit(label, |d, sel| {
|
||||
let mut targets = match &kept {
|
||||
// The document becomes the snapshot with the kept copies, untransformed, and the
|
||||
// loop below transforms only the copies.
|
||||
@@ -229,6 +233,10 @@ fn apply_transform_moving_guides(
|
||||
transform_node(n, xf, sc, objects);
|
||||
}
|
||||
}
|
||||
// Holding them makes any later change to them copy them first, which `moved_by` sees.
|
||||
if from.is_some() {
|
||||
held = targets.iter().filter_map(|id| Some((*id, node_arc(d, paths.get(id)?)?))).collect();
|
||||
}
|
||||
if objects {
|
||||
for id in &targets {
|
||||
super::pixelgrid::keep_compound_aligned(d, *id, sc);
|
||||
@@ -248,7 +256,10 @@ fn apply_transform_moving_guides(
|
||||
targets.extend(d.transform_ruler_guides(sel, xf));
|
||||
}
|
||||
Ok(targets)
|
||||
})?
|
||||
})?;
|
||||
let st = s.doc_mut()?;
|
||||
st.moved = from.and_then(|from| moved_by(&from, st, &held, Vec2::new(c[4], c[5])));
|
||||
targets
|
||||
};
|
||||
let st = s.doc_mut()?;
|
||||
if st.interaction.is_none() {
|
||||
@@ -266,6 +277,47 @@ fn apply_transform_moving_guides(
|
||||
Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>() }))
|
||||
}
|
||||
|
||||
/// The node at index path `path` of `d`, shared.
|
||||
fn node_arc(d: &Document, path: &[usize]) -> Option<Arc<Node>> {
|
||||
let (first, rest) = path.split_first()?;
|
||||
let mut cur = d.layers.get(*first)?;
|
||||
for &i in rest {
|
||||
cur = cur.children()?.get(i)?;
|
||||
}
|
||||
Some(cur.clone())
|
||||
}
|
||||
|
||||
/// The [`crate::Moved`] of a move by `by` that took `from` to the document of `st`, given the moved
|
||||
/// objects as the transform left them (`held`). `None` unless every moved object is still that
|
||||
/// node, none is a member of a blend (whose spine follows its members), and every object the
|
||||
/// selection shows, the key object and the key anchor's object included, is a moved object or
|
||||
/// inside one. A pass after the transform that changes a moved object, such as the one that snaps
|
||||
/// moved pixel-aligned objects to the pixel grid again ([`super::pixelgrid::refresh`]), copies it
|
||||
/// first, so it is no longer that node.
|
||||
fn moved_by(from: &Arc<Document>, st: &crate::DocState, held: &[(NodeId, Arc<Node>)], by: Vec2) -> Option<crate::Moved> {
|
||||
let d = &st.doc;
|
||||
let unchanged = |(id, n): &(NodeId, Arc<Node>)| d.node(*id).is_some_and(|now| std::ptr::eq(now, Arc::as_ptr(n)));
|
||||
if held.is_empty() || !held.iter().all(unchanged) {
|
||||
return None;
|
||||
}
|
||||
let in_blend = |id: NodeId| d.parent_of(id).and_then(|p| d.node(p)).is_some_and(|p| matches!(p.kind, NodeKind::Blend { .. }));
|
||||
if held.iter().any(|(id, _)| in_blend(*id)) {
|
||||
return None;
|
||||
}
|
||||
let mut moved = std::collections::HashSet::new();
|
||||
for (_, n) in held {
|
||||
n.walk(&mut |c| {
|
||||
moved.insert(c.id);
|
||||
});
|
||||
}
|
||||
let sel = &st.selection;
|
||||
let mut shown = sel.objects.iter().copied().chain(sel.key).chain(sel.key_anchor.map(|(id, _)| id));
|
||||
if !shown.all(|id| moved.contains(&id)) {
|
||||
return None;
|
||||
}
|
||||
Some(crate::Moved { from: Arc::downgrade(from), to: Arc::downgrade(d), by, selection: sel.clone() })
|
||||
}
|
||||
|
||||
/// Returns the copies of `roots` for a transform or a perspective edit with `copy` in an interaction
|
||||
/// whose document is still its snapshot, as in a preview ([`Session::preview`] puts the snapshot
|
||||
/// back first). These are the copies the interaction keeps when they were made of that snapshot for
|
||||
|
||||
@@ -25,12 +25,12 @@
|
||||
//! the objects squared to the path; Pivot and Rotate; path edits realign the objects; Detach and
|
||||
//! the objects that move up the path after it; Expand).
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::collections::HashSet;
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::objects_on_path::{CENTER, Held, ObjectsOnPath, attachable_path, held, is_objects_on_path, place};
|
||||
use vectorcraft_doc::{Document, Node, NodeId, NodeKind};
|
||||
use vectorcraft_doc::{Document, Node, NodeId, NodeKind, changed_nodes};
|
||||
use vectorcraft_geom::Rect;
|
||||
|
||||
use super::edit::{roots_of, selected_roots};
|
||||
@@ -499,15 +499,7 @@ fn place_in(doc: &mut Document, id: NodeId) -> bool {
|
||||
/// The Objects on Path groups among `after` and inside them that are not the same nodes as before
|
||||
/// (`before`: the same list before the edit), outer ones first.
|
||||
fn changed_groups(before: &[Arc<Node>], after: &[Arc<Node>], out: &mut Vec<NodeId>) {
|
||||
let mut by_id: Option<HashMap<NodeId, &Arc<Node>>> = None;
|
||||
for (i, a) in after.iter().enumerate() {
|
||||
let b = match before.get(i) {
|
||||
Some(b) if b.id == a.id => Some(b),
|
||||
_ => by_id.get_or_insert_with(|| before.iter().map(|b| (b.id, b)).collect()).get(&a.id).copied(),
|
||||
};
|
||||
if b.is_some_and(|b| Arc::ptr_eq(b, a)) {
|
||||
continue;
|
||||
}
|
||||
for (_, a, b) in changed_nodes(before, after) {
|
||||
if is_objects_on_path(a) {
|
||||
out.push(a.id);
|
||||
}
|
||||
|
||||
@@ -185,14 +185,27 @@ fn can_change_mask(s: &Session) -> std::result::Result<(), String> {
|
||||
/// most one outermost object, which it masks with `ids` (a call's `ids` stand in for the selection
|
||||
/// here). A targeted layer is one subject root however many objects it selects. `make` itself
|
||||
/// refuses any single target in those modes, a layer included, so a selection with a target counts
|
||||
/// as one object.
|
||||
/// as one object. The check sorts the selection into paint order for its outermost objects only when it has one
|
||||
/// subject root and no target.
|
||||
fn can_make(s: &Session) -> std::result::Result<(), String> {
|
||||
has_doc(s)?;
|
||||
let Some(st) = s.active() else { return Ok(()) };
|
||||
let roots = super::appearance::subject_roots(s).map_or(0, |r| r.len());
|
||||
let outermost = super::edit::outermost(&st.doc, st.selection.in_paint_order(&st.doc)).len();
|
||||
let targeted = st.selection.target.is_some();
|
||||
if roots == 1 && (outermost <= 1 || targeted) { super::maskedit::can_edit_mask(s) } else { Ok(()) }
|
||||
if roots != 1 {
|
||||
return Ok(());
|
||||
}
|
||||
let one = st.selection.target.is_some() || {
|
||||
#[cfg(test)]
|
||||
OUTERMOST_FOUND.set(OUTERMOST_FOUND.get() + 1);
|
||||
super::edit::outermost(&st.doc, st.selection.in_paint_order(&st.doc)).len() <= 1
|
||||
};
|
||||
if one { super::maskedit::can_edit_mask(s) } else { Ok(()) }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// How many times [`can_make`] found the selection's outermost objects on this thread.
|
||||
static OUTERMOST_FOUND: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
fn make(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -485,6 +498,12 @@ impl Session {
|
||||
_ => TransparencyInfo::default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The first of the objects the Transparency panel shows ([`TransparencyInfo::ids`]), without comparing their
|
||||
/// values.
|
||||
pub fn transparency_target(&self) -> Option<NodeId> {
|
||||
transparency_targets(self, &Value::Null).ok()?.first().copied()
|
||||
}
|
||||
}
|
||||
|
||||
fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -759,4 +778,22 @@ mod tests {
|
||||
let back = vectorcraft_format::load(&bytes).unwrap();
|
||||
assert_eq!(back.node(NodeId(a)).unwrap().extras().mask, d.node(NodeId(a)).unwrap().extras().mask);
|
||||
}
|
||||
|
||||
/// Make Opacity Mask's check sorts the selection for its outermost objects only when the selection has one
|
||||
/// subject root; with several roots it is enabled without that sort.
|
||||
#[test]
|
||||
fn the_make_check_sorts_only_a_selection_with_one_root() {
|
||||
let (mut s, a, b) = session_with_two();
|
||||
let found = || OUTERMOST_FOUND.get();
|
||||
select(&mut s, &[a, b]);
|
||||
let before = found();
|
||||
assert_eq!(can_make(&s), Ok(()));
|
||||
assert_eq!(found(), before, "two roots: no paint-order sort");
|
||||
select(&mut s, &[a]);
|
||||
assert_eq!(can_make(&s), Ok(()));
|
||||
assert_eq!(found(), before + 1, "one root: the outermost objects are found");
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
assert_eq!(can_make(&s), Ok(()));
|
||||
assert_eq!(found(), before + 1, "no roots: no sort");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1231,12 +1231,24 @@ fn queue(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
// ---------- queries ----------
|
||||
|
||||
/// The colour mode an image file stores its pixels in.
|
||||
fn color_mode(bytes: &[u8]) -> &'static str {
|
||||
match craft_image_codecs::decode(bytes).ok().map(|img| img.layout()) {
|
||||
Some(craft_image_codecs::ChannelLayout::Gray | craft_image_codecs::ChannelLayout::GrayA) => "Grayscale",
|
||||
Some(craft_image_codecs::ChannelLayout::Cmyk | craft_image_codecs::ChannelLayout::CmykA) => "CMYK",
|
||||
_ => "RGB",
|
||||
/// The colour mode an image file stores its pixels in. A PNG, JPEG, TIFF, PSD, GIF or BMP file's
|
||||
/// header says it and a WebP file is always RGB, so their pixels are not decoded; the Control bar
|
||||
/// and the Properties panel ask `image.info` again after every change, each step of a drag
|
||||
/// included. A file in another format is decoded.
|
||||
pub(crate) fn color_mode(bytes: &[u8]) -> &'static str {
|
||||
use craft_image_codecs::{ChannelLayout as L, RasterColorType as T};
|
||||
match craft_image_codecs::inspect_raster(bytes) {
|
||||
Ok(Some(i)) => match i.color_type {
|
||||
T::Bitmap | T::Gray | T::GrayAlpha => "Grayscale",
|
||||
T::Cmyk | T::CmykAlpha => "CMYK",
|
||||
_ => "RGB",
|
||||
},
|
||||
_ if craft_image_codecs::detect(bytes) == Some(craft_image_codecs::Format::WebP) => "RGB",
|
||||
_ => match craft_image_codecs::decode(bytes).ok().map(|img| img.layout()) {
|
||||
Some(L::Gray | L::GrayA) => "Grayscale",
|
||||
Some(L::Cmyk | L::CmykA) => "CMYK",
|
||||
_ => "RGB",
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
pub(super) const ALLOWED: &[&str] = &[
|
||||
"addon.arrange.grid",
|
||||
"addon.arrange.groupOverlapping",
|
||||
"addon.arrange.match",
|
||||
"addon.arrange.offset",
|
||||
"addon.arrange.randomizeOpacity",
|
||||
"addon.arrange.replace",
|
||||
|
||||
@@ -6,12 +6,9 @@ use super::{
|
||||
CommandSpec, EngineError, Result, Session, bad, bool_or, checked_ids_param, cmd, f64_or, has_doc, id_param, number_or, object_param, point_param,
|
||||
};
|
||||
use serde_json::{Value, json};
|
||||
use std::{
|
||||
collections::{BTreeMap, HashMap},
|
||||
sync::Arc,
|
||||
};
|
||||
use std::{collections::BTreeMap, sync::Arc};
|
||||
use vectorcraft_doc::shaper::{EdgeEdit, FILL_PREFIX, FaceEdit, FaceSelector, SOURCES, STROKE_PREFIX, ShaperSpec};
|
||||
use vectorcraft_doc::{Appearance, AppearanceItem, Document, Node, NodeId, NodeKind};
|
||||
use vectorcraft_doc::{Appearance, AppearanceItem, Document, Node, NodeId, NodeKind, changed_nodes};
|
||||
use vectorcraft_geom::{FillRule, PathData, Point, Rect, Shape as _};
|
||||
use vectorcraft_pathops as po;
|
||||
use vectorcraft_tools::builder::{self as b, BuilderMap};
|
||||
@@ -392,15 +389,7 @@ fn generated(d: &mut Document, src: &[Arc<Node>], spec: &ShaperSpec, map: &Build
|
||||
}
|
||||
|
||||
fn changed_shaper_groups(before: &[Arc<Node>], after: &[Arc<Node>], out: &mut Vec<NodeId>) {
|
||||
let mut by_id: Option<HashMap<NodeId, &Arc<Node>>> = None;
|
||||
for (i, a) in after.iter().enumerate() {
|
||||
let b = match before.get(i) {
|
||||
Some(b) if b.id == a.id => Some(b),
|
||||
_ => by_id.get_or_insert_with(|| before.iter().map(|b| (b.id, b)).collect()).get(&a.id).copied(),
|
||||
};
|
||||
if b.is_some_and(|b| Arc::ptr_eq(b, a)) {
|
||||
continue;
|
||||
}
|
||||
for (_, a, b) in changed_nodes(before, after) {
|
||||
if a.extras().shaper.is_some() {
|
||||
out.push(a.id);
|
||||
}
|
||||
|
||||
@@ -5,7 +5,9 @@ use super::{NodeId, Value, cmd, find_command};
|
||||
/// Objects and Distribute Spacing with Align to Artboard distribute objects across it, All on
|
||||
/// Active Artboard selects on it, and Edit Symbol from the Symbols panel centers the symbol's art
|
||||
/// on it. A `command.batch` given `artboard` passes it on to each of their steps that names none.
|
||||
pub const ON_ACTIVE_ARTBOARD: [&str; 8] = [
|
||||
pub const ON_ACTIVE_ARTBOARD: [&str; 10] = [
|
||||
"edit.copy",
|
||||
"edit.cut",
|
||||
"edit.pasteInPlace",
|
||||
"edit.pasteInFront",
|
||||
"edit.pasteInBack",
|
||||
@@ -35,7 +37,9 @@ pub const DRAWS_SHAPE: [&str; 5] = ["shape.rectangle", "shape.ellipse", "shape.p
|
||||
/// Artboard tool had selected for its commands and for Paste in Place, in Front and in Back; the artboards and art Cut and Copy took with that
|
||||
/// tool chosen; the view's center the app passes to Edit Symbol); an action leaves them out
|
||||
/// ([`Session::journal_for_action`]).
|
||||
const REPLAY_ONLY: [(&str, &str); 35] = [
|
||||
const REPLAY_ONLY: [(&str, &str); 37] = [
|
||||
("edit.copy", "artboard"),
|
||||
("edit.cut", "artboard"),
|
||||
("file.new", "created"),
|
||||
("edit.newDocumentFromState", "created"),
|
||||
("document.save", "modified"),
|
||||
|
||||
@@ -203,6 +203,24 @@ pub struct DocState {
|
||||
/// The selected objects as [`crate::Session::select`] last checked them or the proxies last
|
||||
/// read them, with the document they were checked in ([`SelectionRecord`]). Not saved.
|
||||
pub(crate) selection_record: Option<SelectionRecord>,
|
||||
/// The last move of the selected objects that changed nothing else they show ([`Moved`]).
|
||||
/// Not saved.
|
||||
pub moved: Option<Moved>,
|
||||
}
|
||||
|
||||
/// A move of whole objects that took document `from` to document `to`: each object the selection
|
||||
/// shows, the key object and the key anchor included, is the one in `from` moved by `by`, and
|
||||
/// nothing else they are drawn from changed (no member snapped to the pixel grid, no blend spine
|
||||
/// they follow, no pass after the edit). A view that drew the selection of `from` can
|
||||
/// move what it drew by `by` instead of building it again. It holds the documents as
|
||||
/// [`SelectionRecord::doc`] holds one, so a document changed in place no longer matches.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Moved {
|
||||
pub from: std::sync::Weak<Document>,
|
||||
pub to: std::sync::Weak<Document>,
|
||||
pub by: vectorcraft_geom::Vec2,
|
||||
/// The selection the move was made with, which is also the selection after it.
|
||||
pub selection: Selection,
|
||||
}
|
||||
|
||||
/// A selection of objects alone ([`objects_only`]) with the document it was checked or read in:
|
||||
@@ -522,6 +540,7 @@ impl DocState {
|
||||
measured_in_own: None,
|
||||
inline_resolved: None,
|
||||
selection_record: None,
|
||||
moved: None,
|
||||
}
|
||||
}
|
||||
/// The [`SelectionRecord`] of the selection now: `None` when the document or the selected
|
||||
|
||||
@@ -10,6 +10,9 @@ pub struct Interaction {
|
||||
pub doc: Arc<Document>,
|
||||
/// The selection the previews start from (shared, so a preview frame copies nothing).
|
||||
pub selection: Arc<Selection>,
|
||||
/// The document's [`crate::DocState::revision`] when the interaction began. The previews change the document's
|
||||
/// revision, and this value stays the same until the interaction ends.
|
||||
pub revision: u64,
|
||||
pub preview: Option<(String, Value)>,
|
||||
/// The active tool began it (a drag): a command from outside the tool runs as a step of its
|
||||
/// own under it ([`crate::Session::outside_interaction`]). A dialog or a panel that begins an
|
||||
@@ -52,6 +55,13 @@ pub struct Interaction {
|
||||
pub keep_on_switch: bool,
|
||||
}
|
||||
|
||||
impl Interaction {
|
||||
/// The active tool began it (a drag).
|
||||
pub fn by_tool(&self) -> bool {
|
||||
self.tool
|
||||
}
|
||||
}
|
||||
|
||||
/// An interaction that a command from outside the tool set aside while it runs
|
||||
/// ([`crate::Session::outside_interaction`]).
|
||||
#[derive(Debug)]
|
||||
|
||||
@@ -512,7 +512,7 @@ pub(crate) use command_sets::SELECTS_GIVEN_IDS;
|
||||
#[cfg(test)]
|
||||
use command_sets::given_ids;
|
||||
pub use command_sets::{DRAWS_SHAPE, FIT_ACTIVE_ARTBOARD, ON_ACTIVE_ARTBOARD, waits_for_plugin_loads, waits_for_tool_edit};
|
||||
pub use doc_state::{DocState, LayersReveal, OpenRows, RecalledSelection, WindowView};
|
||||
pub use doc_state::{DocState, LayersReveal, Moved, OpenRows, RecalledSelection, WindowView};
|
||||
pub use error::{EngineError, READ_ONLY_LOCATION, Result, SCRIPT_BUSY};
|
||||
#[cfg(test)]
|
||||
use history::history_budget_for;
|
||||
|
||||
@@ -545,6 +545,7 @@ impl Session {
|
||||
effect: None,
|
||||
doc: st.doc.clone(),
|
||||
selection: Arc::new(st.selection.clone()),
|
||||
revision: st.revision,
|
||||
preview: None,
|
||||
tool: false,
|
||||
paint,
|
||||
|
||||
@@ -118,6 +118,7 @@ mod livecorners;
|
||||
mod maskview;
|
||||
pub(super) mod menucmds;
|
||||
mod mesh_picks;
|
||||
mod moved;
|
||||
mod nativefile;
|
||||
mod newart;
|
||||
mod newdoc;
|
||||
|
||||
@@ -137,7 +137,7 @@ fn after_an_edit_only_the_changed_objects_are_compared_again_from_scratch() {
|
||||
s.execute("object.move", &json!({"dx": 5, "dy": 0})).unwrap();
|
||||
let before = made();
|
||||
assert_eq!(highlights(&s).len(), 39);
|
||||
assert_eq!(since(before), (1, 0), "the selected object only: the copies are unchanged");
|
||||
assert_eq!(since(before), (2, 0), "the selected object before and after the move only: the copies are unchanged");
|
||||
sel(&mut s, &[copies[0]]);
|
||||
s.execute("object.scale", &json!({"sx": 200, "sy": 100})).unwrap();
|
||||
sel(&mut s, &[copies[1]]);
|
||||
@@ -156,6 +156,207 @@ fn after_an_edit_only_the_changed_objects_are_compared_again_from_scratch() {
|
||||
assert_eq!(crate::cmd::globaledit::match_count(&s), 38);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_edit_to_the_selected_object_alone_keeps_the_similar_objects_without_a_walk() {
|
||||
use crate::cmd::globaledit::{OBJECTS_WALKED, highlights};
|
||||
let walked = || OBJECTS_WALKED.with(std::cell::Cell::get);
|
||||
// The outlines `highlights` gives, and how many objects it looked at for them.
|
||||
let shown = |s: &Session| {
|
||||
let before = walked();
|
||||
let out = highlights(s);
|
||||
(out, walked() - before)
|
||||
};
|
||||
// The outlines in each layer color.
|
||||
let paths = |h: &crate::cmd::globaledit::Highlights| h.groups.iter().map(|(c, p)| (*c, p.to_vec())).collect::<Vec<_>>();
|
||||
// The outlines a walk finds, the options set again so that nothing is kept.
|
||||
let fresh = |s: &mut Session| {
|
||||
let size = s.global_edit_options.size;
|
||||
s.execute("select.globalEditOptions", &json!({"size": !size})).unwrap();
|
||||
highlights(s);
|
||||
s.execute("select.globalEditOptions", &json!({"size": size})).unwrap();
|
||||
let before = walked();
|
||||
let out = highlights(s);
|
||||
assert!(walked() > before, "a walk");
|
||||
paths(&out)
|
||||
};
|
||||
let mut s = session();
|
||||
let key = rect(&mut s, 0.37, 0.91, 10.3, 10.3);
|
||||
let copies: Vec<NodeId> = (1..40).map(|i| rect(&mut s, 20.0 * f64::from(i % 20), 100.0 + 20.0 * f64::from(i / 20), 10.3, 10.3)).collect();
|
||||
sel(&mut s, &[key]);
|
||||
let (first, n) = shown(&s);
|
||||
assert_eq!(first.len(), 39);
|
||||
assert!(n >= 40, "the first preview walks every object");
|
||||
|
||||
// The move rounds the form in its unit box differently; the same objects are like it.
|
||||
s.execute("object.move", &json!({"dx": 3.17, "dy": 1.29})).unwrap();
|
||||
let (out, n) = shown(&s);
|
||||
assert_eq!(n, 0, "a move of the selected object alone compares the others as before");
|
||||
assert!(std::sync::Arc::ptr_eq(&out, &first), "the canvas keeps the outlines it stroked");
|
||||
assert_eq!(paths(&out), fresh(&mut s));
|
||||
|
||||
// Another object moved: it is shown where it is now.
|
||||
sel(&mut s, &[copies[0]]);
|
||||
s.execute("object.move", &json!({"dx": 300, "dy": 0})).unwrap();
|
||||
sel(&mut s, &[key]);
|
||||
let (out, n) = shown(&s);
|
||||
assert!(n > 0, "another object changed");
|
||||
let moved = node(&s, copies[0]).stroke_path().unwrap();
|
||||
assert!(out.groups.iter().flat_map(|(_, p)| p.iter()).any(|p| *p == moved), "the moved copy is shown where it is now");
|
||||
assert_eq!(paths(&out), fresh(&mut s));
|
||||
|
||||
// The selected object took another shape: none of the squares is like it.
|
||||
s.execute("object.scale", &json!({"sx": 200, "sy": 100})).unwrap();
|
||||
let (out, n) = shown(&s);
|
||||
assert!(n > 0 && out.is_empty(), "the widened square matches none of the squares");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(shown(&s).0.len(), 39);
|
||||
|
||||
// With Size, a larger copy of the selected square is another size.
|
||||
s.execute("select.globalEditOptions", &json!({"size": true})).unwrap();
|
||||
assert_eq!(shown(&s).0.len(), 39);
|
||||
s.execute("object.scale", &json!({"sx": 200, "sy": 200})).unwrap();
|
||||
let (out, n) = shown(&s);
|
||||
assert!(n > 0 && out.is_empty(), "the enlarged square has the size of none of them");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("select.globalEditOptions", &json!({"size": false})).unwrap();
|
||||
|
||||
// With Appearance, another fill on the selected square leaves the others out.
|
||||
s.execute("select.globalEditOptions", &json!({"appearance": true})).unwrap();
|
||||
assert_eq!(shown(&s).0.len(), 39);
|
||||
s.execute("paint.setFill", &json!({"color": "#12ab34"})).unwrap();
|
||||
let (out, n) = shown(&s);
|
||||
assert!(n > 0 && out.is_empty(), "the others have another fill now");
|
||||
s.execute("select.globalEditOptions", &json!({"appearance": false})).unwrap();
|
||||
|
||||
// Reflected, the selected kite keeps its size but is no longer like its copy.
|
||||
let lone = kite(&mut s, 0.0, 500.0, 1.0);
|
||||
kite(&mut s, 200.0, 500.0, 1.0);
|
||||
sel(&mut s, &[lone]);
|
||||
assert_eq!(shown(&s).0.len(), 1);
|
||||
s.execute("object.reflect", &json!({"axis": "vertical"})).unwrap();
|
||||
let (out, n) = shown(&s);
|
||||
assert!(n > 0 && out.is_empty(), "a reflected copy is not like it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn another_layer_locked_leaves_its_objects_out_of_the_similar_objects() {
|
||||
use crate::cmd::globaledit::highlights;
|
||||
let mut s = session();
|
||||
let key = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
|
||||
rect(&mut s, 20.0, 0.0, 10.0, 10.0);
|
||||
let other = NodeId(s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
rect(&mut s, 40.0, 0.0, 10.0, 10.0);
|
||||
rect(&mut s, 60.0, 0.0, 10.0, 10.0);
|
||||
sel(&mut s, &[key]);
|
||||
assert_eq!(highlights(&s).len(), 3);
|
||||
s.execute("layer.setProps", &json!({"id": other.0, "locked": true})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().selection.objects, [key]);
|
||||
assert_eq!(highlights(&s).len(), 1, "the squares on the locked layer are left out");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_new_artboard_brings_the_objects_on_it_into_the_similar_objects() {
|
||||
use crate::cmd::globaledit::highlights;
|
||||
let mut s = session();
|
||||
let key = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
|
||||
rect(&mut s, 20.0, 0.0, 10.0, 10.0);
|
||||
rect(&mut s, 1100.0, 100.0, 10.0, 10.0);
|
||||
s.execute("select.globalEditOptions", &json!({"includeCanvas": false})).unwrap();
|
||||
sel(&mut s, &[key]);
|
||||
assert_eq!(highlights(&s).len(), 1, "the square on the canvas is left out");
|
||||
s.execute("artboard.new", &json!({"x": 1000, "y": 0, "width": 400, "height": 400})).unwrap();
|
||||
sel(&mut s, &[key]);
|
||||
assert_eq!(highlights(&s).len(), 2, "the square is on an artboard now");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_symbol_redrawn_brings_its_instances_onto_the_artboard() {
|
||||
use crate::cmd::globaledit::highlights;
|
||||
let mut s = session();
|
||||
let r = rect(&mut s, 0.0, 0.0, 40.0, 40.0);
|
||||
let key = NodeId(s.execute("symbol.new", &json!({"ids": [r.0], "name": "Tile"})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("symbol.place", &json!({"name": "Tile", "x": 1000, "y": 300})).unwrap();
|
||||
s.execute("select.globalEditOptions", &json!({"includeCanvas": false})).unwrap();
|
||||
sel(&mut s, &[key]);
|
||||
assert!(highlights(&s).is_empty(), "the other instance is on the canvas");
|
||||
// The symbol's art drawn 400 pt to the left: the other instance lies on the artboard.
|
||||
let st = s.doc_mut().unwrap();
|
||||
let d = std::sync::Arc::make_mut(&mut st.doc);
|
||||
let art = std::sync::Arc::make_mut(&mut d.symbols[0].art);
|
||||
art.transform(Affine::translate((-400.0, 0.0)), vectorcraft_doc::Scaling::default());
|
||||
st.revision += 1;
|
||||
assert_eq!(highlights(&s).len(), 1, "the other instance is on the artboard now");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_symbol_instance_put_in_perspective_has_another_size() {
|
||||
use crate::cmd::globaledit::highlights;
|
||||
let mut s = session();
|
||||
s.execute("perspective.grid.preset", &json!({"kind": 2})).unwrap();
|
||||
let r = rect(&mut s, 450.0, 300.0, 100.0, 100.0);
|
||||
let key = NodeId(s.execute("symbol.new", &json!({"ids": [r.0], "name": "Tile"})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("symbol.place", &json!({"name": "Tile", "x": 100, "y": 100})).unwrap();
|
||||
s.execute("select.globalEditOptions", &json!({"size": true})).unwrap();
|
||||
sel(&mut s, &[key]);
|
||||
assert_eq!(highlights(&s).len(), 1);
|
||||
let size = |s: &Session| bounds(s, key).size();
|
||||
let was = size(&s);
|
||||
s.execute("perspective.attach", &json!({"ids": [key.0], "plane": "right"})).unwrap();
|
||||
sel(&mut s, &[key]);
|
||||
assert_ne!(size(&s), was, "the projection changes the instance's size");
|
||||
assert!(highlights(&s).is_empty(), "the other instance has the size the selected one had");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_part_of_a_dynamic_symbol_instance_selected_shows_no_similar_objects() {
|
||||
use crate::cmd::globaledit::highlights;
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
|
||||
let b = rect(&mut s, 20.0, 0.0, 10.0, 10.0);
|
||||
let inst = NodeId(s.execute("symbol.new", &json!({"name": "Pair", "ids": [a.0, b.0], "type": "dynamic"})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("symbol.place", &json!({"name": "Pair", "x": 300, "y": 300})).unwrap();
|
||||
sel(&mut s, &[inst]);
|
||||
assert_eq!(highlights(&s).len(), 1);
|
||||
s.execute("symbol.instance.selectPart", &json!({"id": inst.0, "path": [1]})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().selection.objects, [inst]);
|
||||
assert!(highlights(&s).is_empty(), "Global Edit does not take a part of the art");
|
||||
sel(&mut s, &[inst]);
|
||||
assert_eq!(highlights(&s).len(), 1, "the whole instance again");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_group_selected_inside_a_group_keeps_its_similar_objects_after_a_move() {
|
||||
use crate::cmd::globaledit::{OBJECTS_WALKED, highlights};
|
||||
let walked = || OBJECTS_WALKED.with(std::cell::Cell::get);
|
||||
let mut s = session();
|
||||
let group = |s: &mut Session, ids: &[NodeId]| {
|
||||
sel(s, ids);
|
||||
NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap())
|
||||
};
|
||||
// A group of two squares inside an outer group with a third square, and a copy of both: the
|
||||
// copy's inner group is like the selected inner group.
|
||||
let a = [rect(&mut s, 0.0, 0.0, 10.0, 10.0), rect(&mut s, 20.0, 0.0, 10.0, 10.0)];
|
||||
let inner = group(&mut s, &a);
|
||||
let third = rect(&mut s, 40.0, 0.0, 10.0, 10.0);
|
||||
let outer = group(&mut s, &[inner, third]);
|
||||
let b = [rect(&mut s, 0.0, 100.0, 10.0, 10.0), rect(&mut s, 20.0, 100.0, 10.0, 10.0)];
|
||||
let inner_copy = group(&mut s, &b);
|
||||
let third_copy = rect(&mut s, 40.0, 100.0, 10.0, 10.0);
|
||||
group(&mut s, &[inner_copy, third_copy]);
|
||||
sel(&mut s, &[inner]);
|
||||
let first = highlights(&s);
|
||||
assert_eq!(crate::cmd::globaledit::match_count(&s), 2, "the copy's inner group; the outer group {outer} holds the selected one");
|
||||
assert!(!first.is_empty());
|
||||
s.execute("object.move", &json!({"dx": 5, "dy": 0})).unwrap();
|
||||
let before = walked();
|
||||
assert!(std::sync::Arc::ptr_eq(&highlights(&s), &first));
|
||||
assert_eq!(walked(), before, "the outer group changed with the selected group only");
|
||||
s.execute("select.globalEditOptions", &json!({"size": true})).unwrap();
|
||||
s.execute("select.globalEditOptions", &json!({"size": false})).unwrap();
|
||||
assert_eq!(highlights(&s).groups, first.groups, "a walk finds the same");
|
||||
assert!(walked() > before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_canvas_highlights_similar_objects_before_the_start_with_the_selection_tool_only() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
//! [`DocState::moved`]: a move of whole objects names the documents before and after it and how far
|
||||
//! it went, and only when every object the selection shows is the one before it, moved that far.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_geom::Vec2;
|
||||
|
||||
use crate::*;
|
||||
|
||||
fn session() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn id_of(v: &Value) -> NodeId {
|
||||
NodeId(v["id"].as_u64().unwrap())
|
||||
}
|
||||
|
||||
fn rect(s: &mut Session, x: f64) -> NodeId {
|
||||
id_of(&s.execute("shape.rectangle", &json!({"x": x, "y": 20, "width": 30, "height": 20})).unwrap())
|
||||
}
|
||||
|
||||
fn select(s: &mut Session, ids: &[NodeId]) {
|
||||
s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})).unwrap();
|
||||
}
|
||||
|
||||
fn doc(s: &Session) -> Arc<Document> {
|
||||
s.doc().unwrap().doc.clone()
|
||||
}
|
||||
|
||||
/// The move [`DocState::moved`] names, when it took `from` to the document now.
|
||||
fn moved_from(s: &Session, from: &Arc<Document>) -> Option<Vec2> {
|
||||
let st = s.doc().unwrap();
|
||||
let m = st.moved.as_ref()?;
|
||||
(m.from.as_ptr() == Arc::as_ptr(from) && m.to.as_ptr() == Arc::as_ptr(&st.doc) && m.selection == st.selection).then_some(m.by)
|
||||
}
|
||||
|
||||
// A move of the selection, a nudge and each step of a drag name the move; the drag's steps all start from the
|
||||
// document the drag began with.
|
||||
#[test]
|
||||
fn a_move_of_whole_objects_names_the_documents_and_the_distance() {
|
||||
let mut s = session();
|
||||
let (a, b) = (rect(&mut s, 20.0), rect(&mut s, 80.0));
|
||||
select(&mut s, &[a, b]);
|
||||
let before = doc(&s);
|
||||
s.execute("object.move", &json!({"dx": 12, "dy": -5})).unwrap();
|
||||
assert_eq!(moved_from(&s, &before), Some(Vec2::new(12.0, -5.0)), "Object › Transform › Move");
|
||||
let before = doc(&s);
|
||||
s.execute("object.nudge", &json!({"dx": 1, "dy": 0})).unwrap();
|
||||
assert_eq!(moved_from(&s, &before), Some(Vec2::new(s.prefs.keyboard_increment, 0.0)), "a nudge");
|
||||
|
||||
let start = doc(&s);
|
||||
s.begin_interaction("Move").unwrap();
|
||||
for dx in [3.0, 7.5] {
|
||||
s.preview("object.transform", &json!({"matrix": [1, 0, 0, 1, dx, 2], "copy": false})).unwrap();
|
||||
assert_eq!(moved_from(&s, &start), Some(Vec2::new(dx, 2.0)), "a drag's step by {dx}");
|
||||
}
|
||||
}
|
||||
|
||||
// A copy, a transform that is not a move, a move of patterns alone, a move that also resizes type areas, and a move
|
||||
// of part of what the selection shows name no move.
|
||||
#[test]
|
||||
fn a_copy_a_scale_and_a_move_of_part_of_the_selection_name_no_move() {
|
||||
let mut s = session();
|
||||
let (a, b) = (rect(&mut s, 20.0), rect(&mut s, 80.0));
|
||||
select(&mut s, &[a, b]);
|
||||
let cases = [
|
||||
("object.move", json!({"dx": 12, "dy": 0, "copy": true})),
|
||||
("object.transform", json!({"matrix": [2, 0, 0, 1, 0, 0]})),
|
||||
("object.move", json!({"dx": 12, "dy": 0, "objects": false, "patterns": true})),
|
||||
("object.move", json!({"dx": 12, "dy": 0, "typeAreas": true})),
|
||||
("object.transform", json!({"matrix": [1, 0, 0, 1, 5, 0], "ids": [a.0]})),
|
||||
];
|
||||
for (cmd, p) in cases {
|
||||
select(&mut s, &[a, b]);
|
||||
let before = doc(&s);
|
||||
s.execute(cmd, &p).unwrap();
|
||||
assert_eq!(moved_from(&s, &before), None, "{cmd} {p}");
|
||||
}
|
||||
}
|
||||
|
||||
// The key object is shown too: a move that leaves it where it was names no move.
|
||||
#[test]
|
||||
fn a_key_object_left_where_it_was_names_no_move() {
|
||||
let mut s = session();
|
||||
let (a, b) = (rect(&mut s, 20.0), rect(&mut s, 80.0));
|
||||
select(&mut s, &[a]);
|
||||
s.active_mut().unwrap().selection.key = Some(b);
|
||||
let before = doc(&s);
|
||||
s.execute("object.move", &json!({"dx": 12, "dy": 0})).unwrap();
|
||||
assert_eq!(moved_from(&s, &before), None);
|
||||
}
|
||||
|
||||
// A pixel-aligned path snaps to the pixel grid after the transform, and an instance of a symbol aligned to the pixel
|
||||
// grid snaps after the edit: neither is the object before the move moved by its distance.
|
||||
#[test]
|
||||
fn objects_that_snap_to_the_pixel_grid_name_no_move() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 20.0);
|
||||
select(&mut s, &[a]);
|
||||
s.execute("object.setPixelAligned", &json!({"on": true})).unwrap();
|
||||
let before = doc(&s);
|
||||
s.execute("object.move", &json!({"dx": 0.3, "dy": 0})).unwrap();
|
||||
assert_eq!(moved_from(&s, &before), None, "a pixel-aligned path");
|
||||
|
||||
let mut s = session();
|
||||
let art = rect(&mut s, 20.0);
|
||||
let made = s.execute("symbol.new", &json!({"name": "Box", "ids": [art.0], "alignToPixelGrid": true})).unwrap();
|
||||
select(&mut s, &[id_of(&made)]);
|
||||
let before = doc(&s);
|
||||
s.execute("object.move", &json!({"dx": 0.3, "dy": 0})).unwrap();
|
||||
assert_eq!(moved_from(&s, &before), None, "an instance of a symbol aligned to the pixel grid");
|
||||
}
|
||||
|
||||
// A member of a blend moved on its own changes the blend's spine.
|
||||
#[test]
|
||||
fn a_member_of_a_blend_names_no_move() {
|
||||
let mut s = session();
|
||||
let (a, b) = (rect(&mut s, 20.0), rect(&mut s, 200.0));
|
||||
s.execute("object.blend.make", &json!({"ids": [a.0, b.0], "steps": 1})).unwrap();
|
||||
select(&mut s, &[a]);
|
||||
let before = doc(&s);
|
||||
s.execute("object.move", &json!({"dx": 12, "dy": 0})).unwrap();
|
||||
assert_eq!(moved_from(&s, &before), None);
|
||||
}
|
||||
@@ -247,6 +247,62 @@ fn replace_keeps_the_transform_and_the_stacking_place() {
|
||||
assert_eq!(top_children(&s)[0].id.0, first.as_u64().unwrap(), "one undo step brings the old image back");
|
||||
}
|
||||
|
||||
/// `image.info` reads a PNG's colour mode from its header without decoding its pixels: a grayscale
|
||||
/// PNG whose compressed pixel data is unreadable still says Grayscale. The Control bar asks again
|
||||
/// after every step of a drag, so a decode there redid a large image's whole decode each step.
|
||||
#[test]
|
||||
fn image_color_mode_reads_the_header_without_decoding_the_pixels() {
|
||||
let raw: Vec<u8> = (0..64u32 * 64).map(|i| (i * 7 % 251) as u8).collect();
|
||||
let gray = craft_image_codecs::Image::from_raw(64, 64, craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, raw).unwrap();
|
||||
let mut png = craft_image_codecs::encode(&gray, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap();
|
||||
assert_eq!(cmd::place::color_mode(&png), "Grayscale");
|
||||
// Each IDAT chunk's data zeroed (an invalid zlib stream) under a correct CRC.
|
||||
let mut at = 8;
|
||||
let mut idat = 0;
|
||||
while at + 12 <= png.len() {
|
||||
let len = u32::from_be_bytes(png[at..at + 4].try_into().unwrap()) as usize;
|
||||
if &png[at + 4..at + 8] == b"IDAT" {
|
||||
png[at + 8..at + 8 + len].fill(0);
|
||||
let crc = crc32fast::hash(&png[at + 4..at + 8 + len]);
|
||||
png[at + 8 + len..at + 12 + len].copy_from_slice(&crc.to_be_bytes());
|
||||
idat += 1;
|
||||
}
|
||||
at += 12 + len;
|
||||
}
|
||||
assert!(idat > 0, "the PNG has pixel data");
|
||||
assert!(craft_image_codecs::decode(&png).is_err(), "the pixels no longer decode");
|
||||
assert_eq!(cmd::place::color_mode(&png), "Grayscale", "the header alone gives the colour mode");
|
||||
}
|
||||
|
||||
/// The colour mode read from a file's header is the one its decoded pixels have, in every format
|
||||
/// and channel layout the codecs write.
|
||||
#[test]
|
||||
fn image_color_mode_from_the_header_matches_the_decoded_pixels() {
|
||||
use craft_image_codecs::{ChannelLayout as L, Format as F};
|
||||
let decoded = |bytes: &[u8]| match craft_image_codecs::decode(bytes).map(|i| i.layout()) {
|
||||
Ok(L::Gray | L::GrayA) => "Grayscale",
|
||||
Ok(L::Cmyk | L::CmykA) => "CMYK",
|
||||
Ok(_) => "RGB",
|
||||
Err(e) => panic!("the written file decodes: {e}"),
|
||||
};
|
||||
let mut seen = std::collections::BTreeSet::new();
|
||||
let mut checked = 0;
|
||||
for format in [F::Png, F::Jpeg, F::Tiff, F::Gif, F::Bmp, F::WebP] {
|
||||
for layout in [L::Gray, L::GrayA, L::Rgb, L::Rgba, L::Cmyk] {
|
||||
let n = 16 * 16 * layout.channels();
|
||||
let raw: Vec<u8> = (0..n).map(|i| (i * 13 % 256) as u8).collect();
|
||||
let img = craft_image_codecs::Image::from_raw(16, 16, layout, craft_image_codecs::SampleType::U8, raw).unwrap();
|
||||
let Ok(bytes) = craft_image_codecs::encode(&img, format, &craft_image_codecs::EncodeOptions::default()) else { continue };
|
||||
let want = decoded(&bytes);
|
||||
assert_eq!(cmd::place::color_mode(&bytes), want, "{format:?} written from {layout:?}");
|
||||
seen.insert(want);
|
||||
checked += 1;
|
||||
}
|
||||
}
|
||||
assert!(checked >= 12, "{checked} files written");
|
||||
assert_eq!(seen.into_iter().collect::<Vec<_>>(), ["CMYK", "Grayscale", "RGB"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replace_needs_exactly_one_selected_object() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -2347,29 +2347,35 @@ static STORED_HOOK: std::sync::Mutex<()> = std::sync::Mutex::new(());
|
||||
struct HeldLoad {
|
||||
_lock: std::sync::MutexGuard<'static, ()>,
|
||||
entered: std::sync::Arc<std::sync::atomic::AtomicBool>,
|
||||
go: std::sync::Arc<std::sync::atomic::AtomicBool>,
|
||||
go: std::sync::Arc<(std::sync::Mutex<bool>, std::sync::Condvar)>,
|
||||
gave_up: std::sync::Arc<std::sync::atomic::AtomicBool>,
|
||||
}
|
||||
|
||||
impl HeldLoad {
|
||||
/// Holds the load of the file at `path`. A load the test never lets go gives up after a
|
||||
/// million yields (so a test of code that waits for it ends) and says so in `gave_up`.
|
||||
/// Holds the load of the file at `path` until [`HeldLoad::release`] or the drop. A load that
|
||||
/// runs on the thread that made this one is not held, since nothing could let it go: it goes
|
||||
/// ahead at once and says so in `gave_up`.
|
||||
fn new(path: std::path::PathBuf) -> HeldLoad {
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, Condvar, Mutex};
|
||||
let lock = STORED_HOOK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let (entered, go, gave_up) = (Arc::new(AtomicBool::new(false)), Arc::new(AtomicBool::new(false)), Arc::new(AtomicBool::new(false)));
|
||||
let (entered, gave_up) = (Arc::new(AtomicBool::new(false)), Arc::new(AtomicBool::new(false)));
|
||||
let go = Arc::new((Mutex::new(false), Condvar::new()));
|
||||
let (e, g, q) = (entered.clone(), go.clone(), gave_up.clone());
|
||||
let test_thread = std::thread::current().id();
|
||||
*crate::store::BEFORE_STORED_LOAD.lock().unwrap_or_else(|e| e.into_inner()) = Some(Arc::new(move |p: &std::path::Path| {
|
||||
if p != path {
|
||||
return;
|
||||
}
|
||||
e.store(true, Ordering::SeqCst);
|
||||
if !(0..1_000_000).any(|_| {
|
||||
std::thread::yield_now();
|
||||
g.load(Ordering::SeqCst)
|
||||
}) {
|
||||
if std::thread::current().id() == test_thread {
|
||||
q.store(true, Ordering::SeqCst);
|
||||
return;
|
||||
}
|
||||
let (open, opened) = &*g;
|
||||
let mut open = open.lock().unwrap_or_else(|e| e.into_inner());
|
||||
while !*open {
|
||||
open = opened.wait(open).unwrap_or_else(|e| e.into_inner());
|
||||
}
|
||||
}));
|
||||
HeldLoad { _lock: lock, entered, go, gave_up }
|
||||
@@ -2380,7 +2386,9 @@ impl HeldLoad {
|
||||
}
|
||||
|
||||
fn release(&self) {
|
||||
self.go.store(true, std::sync::atomic::Ordering::SeqCst);
|
||||
let (open, opened) = &*self.go;
|
||||
*open.lock().unwrap_or_else(|e| e.into_inner()) = true;
|
||||
opened.notify_all();
|
||||
}
|
||||
|
||||
fn gave_up(&self) -> bool {
|
||||
@@ -2904,6 +2912,7 @@ fn a_folder_queued_behind_the_stored_plugins_replaces_one_with_its_id() {
|
||||
#[test]
|
||||
fn a_query_runs_while_the_plugins_load() {
|
||||
let id = "test.engine.background.query";
|
||||
assert!(crate::waits_for_plugin_loads("plugin.list") && !crate::waits_for_plugin_loads("document.info"));
|
||||
let (folder, path) = store_with("plugin-background-query", id);
|
||||
let held = HeldLoad::new(path);
|
||||
let mut s = session();
|
||||
@@ -2917,7 +2926,6 @@ fn a_query_runs_while_the_plugins_load() {
|
||||
let waited = held.gave_up() || !s.plugins_loading();
|
||||
held.release();
|
||||
assert!(!waited, "document.info waited for the plug-ins to load");
|
||||
assert!(crate::waits_for_plugin_loads("plugin.list") && !crate::waits_for_plugin_loads("document.info"));
|
||||
s.finish_plugin_loads();
|
||||
assert!(vectorcraft_plugins::registry::remove(id));
|
||||
}
|
||||
@@ -2935,18 +2943,14 @@ fn stored_plugins_load_without_holding_the_plugin_changes_lock() {
|
||||
while !held.entered() && !held.gave_up() {
|
||||
std::thread::yield_now();
|
||||
}
|
||||
// Other tests take the lock for a moment; the load holding it would hold it throughout (a
|
||||
// tenth of the yields the held load waits before it gives up).
|
||||
let free = (0..100_000).any(|_| {
|
||||
// A load run on this thread isn't held, so a free lock then shows nothing.
|
||||
assert!(!held.gave_up(), "the module loaded on the test's thread");
|
||||
// Other tests take the lock for a moment; the held load holding it would hold it until it is let go.
|
||||
while !crate::cmd::plugin::plugin_changes_free() {
|
||||
std::thread::yield_now();
|
||||
crate::cmd::plugin::plugin_changes_free()
|
||||
});
|
||||
// A load that gave up waiting no longer holds anything, so a free lock then shows nothing.
|
||||
let gave_up = held.gave_up();
|
||||
}
|
||||
held.release();
|
||||
s.finish_plugin_loads();
|
||||
assert!(!gave_up, "the held load gave up before the lock was looked at");
|
||||
assert!(free, "the lock was held while the module loaded");
|
||||
assert!(vectorcraft_plugins::registry::remove(id));
|
||||
}
|
||||
|
||||
@@ -2974,6 +2978,10 @@ fn canceled_loads_forget_the_grants_of_what_they_installed() {
|
||||
std::thread::yield_now();
|
||||
}
|
||||
assert!(vectorcraft_plugins::registry::get(first).is_some(), "the first module installed while the second loads");
|
||||
assert!(s.plugins_loading(), "the second module is still loading");
|
||||
// Canceling waits for a running load until its deadline; the second module, let go, loads
|
||||
// while the cancel runs or before it, and doesn't install either way.
|
||||
held.release();
|
||||
s.cancel_plugin_loads();
|
||||
// The file goes once it holds no grant.
|
||||
let listed: Vec<Value> = std::fs::read(&grants).map(|b| serde_json::from_slice(&b).unwrap()).unwrap_or_default();
|
||||
|
||||
@@ -235,7 +235,7 @@ fn shift_click_direct_selection_and_hover_on_a_drop_shadow_pass_through_it() {
|
||||
run(&mut s, "select.set", json!({"ids": [a.0]}));
|
||||
let v = ViewInfo::default();
|
||||
s.select_tool("selection", v).unwrap();
|
||||
assert_eq!(s.cursor(Point::new(50.0, 50.0), Mods::default(), v), Cursor::Move);
|
||||
assert_eq!(s.cursor(Point::new(50.0, 50.0), Mods::default(), v), Cursor::SelectionMove);
|
||||
assert_eq!(s.cursor(Point::new(110.0, 50.0), Mods::default(), v), Cursor::Arrow);
|
||||
assert_eq!(s.cursor(Point::new(92.0, 50.0), Mods::default(), v), Cursor::Arrow);
|
||||
}
|
||||
|
||||
@@ -1002,6 +1002,10 @@ fn structured_junk() {
|
||||
("addon.arrange.replace", json!({"fit": "bounds", "scaleStrokes": true})),
|
||||
("addon.arrange.size", json!({"width": 1e6, "height": 0.001, "reference": 8, "scaleStrokes": true})),
|
||||
("addon.arrange.size", json!({"width": 0.001, "proportional": true, "reference": u64::MAX})),
|
||||
("addon.arrange.match", json!({"size": "both", "rotate": true, "stacking": true, "reference": 8, "scaleStrokes": true})),
|
||||
("addon.arrange.match", json!({"source": "bottom", "size": "width", "patterns": true})),
|
||||
("addon.arrange.match", json!({"source": "key", "rotate": true})),
|
||||
("addon.arrange.match", json!({"source": "nope", "size": 3, "rotate": "x", "reference": u64::MAX})),
|
||||
("addon.arrange.groupOverlapping", json!({"ids": "x", "junk": f64::MAX})),
|
||||
("addon.arrange.randomizeOpacity", json!({"min": 0, "max": 100, "seed": u64::MAX})),
|
||||
("addon.arrange.randomizeOpacity", json!({"min": f64::MAX, "max": -1e308, "seed": -1, "ids": [u64::MAX]})),
|
||||
|
||||
@@ -338,32 +338,78 @@ fn made_content(infos: &[SlotInfo], made: Vec<Option<Made>>, laid: bool) -> Vec<
|
||||
/// it, as far as strokes round type reach) as type the page draws. How many of the page's text
|
||||
/// objects no made type takes, shown or not: none that holds a piece of the object has its words
|
||||
/// ([`spelling`]). Past `MAX_PAIRS` comparisons nothing is marked or counted (`None`).
|
||||
///
|
||||
/// The page can draw two text objects as one word: a word and a letter set apart from it (a swash
|
||||
/// "h" after "Spirit") come out of the page as one piece, "Spirith", that neither spells. A word
|
||||
/// left that is the last word of one text object holding the piece joined to the first word of
|
||||
/// another that holds it and draws after it, along the first one's lines, is theirs
|
||||
/// ([`joined_by_two`]).
|
||||
fn see_page_type(content: &mut [Content], shown: &[Vec<Arc<Node>>]) -> Option<usize> {
|
||||
let texts = |o: &[Arc<Node>]| o.iter().filter_map(|n| if let NodeKind::Text(_) = &n.kind { Some(n.clone()) } else { None }).collect::<Vec<_>>();
|
||||
// Each object's pieces of type, and the words of them that no made type holding it has yet.
|
||||
let mut objects: Vec<(Vec<Rect>, Vec<String>, bool)> =
|
||||
shown.iter().map(|o| (texts(o).iter().filter_map(|n| n.visual_bounds()).collect(), object_words(o), false)).collect();
|
||||
let pieces: usize = objects.iter().map(|o| o.0.len()).sum();
|
||||
if content.len().saturating_mul(pieces) > MAX_PAIRS {
|
||||
return None;
|
||||
}
|
||||
let mut budget = MAX_PAIRS.checked_sub(content.len().checked_mul(pieces)?)?;
|
||||
let holds = |drawn: Rect, r: &Rect| drawn.inflate(OUTLINE_REACH, OUTLINE_REACH).intersect(*r).area() >= 0.5 * r.area().max(1e-9);
|
||||
for c in content {
|
||||
let Content::Made(node, region, seen) = c else { continue };
|
||||
// The made type holding each object, in order: where it draws and its words.
|
||||
let mut holders: Vec<Vec<Arc<Holder>>> = vec![vec![]; objects.len()];
|
||||
let mut seen_slots = Vec::new();
|
||||
for (slot, c) in content.iter().enumerate() {
|
||||
let Content::Made(node, region, _) = c else { continue };
|
||||
// Hidden made type has no region: where it draws, shown, is its own box.
|
||||
let Some(drawn) = region.or_else(|| node.visual_bounds()) else { continue };
|
||||
let spelled = if let NodeKind::Text(t) = &node.kind { spelling(&t.plain_text()) } else { String::new() };
|
||||
for (rects, words, held) in &mut objects {
|
||||
let (spelled, holder) = match &node.kind {
|
||||
NodeKind::Text(t) => {
|
||||
let text = t.plain_text();
|
||||
let [a, b, ..] = t.xf.as_coeffs();
|
||||
(spelling(&text), Some(Arc::new((drawn.center(), (a, b), word_pieces(&text).map(spelling).filter(|w| !w.is_empty()).collect()))))
|
||||
}
|
||||
_ => (String::new(), None),
|
||||
};
|
||||
for ((rects, words, held), by) in objects.iter_mut().zip(&mut holders) {
|
||||
if rects.iter().any(|r| holds(drawn, r)) {
|
||||
*held = true;
|
||||
*seen |= region.is_some();
|
||||
if region.is_some() && seen_slots.last() != Some(&slot) {
|
||||
seen_slots.push(slot);
|
||||
}
|
||||
words.retain(|w| !spelled.contains(w.as_str()));
|
||||
by.extend(holder.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
for ((_, words, _), by) in objects.iter_mut().zip(&holders) {
|
||||
if !words.is_empty() && !by.is_empty() {
|
||||
// Each unmatched word can visit every ordered pair of holders, plus the first-holder scan.
|
||||
budget = budget.checked_sub(words.len().checked_mul(by.len())?.checked_mul(by.len().checked_add(1)?)?)?;
|
||||
words.retain(|w| !joined_by_two(w, by));
|
||||
}
|
||||
}
|
||||
for slot in seen_slots {
|
||||
if let Content::Made(_, _, seen) = &mut content[slot] {
|
||||
*seen = true;
|
||||
}
|
||||
}
|
||||
Some(objects.iter().filter(|(_, words, held)| !held || !words.is_empty()).count())
|
||||
}
|
||||
|
||||
/// A made text object that holds a piece of the page's type: the centre of where it draws, the
|
||||
/// way its lines run (the first column of its transform) and its words ([`spelling`]).
|
||||
type Holder = (Point, (f64, f64), Vec<String>);
|
||||
|
||||
/// Is `word` (a [`spelling`]) the last word of one of `by` joined to the first word of another of
|
||||
/// them that draws after it, along the first one's lines? Each part is a whole word of its text
|
||||
/// object, so a piece is never made up of bits of words.
|
||||
fn joined_by_two(word: &str, by: &[Arc<Holder>]) -> bool {
|
||||
by.iter().map(Arc::as_ref).any(|(at, (a, b), first)| {
|
||||
let Some(head) = first.last().filter(|h| word.len() > h.len() && word.starts_with(h.as_str())) else { return false };
|
||||
let tail = &word[head.len()..];
|
||||
by.iter()
|
||||
.map(Arc::as_ref)
|
||||
.any(|(next, _, second)| (next.x - at.x) * a + (next.y - at.y) * b > 0.0 && second.first().is_some_and(|w| w == tail))
|
||||
})
|
||||
}
|
||||
|
||||
/// What goes into each of `infos`' slots when the file's text document can't make the type of every
|
||||
/// slot that shows: type made from the text document (`made`) where it can, else the page's type that
|
||||
/// the text document puts where the page has it, else the page's type in a copy that a layer's or
|
||||
|
||||
@@ -8663,3 +8663,35 @@ fn trusted_editing_data_keeps_an_artboard_taller_than_its_pdf_page() {
|
||||
let (_, w, read) = crate::layered_ai(&private(&art), Document::new(12000.0, 14400.0), vec![], false, true, 1.0);
|
||||
assert!(!read, "the uncapped dimension must still match: {w:?}");
|
||||
}
|
||||
|
||||
/// The page's "2014" drawn as one piece 20 points across the art, and two text objects "20" and
|
||||
/// "14" anchored at `twenty` and `fourteen`, set in the bundled Source Sans 3 at 14 points (a digit
|
||||
/// 6.958 points wide) so that where they draw doesn't hang on the fonts installed.
|
||||
fn word_of_two_text_objects(fourteen: f64, twenty: f64) -> crate::import::Imported {
|
||||
let stories = [("20\r", 0, (twenty, 8180.0), (0.0, 0.0), 0.0), ("14\r", 0, (fourteen, 8180.0), (0.0, 0.0), 0.0)];
|
||||
let doc = text_document(&stories).replacen("/0 (Helvetica)", "/0 (SourceSans3-Regular)", 1);
|
||||
let art = native_with_text(&layer("Art", true, &(text_object(0) + &text_object(1))), &doc);
|
||||
let page = "0 1 0 0 setcmykcolor /SourceSans3-Regular findfont 14 scalefont setfont 20 61.5 moveto (2014) show";
|
||||
import(&eps(page, &art)).unwrap()
|
||||
}
|
||||
|
||||
/// The page can draw two text objects as one word: "20" and "14" set one after the other come out
|
||||
/// of the page as one piece, "2014", that neither spells. The word is the last word of the one
|
||||
/// joined to the first word of the one after it, so the page's type is theirs and nothing is noted
|
||||
/// as left out.
|
||||
#[test]
|
||||
fn a_word_the_page_draws_from_two_text_objects_in_a_row_is_their_type() {
|
||||
let r = word_of_two_text_objects(8161.5 + 13.916, 8161.5);
|
||||
assert_eq!(names(&r.document), ["Art"], "{:?}", r.warnings);
|
||||
let texts: Vec<String> = text_of(&r.document.layers[0]).iter().map(|t| t.plain_text()).collect();
|
||||
assert_eq!(texts, ["20", "14"], "{:?}", r.warnings);
|
||||
assert!(!r.warnings.iter().any(|w| crate::is_loss(w)), "{:?}", r.warnings);
|
||||
}
|
||||
|
||||
/// The two text objects the other way round ("14" before "20") don't make the page's "2014": its
|
||||
/// word keeps the loss note.
|
||||
#[test]
|
||||
fn two_text_objects_the_other_way_round_arent_the_word_the_page_draws() {
|
||||
let r = word_of_two_text_objects(8161.5, 8161.5 + 13.916);
|
||||
assert!(r.warnings.iter().any(|w| w.contains("some of the page's type has no text object in the layers")), "{:?}", r.warnings);
|
||||
}
|
||||
|
||||
@@ -801,7 +801,7 @@ fn digits_unnamed(text: &str) -> Vec<u8> {
|
||||
out
|
||||
}
|
||||
|
||||
/// #708, #811: a glyph whose ToUnicode value is U+FFFD isn't type showing "�". This subset font
|
||||
/// #708, #811: a glyph whose ToUnicode value is U+FFFD isn't type showing `\u{FFFD}`. This subset font
|
||||
/// has no character map of its own, but the font is installed: each digit is found by its outline
|
||||
/// there, so the whole text stays one type object, with no outlines left behind.
|
||||
#[test]
|
||||
|
||||
@@ -8,35 +8,5 @@
|
||||
startup | Noto Sans Arabic | Regular
|
||||
startup | Noto Sans Thai | Regular
|
||||
startup | Noto Sans Georgian | Regular
|
||||
background | Cairo | Regular
|
||||
background | Tajawal | ExtraLight
|
||||
background | Tajawal | Light
|
||||
background | Tajawal | Regular
|
||||
background | Tajawal | Medium
|
||||
background | Tajawal | Bold
|
||||
background | Tajawal | ExtraBold
|
||||
background | Tajawal | Black
|
||||
background | Almarai | Light
|
||||
background | Almarai | Regular
|
||||
background | Almarai | Bold
|
||||
background | Almarai | ExtraBold
|
||||
background | IBM Plex Sans Arabic | Thin
|
||||
background | IBM Plex Sans Arabic | ExtraLight
|
||||
background | IBM Plex Sans Arabic | Light
|
||||
background | IBM Plex Sans Arabic | Regular
|
||||
background | IBM Plex Sans Arabic | Medium
|
||||
background | IBM Plex Sans Arabic | SemiBold
|
||||
background | IBM Plex Sans Arabic | Bold
|
||||
background | Noto Kufi Arabic | Regular
|
||||
background | Amiri | Regular
|
||||
background | Amiri | Italic
|
||||
background | Amiri | Bold
|
||||
background | Amiri | Bold Italic
|
||||
background | Alexandria | Regular
|
||||
background | Fustat | Regular
|
||||
background | Reem Kufi | Regular
|
||||
background | Aref Ruqaa | Regular
|
||||
background | Aref Ruqaa | Bold
|
||||
background | Gulzar | Regular
|
||||
demand | NanumGothic | Regular
|
||||
demand | Noto Sans Devanagari | Regular
|
||||
|
||||
@@ -17,6 +17,8 @@ pub enum Cursor {
|
||||
GroupSelection,
|
||||
/// Alt-dragging a copy with the Selection or Direct Selection tool: a double arrowhead.
|
||||
SelectionCopy,
|
||||
/// The Selection arrow over movable artwork.
|
||||
SelectionMove,
|
||||
Move,
|
||||
Crosshair,
|
||||
ResizeH,
|
||||
|
||||
@@ -129,11 +129,20 @@ shown_when = [
|
||||
hotspot = "The arrow's tip."
|
||||
look = "Arrow with a small x badge (nothing to select)."
|
||||
|
||||
[[cursor]]
|
||||
id = "SelectionMove"
|
||||
group = "Selection"
|
||||
shown_when = [
|
||||
"The Selection tool over a selected object or its movable source artwork, or over its visible centre point without Cmd/Ctrl held.",
|
||||
"The Selection tool over artwork while Alt is held, before the copy drag begins.",
|
||||
]
|
||||
hotspot = "The arrow's tip."
|
||||
look = "The Selection arrow with a small move badge."
|
||||
|
||||
[[cursor]]
|
||||
id = "Move"
|
||||
group = "Selection"
|
||||
shown_when = [
|
||||
"The Selection tool over a selected object, or over any object with Alt held (once an Alt-drag starts, SelectionCopy shows).",
|
||||
"The shape tools over a selected object's centre point (Attributes › Show Center), before a press there moves it (while the drag runs the arrow is plain, SelectionCopy with Alt, ArrowHollow while it snaps).",
|
||||
"Reshape over a path or while dragging.",
|
||||
"Inside the Free Transform and Crop Image boxes.",
|
||||
|
||||
@@ -1552,7 +1552,7 @@ impl Tool for SelectionTool {
|
||||
// take the pointer too (on a thin box the centre lies within a handle's reach), and with
|
||||
// Cmd/Ctrl held the press selects the object behind instead.
|
||||
if near_selected && !m.cmd && hit_center(cx, p, cx.point_tol()).is_some() {
|
||||
return Cursor::Move;
|
||||
return Cursor::SelectionMove;
|
||||
}
|
||||
// View → Snap to Point: over an anchor a press would grab the object by, the arrow turns
|
||||
// hollow.
|
||||
@@ -1560,11 +1560,11 @@ impl Tool for SelectionTool {
|
||||
return Cursor::ArrowHollow;
|
||||
}
|
||||
if selected_source_hit(cx, p).is_some() {
|
||||
return Cursor::Move;
|
||||
return Cursor::SelectionMove;
|
||||
}
|
||||
if let Some(h) = hit_test(cx.doc, p, cx.selection_hit_options()) {
|
||||
if selected_under(cx, &h, h.top_object(cx.isolation)).is_some() || m.alt {
|
||||
return Cursor::Move;
|
||||
return Cursor::SelectionMove;
|
||||
}
|
||||
return Cursor::Arrow;
|
||||
}
|
||||
|
||||
@@ -17,7 +17,7 @@ fn a_press_on_a_selected_shaper_source_moves_it_while_a_mask_is_edited() {
|
||||
let c = ToolContext { isolation: Some(layer), ..cx(&d, &s, &p) };
|
||||
for x in [75.0, 125.0] {
|
||||
let mut t = SelectionTool::default();
|
||||
assert_eq!(t.cursor(&c, Point::new(x, 350.0), Mods::default()), Cursor::Move, "at {x}");
|
||||
assert_eq!(t.cursor(&c, Point::new(x, 350.0), Mods::default()), Cursor::SelectionMove, "at {x}");
|
||||
let down = t.pointer(&c, &ev(PointerKind::Down, x, 350.0));
|
||||
assert!(!down.iter().any(|a| matches!(a, Action::Exec(c, _) if c == "select.set")), "at {x}: {down:?}");
|
||||
let drag = t.pointer(&c, &ev(PointerKind::Drag, x + 20.0, 350.0));
|
||||
@@ -45,7 +45,7 @@ fn a_selected_shaper_source_moves_after_other_objects_and_behind_front_art() {
|
||||
s.set([rect, ids[1]]);
|
||||
let c = ToolContext { isolation: Some(layer), ..cx(&d, &s, &p) };
|
||||
let mut t = SelectionTool::default();
|
||||
assert_eq!(t.cursor(&c, Point::new(125.0, 350.0), Mods::default()), Cursor::Move);
|
||||
assert_eq!(t.cursor(&c, Point::new(125.0, 350.0), Mods::default()), Cursor::SelectionMove);
|
||||
let down = t.pointer(&c, &ev(PointerKind::Down, 125.0, 350.0));
|
||||
assert!(!down.iter().any(|a| matches!(a, Action::Exec(c, _) if c == "select.set")), "{down:?}");
|
||||
let drag = t.pointer(&c, &ev(PointerKind::Drag, 145.0, 350.0));
|
||||
@@ -55,7 +55,7 @@ fn a_selected_shaper_source_moves_after_other_objects_and_behind_front_art() {
|
||||
d.insert(Some(layer), 2, Node::path(front, square, Appearance::default_art())).unwrap();
|
||||
s.set([ids[1]]);
|
||||
let c = ToolContext { isolation: Some(layer), ..cx(&d, &s, &p) };
|
||||
assert_ne!(SelectionTool::default().cursor(&c, Point::new(125.0, 350.0), Mods::default()), Cursor::Move);
|
||||
assert_ne!(SelectionTool::default().cursor(&c, Point::new(125.0, 350.0), Mods::default()), Cursor::SelectionMove);
|
||||
let down = SelectionTool::default().pointer(&c, &ev(PointerKind::Down, 125.0, 350.0));
|
||||
assert!(down.iter().any(|a| matches!(a, Action::Exec(c, v) if c == "select.set" && v["ids"] == json!([front.0]))), "{down:?}");
|
||||
}
|
||||
@@ -1042,7 +1042,7 @@ fn hidden_box_handles_take_no_press_while_anchors_are_selected() {
|
||||
s.anchors.entry(id).or_default().insert((0, 1));
|
||||
let c = cx(&d, &s, &p);
|
||||
let mut t = SelectionTool::default();
|
||||
assert_eq!(t.cursor(&c, top_middle, Mods::default()), Cursor::Move);
|
||||
assert_eq!(t.cursor(&c, top_middle, Mods::default()), Cursor::SelectionMove);
|
||||
let down = t.pointer(&c, &ev(PointerKind::Down, 150.0, 100.0));
|
||||
assert!(!down.contains(&Action::Begin("Scale".into())), "{down:?}");
|
||||
assert!(!crate::select::bbox_handle_at(&c, top_middle));
|
||||
@@ -3006,9 +3006,9 @@ fn a_press_on_the_centre_point_moves_an_unfilled_shape() {
|
||||
let c = ToolContext { path_only: true, ..cx(&d, &s, &p) };
|
||||
let centre = Point::new(150.0, 150.0);
|
||||
let mut t = SelectionTool::default();
|
||||
assert_eq!(t.cursor(&c, centre, Mods::default()), Cursor::Move);
|
||||
assert_eq!(t.cursor(&c, centre, Mods::default()), Cursor::SelectionMove);
|
||||
// Cmd/Ctrl selects the object behind, not the centre point, so the pointer says neither.
|
||||
assert_ne!(t.cursor(&c, centre, Mods { cmd: true, ..Mods::default() }), Cursor::Move);
|
||||
assert_ne!(t.cursor(&c, centre, Mods { cmd: true, ..Mods::default() }), Cursor::SelectionMove);
|
||||
assert!(t.pointer(&c, &ev(PointerKind::Down, centre.x, centre.y)).is_empty());
|
||||
let a = t.pointer(&c, &ev(PointerKind::Drag, 170.0, 160.0));
|
||||
assert_eq!(a.first(), Some(&Action::Begin("Move".into())), "{a:?}");
|
||||
@@ -3102,7 +3102,7 @@ fn a_ruler_guide_under_the_centre_point_keeps_the_pointer() {
|
||||
assert!(hit_center(&c, centre, c.point_tol()).is_some());
|
||||
let mut t = SelectionTool::default();
|
||||
let cursor = t.cursor(&c, centre, Mods::default());
|
||||
assert_ne!(cursor, Cursor::Move, "the guide's cursor, not the move arrow");
|
||||
assert_ne!(cursor, Cursor::SelectionMove, "the guide's cursor, not the move arrow");
|
||||
let down = t.pointer(&c, &ev(PointerKind::Down, centre.x, centre.y));
|
||||
let drag = t.pointer(&c, &ev(PointerKind::Drag, 170.0, 150.0));
|
||||
assert!(drag.iter().any(|a| matches!(a, Action::Preview(cmd, _) if cmd == "guide.move")), "the guide drags: {down:?} {drag:?}");
|
||||
@@ -3177,7 +3177,7 @@ fn a_press_on_a_selected_member_of_a_group_moves_the_selected_members() {
|
||||
s.set(picked.iter().copied());
|
||||
let c = cx(&d, &s, &p);
|
||||
let mut t = SelectionTool::default();
|
||||
assert_eq!(t.cursor(&c, Point::new(125.0, 125.0), Mods::default()), Cursor::Move, "{picked:?}");
|
||||
assert_eq!(t.cursor(&c, Point::new(125.0, 125.0), Mods::default()), Cursor::SelectionMove, "{picked:?}");
|
||||
let down = t.pointer(&c, &ev(PointerKind::Down, 125.0, 125.0));
|
||||
assert!(!is_select(&down), "{picked:?}: {down:?}");
|
||||
let drag = t.pointer(&c, &ev(PointerKind::Drag, 145.0, 125.0));
|
||||
@@ -3218,7 +3218,7 @@ fn a_press_on_a_selected_member_of_a_group_moves_the_selected_members() {
|
||||
s.anchors.insert(a, [(0, 0), (0, 1), (0, 2), (0, 3)].into_iter().collect());
|
||||
let c = cx(&d, &s, &p);
|
||||
let mut t = SelectionTool::default();
|
||||
assert_eq!(t.cursor(&c, Point::new(125.0, 125.0), Mods::default()), Cursor::Move, "every anchor");
|
||||
assert_eq!(t.cursor(&c, Point::new(125.0, 125.0), Mods::default()), Cursor::SelectionMove, "every anchor");
|
||||
let down = t.pointer(&c, &ev(PointerKind::Down, 125.0, 125.0));
|
||||
assert!(!is_select(&down), "every anchor: {down:?}");
|
||||
}
|
||||
|
||||
@@ -104,6 +104,7 @@ vectorcraft-testkit = { workspace = true }
|
||||
vectorcraft-tools = { workspace = true, features = ["testing"] }
|
||||
# A variable font built in code (no font file is committed).
|
||||
vectorcraft-text = { workspace = true, features = ["test-fonts"] }
|
||||
vectorcraft-plugins = { workspace = true, features = ["test-steady"] }
|
||||
wat = { workspace = true }
|
||||
|
||||
[build-dependencies]
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! Arrange Tools in the interface: its submenu (Object › Plug-ins › Arrange Tools); the dialogs of
|
||||
//! Arrange in Grid, Offset Objects, Replace with Top Object, Set Size of Each, Randomize Opacity and Sort Objects,
|
||||
//! Arrange in Grid, Offset Objects, Replace with Top Object, Set Size of Each, Match Objects, Randomize Opacity and
|
||||
//! Sort Objects,
|
||||
//! which preview on the canvas and run their `addon.arrange.*` command on OK; Group Overlapping
|
||||
//! Objects; and Zoom to Selection ([`ZOOM`]), which fits the active view to the selection.
|
||||
|
||||
@@ -25,14 +26,16 @@ const GRID: &str = "addon.arrange.grid";
|
||||
const OFFSET: &str = "addon.arrange.offset";
|
||||
const REPLACE: &str = "addon.arrange.replace";
|
||||
const SIZE: &str = "addon.arrange.size";
|
||||
const MATCH: &str = "addon.arrange.match";
|
||||
const OPACITY: &str = "addon.arrange.randomizeOpacity";
|
||||
const SORT: &str = "addon.arrange.sort";
|
||||
/// Each dialog's command and heading.
|
||||
const DIALOGS: [(&str, &str); 6] = [
|
||||
const DIALOGS: [(&str, &str); 7] = [
|
||||
(GRID, "Arrange in Grid"),
|
||||
(OFFSET, "Offset Objects"),
|
||||
(REPLACE, "Replace with Top Object"),
|
||||
(SIZE, "Set Size of Each"),
|
||||
(MATCH, "Match Objects"),
|
||||
(OPACITY, "Randomize Opacity"),
|
||||
(SORT, "Sort Objects"),
|
||||
];
|
||||
@@ -63,6 +66,7 @@ pub fn menu() -> Vec<Node> {
|
||||
cp("Swap Objects and Sizes", "addon.arrange.swap", json!({ "size": true })),
|
||||
c("Replace with Top Object…", REPLACE),
|
||||
c("Set Size of Each…", SIZE),
|
||||
c("Match Objects…", MATCH),
|
||||
cp("Group Overlapping Objects", "addon.arrange.groupOverlapping", json!({})),
|
||||
c("Randomize Opacity…", OPACITY),
|
||||
c("Sort Objects…", SORT),
|
||||
@@ -75,6 +79,7 @@ static GRID_SPEC: Spec = Spec { command: GRID, params: grid_params, found: None
|
||||
static OFFSET_SPEC: Spec = Spec { command: OFFSET, params: offset_params, found: None };
|
||||
static REPLACE_SPEC: Spec = Spec { command: REPLACE, params: replace_params, found: None };
|
||||
static SIZE_SPEC: Spec = Spec { command: SIZE, params: size_params, found: None };
|
||||
static MATCH_SPEC: Spec = Spec { command: MATCH, params: match_params, found: None };
|
||||
static OPACITY_SPEC: Spec = Spec { command: OPACITY, params: opacity_params, found: None };
|
||||
static SORT_SPEC: Spec = Spec { command: SORT, params: sort_params, found: None };
|
||||
|
||||
@@ -149,6 +154,20 @@ fn size_rows(lengths: LengthUnits) -> Vec<Param> {
|
||||
]
|
||||
}
|
||||
|
||||
fn match_rows() -> Vec<Param> {
|
||||
let sources = [("key", "Key Object"), ("top", "Top Object"), ("bottom", "Bottom Object")];
|
||||
let sizes = [("none", "None"), ("width", "Width"), ("height", "Height"), ("both", "Width and Height")];
|
||||
vec![
|
||||
choice("source", "Match To:", &sources, "key"),
|
||||
choice("size", "Size:", &sizes, "both"),
|
||||
check("rotate", "Rotation", false),
|
||||
check("stacking", "Stacking Order", false),
|
||||
reference_param("reference", tl!("Reference Point")),
|
||||
scale_strokes().enabled_when_in("size", ["width", "height", "both"]),
|
||||
check("patterns", "Transform Patterns", false),
|
||||
]
|
||||
}
|
||||
|
||||
fn opacity_rows() -> Vec<Param> {
|
||||
vec![percent("min", "Minimum:", 30.0), percent("max", "Maximum:", 100.0), seed()]
|
||||
}
|
||||
@@ -192,6 +211,10 @@ fn size_params(fields: &DialogFields) -> Value {
|
||||
Value::Object(params)
|
||||
}
|
||||
|
||||
fn match_params(fields: &DialogFields) -> Value {
|
||||
Value::Object(form::json_of(&match_rows(), fields))
|
||||
}
|
||||
|
||||
fn opacity_params(fields: &DialogFields) -> Value {
|
||||
Value::Object(form::json_of(&opacity_rows(), fields))
|
||||
}
|
||||
@@ -205,6 +228,7 @@ pub(crate) fn open(app: &mut VectorcraftApp, id: &str) -> Option<Result<Value, S
|
||||
let &(command, _) = DIALOGS.iter().find(|(command, _)| *command == id)?;
|
||||
let st = app.session.active()?;
|
||||
let strokes = app.session.prefs.scale_strokes;
|
||||
let key = st.selection.key.is_some();
|
||||
let lengths = general_lengths(app);
|
||||
let (rows, opening) = match command {
|
||||
// A square grid to start with: as many columns as the square root of the count.
|
||||
@@ -217,6 +241,14 @@ pub(crate) fn open(app: &mut VectorcraftApp, id: &str) -> Option<Result<Value, S
|
||||
),
|
||||
OFFSET => (offset_rows(lengths), json!({ "direction": "row", "gap": 10, "order": "stacking", "reverse": false })),
|
||||
REPLACE => (replace_rows(), json!({ "fit": "keep", "keep": false, "scaleStrokes": strokes })),
|
||||
// The key object while the selection has one, else the top object.
|
||||
MATCH => (
|
||||
match_rows(),
|
||||
json!({
|
||||
"source": if key { "key" } else { "top" }, "size": "both", "rotate": false, "stacking": false,
|
||||
"reference": 4, "scaleStrokes": strokes, "patterns": app.session.prefs.transform_pattern_tiles,
|
||||
}),
|
||||
),
|
||||
// A new seed each time the document has changed, so running it again varies the result.
|
||||
OPACITY => (opacity_rows(), json!({ "min": 30, "max": 100, "seed": st.revision % SEEDS })),
|
||||
// The random order's seed (not shown): new whenever the document has changed, so each run
|
||||
@@ -245,6 +277,14 @@ pub(crate) fn open(app: &mut VectorcraftApp, id: &str) -> Option<Result<Value, S
|
||||
GRID => super::dialogs::open(app, &GRID_SPEC, fields, move |fields| dialog(GRID, grid_rows(lengths)).values(Bind::bound(fields))),
|
||||
OFFSET => super::dialogs::open(app, &OFFSET_SPEC, fields, move |fields| dialog(OFFSET, offset_rows(lengths)).values(Bind::bound(fields))),
|
||||
REPLACE => super::dialogs::open(app, &REPLACE_SPEC, fields, |fields| dialog(REPLACE, replace_rows()).values(Bind::bound(fields))),
|
||||
MATCH => super::dialogs::open(app, &MATCH_SPEC, fields, move |fields| {
|
||||
let chosen = fields.text("size").is_some_and(|size| size != "none")
|
||||
|| fields.bool("rotate") == Some(true)
|
||||
|| fields.bool("stacking") == Some(true);
|
||||
let source = key || fields.text("source") != Some("key");
|
||||
let reason = if source { tl!("Choose Size, Rotation or Stacking Order.") } else { tl!("The selection has no key object.") };
|
||||
dialog(MATCH, match_rows()).ok_enabled(chosen && source).ok_reason(reason.into()).values(Bind::bound(fields))
|
||||
}),
|
||||
OPACITY => super::dialogs::open(app, &OPACITY_SPEC, fields, |fields| {
|
||||
let (min, max) = (fields.number("min").unwrap_or(0.0), fields.number("max").unwrap_or(100.0));
|
||||
dialog(OPACITY, opacity_rows()).ok_enabled(min <= max).values(Bind::bound(fields))
|
||||
|
||||
@@ -231,6 +231,59 @@ fn set_size_of_each_sets_the_sides_ticked() {
|
||||
assert_eq!((bounds(&app, b).width(), bounds(&app, b).height()), (30.0, 40.0));
|
||||
}
|
||||
|
||||
fn layer_order(app: &VectorcraftApp) -> Vec<NodeId> {
|
||||
app.session.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|n| n.id).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn real_match_keyboard_edits_preview_confirm_and_cancel() {
|
||||
let (app, a, b) = app();
|
||||
let steps = |app: &VectorcraftApp| app.session.doc().unwrap().history.undo.len();
|
||||
let before = steps(&app);
|
||||
let mut panel = Harness::new(app, crate::tests::picks::dialogs);
|
||||
click(&mut panel.app(), "Match Objects…");
|
||||
panel.frame();
|
||||
let id = host::dialog_id(&panel.app());
|
||||
// No key object: it opens on the top object, b, and previews its size on a.
|
||||
assert_eq!(
|
||||
host::read(&panel.app(), id, |f| (f.text("source").map(str::to_owned), f.text("size").map(str::to_owned))),
|
||||
(Some("top".into()), Some("both".into()))
|
||||
);
|
||||
assert_eq!(bounds(&panel.app(), a), vectorcraft_geom::Rect::new(-10.0, -15.0, 30.0, 25.0));
|
||||
panel.focus("Stacking Order");
|
||||
panel.key(egui::Key::Space, egui::Modifiers::NONE);
|
||||
panel.frame();
|
||||
assert_eq!(host::read(&panel.app(), id, |f| f.bool("stacking")), Some(true));
|
||||
assert_eq!(layer_order(&panel.app()), [b, a], "the preview puts a above b");
|
||||
panel.click("Cancel");
|
||||
panel.frame();
|
||||
{
|
||||
let app = panel.app();
|
||||
assert_eq!((bounds(&app, a), layer_order(&app), steps(&app)), (vectorcraft_geom::Rect::new(0.0, 0.0, 20.0, 10.0), vec![a, b], before));
|
||||
}
|
||||
click(&mut panel.app(), "Match Objects…");
|
||||
panel.frame();
|
||||
let id = host::dialog_id(&panel.app());
|
||||
host::set(&panel.app(), id, "size", json!("none"));
|
||||
panel.frame();
|
||||
assert!(!panel.enabled("OK"), "nothing to match");
|
||||
host::set(&panel.app(), id, "size", json!("width"));
|
||||
host::set(&panel.app(), id, "source", json!("key"));
|
||||
panel.frame();
|
||||
assert!(!panel.enabled("OK"), "the selection has no key object");
|
||||
host::set(&panel.app(), id, "source", json!("bottom"));
|
||||
panel.frame();
|
||||
assert!(panel.enabled("OK"));
|
||||
panel.click("OK");
|
||||
panel.frame();
|
||||
let app = panel.app();
|
||||
assert!(!app.any_dialog_open());
|
||||
// b takes a's width, its height in proportion, as one undo step.
|
||||
assert_eq!(bounds(&app, b), vectorcraft_geom::Rect::new(110.0, 110.0, 130.0, 130.0));
|
||||
assert_eq!(bounds(&app, a), vectorcraft_geom::Rect::new(0.0, 0.0, 20.0, 10.0));
|
||||
assert_eq!(steps(&app), before + 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replace_opens_with_the_scale_strokes_preference_and_swap_runs_directly() {
|
||||
let (mut app, a, b) = app();
|
||||
|
||||
@@ -134,10 +134,12 @@ impl VectorcraftApp {
|
||||
print_tiling: None,
|
||||
live_paint_gaps: None,
|
||||
find_font: None,
|
||||
missing_fonts: vec![],
|
||||
hidden_chars: Default::default(),
|
||||
spelling: Default::default(),
|
||||
text_nodes: Default::default(),
|
||||
momentary: None,
|
||||
hand: None,
|
||||
selection_box: None,
|
||||
selection_bounds: None,
|
||||
selection_marks: None,
|
||||
@@ -715,7 +717,13 @@ impl VectorcraftApp {
|
||||
export_progress::show(self, ui);
|
||||
// After every window this pass may open, and before the palette's field takes the keyboard.
|
||||
panel_docking::close_overlays_for_modal(self, &ctx);
|
||||
let drawn_document = self.session.active().map(|st| (st.uid, st.revision));
|
||||
dialogs::host::pump(self, &ctx);
|
||||
// The canvas has already painted. A dialog can apply or roll back its preview
|
||||
// on the final input frame, with no further mouse movement to wake the window.
|
||||
if self.session.active().map(|st| (st.uid, st.revision)) != drawn_document {
|
||||
ctx.request_repaint();
|
||||
}
|
||||
prefs_dialog::show(self, ui);
|
||||
crate::shortcut_editor::show(self, ui);
|
||||
credits::open_taken_link(self);
|
||||
@@ -822,6 +830,9 @@ pub(crate) fn root_env(prefs: &vectorcraft_engine::Prefs, native_ppp: f32, print
|
||||
root.escape_leaves_fields = true;
|
||||
// A held key repeats its command (Cmd+= keeps zooming in).
|
||||
root.shortcuts_repeat = true;
|
||||
// The wheel steps a focused number field only while the pointer is over it; elsewhere it scrolls what is under the
|
||||
// pointer.
|
||||
root.pointer_scoped_field_wheel = true;
|
||||
root
|
||||
}
|
||||
|
||||
|
||||
@@ -129,11 +129,12 @@ impl VectorcraftApp {
|
||||
/// document without artboards they get neither.
|
||||
fn add_active_artboard(&self, id: &str, params: &mut Value) {
|
||||
let paste = matches!(id, "edit.pasteInPlace" | "edit.pasteInFront" | "edit.pasteInBack");
|
||||
let clipboard_command = paste || matches!(id, "edit.copy" | "edit.cut");
|
||||
if (vectorcraft_engine::ON_ACTIVE_ARTBOARD.contains(&id) || id == "command.batch")
|
||||
&& params.get("artboard").is_none()
|
||||
&& !(paste && params.get("artboards").is_some())
|
||||
&& self.view().is_some()
|
||||
&& let Some(n) = self.session.active().map(|d| d.doc.artboards.len()).filter(|n| *n > 0 || !paste)
|
||||
&& let Some(n) = self.session.active().map(|d| d.doc.artboards.len()).filter(|n| *n > 0 || !clipboard_command)
|
||||
&& let Some(p) = params.as_object_mut()
|
||||
{
|
||||
let picked = panels::artboards::picked(self, n);
|
||||
|
||||
@@ -64,6 +64,10 @@ pub struct CanvasCache {
|
||||
/// version of the document's content and of the available fonts: the dialog reads them every
|
||||
/// frame.
|
||||
pub find_font: Option<FindFontCache>,
|
||||
/// The missing fonts of each document whose Missing Fonts dialog waits to open, for a version of
|
||||
/// the document's content and of the available fonts: the frame that checks whether a dialog
|
||||
/// waits and the frame's pump that opens it read the same list.
|
||||
pub missing_fonts: Vec<MissingFontsCache>,
|
||||
/// The marks Type → Show Hidden Characters drew on each text object in the last frame. A frame
|
||||
/// that does not draw them drops them ([`canvas::show`]).
|
||||
pub hidden_chars: canvas::marks::HiddenChars,
|
||||
@@ -77,6 +81,7 @@ pub struct CanvasCache {
|
||||
/// The Hand, Zoom and Rotate View tools the Space key and its chords lend the canvas, between
|
||||
/// passes; the tool adapter takes it out for its call and puts it back.
|
||||
pub momentary: Option<craft::ui::canvas::Momentary>,
|
||||
pub hand: Option<craft::ui::canvas::HandTool>,
|
||||
/// [`VectorcraftApp::selection_box`] for (document uid, revision, Use Preview Bounds and
|
||||
/// Measure Type by Glyph Bounds).
|
||||
pub selection_box: Option<((u64, u64, vectorcraft_effects::preview::Measure), Option<vectorcraft_doc::OrientedBox>)>,
|
||||
@@ -253,6 +258,15 @@ pub struct FindFontCache {
|
||||
pub missing: Option<bool>,
|
||||
}
|
||||
|
||||
/// [`CanvasCache::missing_fonts`]: a document's `text.missingFonts` rows
|
||||
/// ([`vectorcraft_engine::cmd::fontfiles::missing_font_rows`]).
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct MissingFontsCache {
|
||||
/// The document and the content and fonts the rows were worked out from.
|
||||
pub key: FontsKey,
|
||||
pub fonts: Vec<serde_json::Value>,
|
||||
}
|
||||
|
||||
/// A document's uid, a version of its content (compared by identity) and the font database's
|
||||
/// generation ([`vectorcraft_text::FontDb::generation`]). The weak reference keeps the version's
|
||||
/// allocation, so a later version is never placed at the same address while the key is kept.
|
||||
|
||||
@@ -278,8 +278,8 @@ pub(crate) fn show_document(app: &mut VectorcraftApp, ui: &mut Ui, win: Win, kin
|
||||
pressed
|
||||
}
|
||||
|
||||
/// The body of the canvas in order: controls that take presses first, the tool host, the selection's marks, the
|
||||
/// picture last.
|
||||
/// The body of the canvas in order: controls that take presses first, the tool host, the selection's marks and the
|
||||
/// display-only widgets over it, the picture last.
|
||||
fn show_body(app: &mut VectorcraftApp, ui: &mut Ui, space: &CanvasSpace, pass: Option<&ToolPass>, win: Win, kind: BodyKind) -> Body {
|
||||
let live = kind == BodyKind::Live;
|
||||
let presenting = app.ui.screen_mode == 3;
|
||||
@@ -299,11 +299,12 @@ fn show_body(app: &mut VectorcraftApp, ui: &mut Ui, space: &CanvasSpace, pass: O
|
||||
crate::dialogs::simplify_slider::show(app, ui, &space.view);
|
||||
}
|
||||
guides::show(app, ui, space, win, kind);
|
||||
widgets::show_hollow_corners(app, ui, space, kind);
|
||||
// The selection's marks paint here, under the widgets and bars, and are drawn after the tool host has taken this
|
||||
// frame's pointer event, from the document as the event leaves it.
|
||||
// The hollow Live Corners, the selection's marks, and the bounding box, Live Corners and shape widgets paint here
|
||||
// in that order, under the 3D handles and the bars. All of them are display only and are drawn after the tool host
|
||||
// has taken this frame's pointer event, from the document as the event leaves it.
|
||||
let hollow = PaintSlot::reserve(ui.painter());
|
||||
let marks = PaintSlot::reserve(ui.painter());
|
||||
widgets::show(app, ui, space, win, kind);
|
||||
let shown_widgets = PaintSlot::reserve(ui.painter());
|
||||
if !presenting && !revolve_editing(app) {
|
||||
crate::panels::three_d::handles::show(app, ui, space);
|
||||
}
|
||||
@@ -339,14 +340,21 @@ fn show_body(app: &mut VectorcraftApp, ui: &mut Ui, space: &CanvasSpace, pass: O
|
||||
crate::type_editing::show(app, ui);
|
||||
}
|
||||
}
|
||||
let after = PaintSlot::reserve(ui.painter());
|
||||
selection::show(app, ui, space, win, kind);
|
||||
marks.extend(ui.ctx(), after.take_after(ui.ctx()));
|
||||
paint_into(ui, hollow, |ui| widgets::show_hollow_corners(app, ui, space, kind));
|
||||
paint_into(ui, marks, |ui| selection::show(app, ui, space, win, kind));
|
||||
paint_into(ui, shown_widgets, |ui| widgets::show(app, ui, space, win, kind));
|
||||
drops::show(app, ui, win, kind);
|
||||
raster::picture(app, ui, space, win, kind);
|
||||
out
|
||||
}
|
||||
|
||||
/// Runs `draw` now and moves the shapes it paints on `ui`'s layer to `slot`, their place in the paint order.
|
||||
fn paint_into(ui: &mut Ui, slot: PaintSlot, draw: impl FnOnce(&mut Ui)) {
|
||||
let after = PaintSlot::reserve(ui.painter());
|
||||
draw(ui);
|
||||
slot.extend(ui.ctx(), after.take_after(ui.ctx()));
|
||||
}
|
||||
|
||||
/// The keys held now, as the engine's tools read them, with `space` set while Space is down.
|
||||
pub(crate) fn held_mods(ctx: &egui::Context) -> vectorcraft_tools::Mods {
|
||||
let (m, space) = ctx.input(|i| (i.modifiers, i.key_down(egui::Key::Space)));
|
||||
|
||||
@@ -31,7 +31,7 @@ pub(super) fn checker_of(setup: &vectorcraft_doc::DocSetup) -> Checker {
|
||||
}
|
||||
|
||||
/// The page frames of document `st` seen through `view`: one per artboard, named "01 - name" with the
|
||||
/// Artboard tool or several boards, filled with its paper or the transparency grid (nothing in Outline).
|
||||
/// Artboard tool or several boards, filled with its paper or the transparency grid (white in Outline).
|
||||
/// Empty while the artboards are hidden.
|
||||
pub(super) fn frames(app: &VectorcraftApp, st: &vectorcraft_engine::DocState, view: &View, outline: bool) -> Vec<PageFrame> {
|
||||
if !shows_artboards(app) {
|
||||
@@ -51,7 +51,7 @@ pub(super) fn frames(app: &VectorcraftApp, st: &vectorcraft_engine::DocState, vi
|
||||
frame = frame.name(format!("{:02} - {}", i + 1, ab.name));
|
||||
}
|
||||
if outline {
|
||||
frame
|
||||
frame.fill(DataColor::new(Color32::WHITE))
|
||||
} else if grid {
|
||||
frame.checker(checker_of(setup))
|
||||
} else {
|
||||
|
||||
@@ -47,13 +47,13 @@ fn shift_clicking_a_name_toggles_selection_and_a_plain_click_activates() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn outline_has_a_white_canvas_line_edges_and_no_paper() {
|
||||
fn outline_has_white_artboards_on_a_white_canvas_with_line_edges() {
|
||||
let _view = crate::testing::DefaultProofView::new();
|
||||
let app = app_with(2);
|
||||
let st = app.session.active().unwrap();
|
||||
assert_eq!(pasteboard_color(&app, st, true), PasteboardColor::Custom(DataColor::new(Color32::WHITE)));
|
||||
assert_eq!(border(true), PageBorder::Line);
|
||||
assert!(frames_of(&app, true).iter().all(|f| f.fill.is_none()));
|
||||
assert!(frames_of(&app, true).iter().all(|f| f.fill == Some(PageFill::Color(DataColor::new(Color32::WHITE)))));
|
||||
assert_eq!(pasteboard_color(&app, st, false), PasteboardColor::Default);
|
||||
assert_eq!(border(false), PageBorder::DropShadow);
|
||||
assert!(frames_of(&app, false).iter().all(|f| f.fill.is_some()));
|
||||
|
||||
@@ -35,7 +35,8 @@ pub(super) fn show(app: &VectorcraftApp, ui: &mut egui::Ui, space: &CanvasSpace,
|
||||
let options = super::selection::path_options(&app.session.prefs);
|
||||
let quiet = tool_adapter::in_gesture(app, ui.ctx()) || tool_adapter::view_tool_held(app);
|
||||
let lists = [extra, overlays];
|
||||
for (i, o) in extra.iter().chain(overlays).enumerate() {
|
||||
// Only the overlays that are controls get a child `Ui`: a list of 10,000 path marks makes none.
|
||||
for (i, o) in extra.iter().chain(overlays).enumerate().filter(|(_, o)| is_control(o)) {
|
||||
ui.push_id(("tool-control", i), |ui| show_control(ui, rect, o));
|
||||
}
|
||||
for (i, list) in lists.into_iter().enumerate() {
|
||||
@@ -48,6 +49,26 @@ pub(super) fn show(app: &VectorcraftApp, ui: &mut egui::Ui, space: &CanvasSpace,
|
||||
});
|
||||
}
|
||||
|
||||
/// Whether `o` is shown as a framework control of its own ([`show_control`]) rather than painted by [`ToolMarks`].
|
||||
fn is_control(o: &Overlay) -> bool {
|
||||
match o {
|
||||
Overlay::Marquee(_) | Overlay::SelectionMarquee { .. } | Overlay::SharedPath { .. } | Overlay::Outlines { .. } | Overlay::Distance { .. } => {
|
||||
true
|
||||
}
|
||||
Overlay::Path { .. }
|
||||
| Overlay::Line { .. }
|
||||
| Overlay::Anchor { .. }
|
||||
| Overlay::CurvePoint { .. }
|
||||
| Overlay::Handle { .. }
|
||||
| Overlay::Label { .. }
|
||||
| Overlay::Measure { .. }
|
||||
| Overlay::Highlight { .. }
|
||||
| Overlay::Swatch { .. }
|
||||
| Overlay::GridLine { .. }
|
||||
| Overlay::HoverText { .. } => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// The framework control `o` stands for, if it is one: a marquee, a settled outline, a set of outlines or a distance.
|
||||
fn show_control(ui: &mut egui::Ui, rect: ScreenRect, o: &Overlay) {
|
||||
match o {
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
use std::collections::HashMap;
|
||||
use std::collections::hash_map::{DefaultHasher, Entry};
|
||||
use std::hash::{Hash, Hasher};
|
||||
use std::sync::{Arc, Weak};
|
||||
|
||||
use craft::behavior::Input;
|
||||
use craft::behavior::Metrics;
|
||||
@@ -18,9 +19,9 @@ use craft::ui::canvas_controls::{HoverOutline, HoverShape, SelectionOutline};
|
||||
use craft::ui::contract::{Access, Bind, Common, Component, Cx, MeasureCx, PaintUi, Props as _, Role, Show as _};
|
||||
use craft::ui::style::{ComponentStyle, DataColor, StyleCx};
|
||||
use egui::{Color32, Rect, Response, Shape, Stroke, StrokeKind, vec2};
|
||||
use vectorcraft_doc::{NodeId, NodeKind};
|
||||
use vectorcraft_doc::{Document, NodeId, NodeKind};
|
||||
use vectorcraft_engine::{DocState, Prefs, ViewInfo};
|
||||
use vectorcraft_geom::{AnchorKind, BezPath, PathData, PathEl, Point};
|
||||
use vectorcraft_geom::{AnchorKind, BezPath, PathData, PathEl, Point, Vec2};
|
||||
use vectorcraft_tools::Mods;
|
||||
|
||||
use super::cursor::ViewKey;
|
||||
@@ -632,9 +633,13 @@ pub(super) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui, space: &CanvasSp
|
||||
HoverOutline::new("Object highlight", Some(HoverShape::Path(h.path))).color(DataColor::new(h.color)).show_at(ui, rect);
|
||||
}
|
||||
let key = marks_key(app, st, tool, tool_points);
|
||||
let view = view_key(app, st, tool, tool_points);
|
||||
let marks = match app.canvas.selection_marks.take() {
|
||||
Some(kept) if kept.key == key => kept,
|
||||
_ => SelectionMarks::build(app, st, tool, tool_points, key),
|
||||
Some(kept) if kept.view == view && kept.selection == st.selection => {
|
||||
kept.follow(st, key).unwrap_or_else(|| SelectionMarks::build(app, st, tool, tool_points, (key, view)))
|
||||
}
|
||||
_ => SelectionMarks::build(app, st, tool, tool_points, (key, view)),
|
||||
};
|
||||
for o in &marks.outlines {
|
||||
let mut outline = SelectionOutline::solid("Selection", &o.paths).color(DataColor::new(o.color)).revision(o.revision);
|
||||
@@ -663,29 +668,99 @@ pub(super) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui, space: &CanvasSp
|
||||
}
|
||||
|
||||
/// The outlines, anchors and dots `show` draws, kept between passes while their [`marks_key`] stays: a frame with
|
||||
/// nothing changed walks no selected object.
|
||||
/// nothing changed walks no selected object. They are also kept while the document and the selection stay the same
|
||||
/// under another revision, and moved with the selection when a move ([`vectorcraft_engine::Moved`]) took the document
|
||||
/// they show to the one now.
|
||||
pub(crate) struct SelectionMarks {
|
||||
key: u64,
|
||||
/// [`view_key`] of the state they were made for.
|
||||
view: u64,
|
||||
/// The selection they show.
|
||||
selection: vectorcraft_doc::Selection,
|
||||
/// The document they show.
|
||||
doc: Weak<Document>,
|
||||
/// A document they show moved by a distance: the one they were built for and no distance, or the document the
|
||||
/// last move they followed started from and its distance. Each step of a drag starts from the document the drag
|
||||
/// began with ([`SelectionMarks::follow`]).
|
||||
from: (Weak<Document>, Vec2),
|
||||
outlines: Vec<Outlined>,
|
||||
anchors: Anchors,
|
||||
dots: Dots,
|
||||
}
|
||||
|
||||
impl SelectionMarks {
|
||||
fn build(app: &VectorcraftApp, st: &DocState, tool: &str, tool_points: bool, key: u64) -> Self {
|
||||
fn build(app: &VectorcraftApp, st: &DocState, tool: &str, tool_points: bool, (key, view): (u64, u64)) -> Self {
|
||||
#[cfg(test)]
|
||||
tests::MARKS_BUILT.with(|built| built.set(built.get() + 1));
|
||||
Self { key, outlines: outlines(app, st), anchors: anchors(app, st, tool, tool_points), dots: dots(app, st) }
|
||||
let doc = Arc::downgrade(&st.doc);
|
||||
Self {
|
||||
key,
|
||||
view,
|
||||
selection: st.selection.clone(),
|
||||
from: (doc.clone(), Vec2::ZERO),
|
||||
doc,
|
||||
outlines: outlines(app, st),
|
||||
anchors: anchors(app, st, tool, tool_points),
|
||||
dots: dots(app, st),
|
||||
}
|
||||
}
|
||||
|
||||
/// The marks of `st`, whose [`marks_key`] is `key`, from these marks of the same selection and view: these marks
|
||||
/// when `st` shows the same document, these marks moved by `st`'s move when it took the document they show, or the
|
||||
/// document of [`SelectionMarks::from`], to the one `st` shows, else `None`.
|
||||
fn follow(mut self, st: &DocState, key: u64) -> Option<Self> {
|
||||
let now = Arc::as_ptr(&st.doc);
|
||||
if self.doc.as_ptr() != now {
|
||||
let moved = st.moved.as_ref().filter(|m| m.to.as_ptr() == now && m.selection == st.selection)?;
|
||||
let by = if moved.from.ptr_eq(&self.doc) {
|
||||
moved.by
|
||||
} else if moved.from.ptr_eq(&self.from.0) {
|
||||
moved.by - self.from.1
|
||||
} else {
|
||||
return None;
|
||||
};
|
||||
self.translate(by);
|
||||
self.from = (moved.from.clone(), moved.by);
|
||||
self.doc = moved.to.clone();
|
||||
}
|
||||
self.key = key;
|
||||
Some(self)
|
||||
}
|
||||
|
||||
/// Moves every mark by `by`.
|
||||
fn translate(&mut self, by: Vec2) {
|
||||
let shift = vectorcraft_geom::Affine::translate(by);
|
||||
for o in &mut self.outlines {
|
||||
o.paths.iter_mut().chain(o.key.as_mut()).for_each(|path| path.apply_affine(shift));
|
||||
o.revision = outline_revision(&o.paths, o.key.as_ref(), o.color.to_array());
|
||||
}
|
||||
for knot in self.anchors.paths.iter_mut().flat_map(|p| &mut p.subpaths).flat_map(|sp| &mut sp.knots) {
|
||||
knot.anchor += by;
|
||||
knot.in_ctrl += by;
|
||||
knot.out_ctrl += by;
|
||||
}
|
||||
let dots = &mut self.dots;
|
||||
for (at, _) in dots.origins.iter_mut().chain(&mut dots.centers).chain(&mut dots.key_anchor) {
|
||||
*at += by;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What the selection's marks are built from: the document and its selection (its uid and revision), the parts the
|
||||
/// view hides, Halftone Preview, the tool whose marks show, whether that tool draws its own points, and the
|
||||
/// Selection & Anchor Display preferences.
|
||||
/// What the selection's marks are built from: the document and its selection (its uid and revision), and what
|
||||
/// [`view_key`] hashes.
|
||||
fn marks_key(app: &VectorcraftApp, st: &DocState, tool: &str, tool_points: bool) -> u64 {
|
||||
let mut h = DefaultHasher::new();
|
||||
(st.revision, view_key(app, st, tool, tool_points)).hash(&mut h);
|
||||
h.finish()
|
||||
}
|
||||
|
||||
/// What the selection's marks are built from besides the document's content and the selection: the document (its
|
||||
/// uid), the parts the view hides, Halftone Preview, the tool whose marks show, whether that tool draws its own points,
|
||||
/// and the Selection & Anchor Display preferences.
|
||||
fn view_key(app: &VectorcraftApp, st: &DocState, tool: &str, tool_points: bool) -> u64 {
|
||||
let mut h = DefaultHasher::new();
|
||||
let hides = ViewHides::of(app);
|
||||
(st.uid, st.revision, hides.templates, hides.guides, hidden(app), tool, tool_points).hash(&mut h);
|
||||
(st.uid, hides.templates, hides.guides, hidden(app), tool, tool_points).hash(&mut h);
|
||||
let prefs = &app.session.prefs;
|
||||
(prefs.anchor_size, prefs.show_handles_multiple_anchors, prefs.handle_style.as_str()).hash(&mut h);
|
||||
h.finish()
|
||||
|
||||
@@ -918,3 +918,75 @@ fn the_canvas_builds_the_selection_marks_once_per_change() {
|
||||
app.select_tool("directSelection");
|
||||
assert_eq!(frames(&mut app, 5), 1, "another tool builds the marks once");
|
||||
}
|
||||
|
||||
/// Every point of the outlines, the anchors and their handles, and the dots, in order.
|
||||
fn points_of(outlines: &[Outlined], anchors: &Anchors, dots: &Dots) -> Vec<Point> {
|
||||
let mut out = vec![];
|
||||
for path in outlines.iter().flat_map(|o| o.paths.iter().chain(&o.key)) {
|
||||
for el in path.elements() {
|
||||
match *el {
|
||||
PathEl::MoveTo(a) | PathEl::LineTo(a) => out.push(a),
|
||||
PathEl::QuadTo(a, b) => out.extend([a, b]),
|
||||
PathEl::CurveTo(a, b, c) => out.extend([a, b, c]),
|
||||
PathEl::ClosePath => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
for knot in anchors.paths.iter().flat_map(|p| &p.subpaths).flat_map(|sp| &sp.knots) {
|
||||
out.extend([knot.anchor, knot.in_ctrl, knot.out_ctrl]);
|
||||
}
|
||||
out.extend(dots.origins.iter().chain(&dots.centers).chain(&dots.key_anchor).map(|(at, _)| *at));
|
||||
out
|
||||
}
|
||||
|
||||
/// Whether the marks the canvas keeps are, to rounding, the ones the builders give for the state now.
|
||||
fn kept_marks_are_current(app: &VectorcraftApp) -> bool {
|
||||
let kept = app.canvas.selection_marks.as_ref().expect("the canvas drew the selection's marks");
|
||||
let st = app.session.active().unwrap();
|
||||
let now = points_of(&outlines(app, st), &anchors(app, st, app.session.tool_id(), false), &dots(app, st));
|
||||
let was = points_of(&kept.outlines, &kept.anchors, &kept.dots);
|
||||
now.len() == was.len() && now.iter().zip(&was).all(|(a, b)| (*a - *b).hypot() < 1e-9)
|
||||
}
|
||||
|
||||
// Whole-app frames keep the selection's marks through a new revision of the same document and selection, and move
|
||||
// them with a move of the selection instead of building them: a move command, each step of a drag, and the drag's end
|
||||
// build nothing and keep the marks of the state now. A scale and an undo still build them once.
|
||||
#[test]
|
||||
fn a_move_of_the_selection_moves_its_marks_without_building_them() {
|
||||
let (mut app, _) = scene();
|
||||
let ctx = crate::testing::ui_context();
|
||||
let frames = |app: &mut VectorcraftApp, n: usize| {
|
||||
let before = MARKS_BUILT.with(std::cell::Cell::get);
|
||||
for _ in 0..n {
|
||||
let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1600.0, 850.0));
|
||||
crate::testing::app_frame(app, &ctx, egui::RawInput { screen_rect: Some(screen), ..Default::default() });
|
||||
}
|
||||
MARKS_BUILT.with(std::cell::Cell::get) - before
|
||||
};
|
||||
frames(&mut app, 3);
|
||||
let layer = app.session.active().unwrap().doc.layers[0].id;
|
||||
let revision = app.session.active().unwrap().revision;
|
||||
app.run("layer.setCurrent", json!({"id": layer.0})).unwrap();
|
||||
assert_ne!(app.session.active().unwrap().revision, revision, "a new revision");
|
||||
assert_eq!(frames(&mut app, 3), 0, "a new revision of the same document and selection");
|
||||
app.run("object.move", json!({"dx": 12.25, "dy": -5})).unwrap();
|
||||
assert_eq!(frames(&mut app, 3), 0, "a move command");
|
||||
assert!(kept_marks_are_current(&app), "after a move command");
|
||||
|
||||
app.session.begin_interaction("Move").unwrap();
|
||||
for dx in [3.0, 7.5, -2.0] {
|
||||
app.session.preview("object.transform", &json!({"matrix": [1, 0, 0, 1, dx, 4], "copy": false})).unwrap();
|
||||
assert_eq!(frames(&mut app, 2), 0, "a drag's step by {dx}");
|
||||
assert!(kept_marks_are_current(&app), "after a drag's step by {dx}");
|
||||
}
|
||||
app.session.commit_interaction().unwrap();
|
||||
assert_eq!(frames(&mut app, 2), 0, "the drag's end");
|
||||
assert!(kept_marks_are_current(&app), "after the drag");
|
||||
|
||||
app.run("object.transform", json!({"matrix": [2, 0, 0, 1, 0, 0]})).unwrap();
|
||||
assert_eq!(frames(&mut app, 3), 1, "a scale");
|
||||
assert!(kept_marks_are_current(&app), "after a scale");
|
||||
app.run("edit.undo", json!({})).unwrap();
|
||||
assert_eq!(frames(&mut app, 3), 1, "an undo");
|
||||
assert!(kept_marks_are_current(&app), "after an undo");
|
||||
}
|
||||
|
||||
@@ -303,7 +303,22 @@ fn press(at: Pos2, pressed: bool) -> egui::Event {
|
||||
/// object has after that frame's event, and none at the corner it had before it.
|
||||
#[test]
|
||||
fn a_selection_drag_draws_its_marks_in_the_frame_the_pointer_moves() {
|
||||
selection_drag_marks_follow(drag_app());
|
||||
}
|
||||
|
||||
/// With Show Bounding Box While Moving and Drawing on, a Selection tool drag draws the bounding box and its handles in
|
||||
/// the frame the pointer moves: at the corner the object has after that frame's event, and none at the corner it had
|
||||
/// before it.
|
||||
#[test]
|
||||
fn a_selection_drag_draws_its_bounding_box_in_the_frame_the_pointer_moves() {
|
||||
let mut app = drag_app();
|
||||
app.session.prefs.bounding_box_while_moving_and_drawing = true;
|
||||
selection_drag_marks_follow(app);
|
||||
}
|
||||
|
||||
/// Drags a selected rectangle with the Selection tool in six frames and checks each frame that moved it: a mark at
|
||||
/// its corner after the frame's event, none at its corner before.
|
||||
fn selection_drag_marks_follow(mut app: VectorcraftApp) {
|
||||
let id = app.session.execute("shape.rectangle", &json!({"x": 150, "y": 100, "width": 60, "height": 40})).unwrap()["id"].as_u64().unwrap();
|
||||
app.select_tool("selection");
|
||||
app.session.execute("select.set", &json!({"ids": [id]})).unwrap();
|
||||
@@ -411,6 +426,23 @@ fn a_click_activates_its_artboard_and_paste_in_place_goes_onto_it() {
|
||||
assert_eq!((b.x0, b.y0), (boards[2].x0 + 10.0, boards[2].y0 + 15.0));
|
||||
}
|
||||
|
||||
/// Copy uses the active board as its origin even when selected art lies on a different board.
|
||||
#[test]
|
||||
fn copy_and_paste_use_the_active_source_and_destination_artboards() {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 200, "height": 100, "artboards": 3})).unwrap();
|
||||
let boards: Vec<_> = app.session.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect();
|
||||
let origin = Point::new(boards[1].x0 + 10.0, boards[1].y0 + 15.0);
|
||||
app.run("shape.rectangle", json!({"x": origin.x, "y": origin.y, "width": 20, "height": 20})).unwrap();
|
||||
app.views[0].artboard = 0;
|
||||
app.run("edit.copy", json!({})).unwrap();
|
||||
app.views[0].artboard = 2;
|
||||
let pasted = app.run("edit.pasteInPlace", json!({})).unwrap();
|
||||
let id = vectorcraft_doc::NodeId(pasted["ids"][0].as_u64().unwrap());
|
||||
let bounds = app.session.active().unwrap().doc.bounds_of(&[id], false).unwrap();
|
||||
assert_eq!(bounds.origin(), origin + (boards[2].origin() - boards[0].origin()));
|
||||
}
|
||||
|
||||
/// A Shift-click with the Selection tool on an empty spot inside an artboard makes it the active
|
||||
/// one and keeps the selection, and Align to Artboard then aligns the objects to it unless the
|
||||
/// call names another artboard.
|
||||
@@ -865,6 +897,58 @@ fn the_move_of_a_releasing_frame_counts_for_the_tool_drag() {
|
||||
assert_eq!(draw(true), Rect::new(130.0, 115.0, 160.0, 130.0), "with Space held through the release the last move moves it");
|
||||
}
|
||||
|
||||
/// A Selection tool move builds the menus' states again twice, in the frame of its press and in the frame of its
|
||||
/// release, which commits the move. The frame the move begins in and the frames of its previews, which change the
|
||||
/// document's revision, keep them. The menus are also built again when a process-wide catalog changes, so the fonts
|
||||
/// and plug-ins are held steady against tests running alongside for the whole run, and the move runs again on a new
|
||||
/// app, at most 20 times, until the other catalogs held still through it.
|
||||
#[test]
|
||||
fn a_selection_move_rebuilds_the_menus_for_its_press_and_release_only() {
|
||||
let fonts = vectorcraft_text::FontDb::global();
|
||||
let _steady = (vectorcraft_text::test_fonts::steady_fonts(fonts), vectorcraft_plugins::steady::steady_plugins());
|
||||
let catalogs = || {
|
||||
(
|
||||
crate::menus::plugin_revision(),
|
||||
fonts.generation(),
|
||||
fonts.installed_fonts_ready(),
|
||||
crate::scripts_menu::revision(),
|
||||
crate::dialogs::proof_setup::saved_revision(),
|
||||
)
|
||||
};
|
||||
let run = || {
|
||||
let (mut app, ctx, xf) = rectangle_tool();
|
||||
let id = app.session.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 60, "height": 30})).unwrap()["id"].as_u64().unwrap();
|
||||
app.select_tool("selection");
|
||||
app.session.execute("select.set", &json!({"ids": [id]})).unwrap();
|
||||
let (from, to) = (xf.to_screen(Point::new(130.0, 115.0)), xf.to_screen(Point::new(170.0, 135.0)));
|
||||
app_step(&mut app, &ctx, vec![egui::Event::PointerMoved(from)]);
|
||||
for _ in 0..2 {
|
||||
app_step(&mut app, &ctx, vec![]);
|
||||
}
|
||||
let none = egui::Modifiers::NONE;
|
||||
let mut steps = vec![vec![primary(from, true, none)]];
|
||||
steps.extend((1..=8).map(|i| vec![egui::Event::PointerMoved(from.lerp(to, i as f32 / 8.0))]));
|
||||
steps.push(vec![primary(to, false, none)]);
|
||||
steps.extend([vec![], vec![], vec![]]);
|
||||
let mut rebuilt = vec![];
|
||||
for events in steps {
|
||||
let before = app.menus.rebuilds;
|
||||
app_step(&mut app, &ctx, events);
|
||||
rebuilt.push(app.menus.rebuilds - before);
|
||||
}
|
||||
(app, rebuilt)
|
||||
};
|
||||
let (app, rebuilt) = (0..20)
|
||||
.find_map(|_| {
|
||||
let before = catalogs();
|
||||
let out = run();
|
||||
(catalogs() == before).then_some(out)
|
||||
})
|
||||
.unwrap_or_else(|| panic!("tests running alongside kept changing the font and plug-in catalogs"));
|
||||
assert_eq!(drawn_paths(&app), vec![Rect::new(140.0, 120.0, 200.0, 150.0)], "the drag moves the rectangle");
|
||||
assert_eq!(rebuilt, [1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0], "rebuilds in each frame: press, 8 moves, release, 3 idle");
|
||||
}
|
||||
|
||||
/// #6369: only the selection box remains over the temporary halftone, and the original
|
||||
/// selection's outlines come back when Preview is turned off or the dialog is cancelled.
|
||||
#[test]
|
||||
@@ -4859,6 +4943,25 @@ fn a_flip_during_a_press_waits_for_the_release() {
|
||||
assert_eq!(app.session.tool_id(), "eraser", "the frame after the release");
|
||||
}
|
||||
|
||||
/// A selected Hand tracks its drag in the framework, outside the document tool's grab.
|
||||
#[test]
|
||||
fn turning_the_pen_during_a_hand_drag_waits_for_release() {
|
||||
let (mut app, stylus, ctx) = pen_app();
|
||||
app.select_tool("hand");
|
||||
let at = app.canvas_view().unwrap().rect.center();
|
||||
let to = at + egui::vec2(30.0, 20.0);
|
||||
let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
|
||||
stylus.set(tip(0.5));
|
||||
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at), button(at, true)]);
|
||||
stylus.set(eraser_end(0.5));
|
||||
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(to)]);
|
||||
assert_eq!(app.session.tool_id(), "hand");
|
||||
frame(&mut app, &ctx, vec![button(to, false)]);
|
||||
assert_eq!(app.session.tool_id(), "hand");
|
||||
frame(&mut app, &ctx, vec![]);
|
||||
assert_eq!(app.session.tool_id(), "eraser");
|
||||
}
|
||||
|
||||
/// #764: a tool chosen while the eraser end stands in (the toolbar and shortcuts call
|
||||
/// `select_tool`; menus and MCP run `tool.select`) stays when the tip comes back.
|
||||
#[test]
|
||||
|
||||
@@ -127,10 +127,12 @@ fn a_hand_drag_held_near_the_edge_does_not_scroll_on() {
|
||||
let (mut app, ctx, _) = zoomed_in("hand");
|
||||
let rect = app.canvas_view().unwrap().rect;
|
||||
let start = rect.center();
|
||||
let before = center(&app);
|
||||
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(start), button(start, true)]);
|
||||
let edge = pos2(rect.right() - 4.0, start.y);
|
||||
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(edge)]);
|
||||
let c0 = center(&app);
|
||||
assert!(c0.x < before.x, "dragging the selected Hand right must pan the view");
|
||||
for _ in 0..3 {
|
||||
frame(&mut app, &ctx, vec![]);
|
||||
}
|
||||
|
||||
@@ -629,6 +629,7 @@ pub(crate) fn run(app: &mut VectorcraftApp, ui: &mut Ui, pass: &ToolPass) -> Too
|
||||
// the release, and a pointer over another window for the pointer to come in.
|
||||
if ui.ctx().current_pass_index() == 0
|
||||
&& app.canvas.grab.is_none()
|
||||
&& !ToolHost::in_gesture(ui.ctx(), pass.id)
|
||||
&& ui.input(|i| i.pointer.has_pointer())
|
||||
&& crate::stylus::sync_eraser_tool(app)
|
||||
{
|
||||
@@ -650,7 +651,18 @@ pub(crate) fn run(app: &mut VectorcraftApp, ui: &mut Ui, pass: &ToolPass) -> Too
|
||||
let mut picked = ToolHostResponse::default();
|
||||
let mut response = if crate::dialogs::recolor::edit_tab::with_theme_pick(app, |app, tool| picked = host_run(app, ui, pass, tool)) {
|
||||
picked
|
||||
} else if app.session.tool_id() == "hand" && app.ui.screen_mode != 3 && app.ui.rearrange_placement.is_none() {
|
||||
let options = crate::app::view::navigation(&app.session.prefs);
|
||||
let mut hand = app.canvas.hand.take().unwrap_or_else(|| craft::ui::canvas::HandTool::new(options));
|
||||
hand.options = options;
|
||||
let response = host_run(app, ui, pass, &mut hand);
|
||||
if response.gesture.is_some() && !view_tool_held(app) && ui.input(|i| i.pointer.primary_down() || i.pointer.primary_pressed()) {
|
||||
crate::shortcuts::note_tool_use(app);
|
||||
}
|
||||
app.canvas.hand = Some(hand);
|
||||
response
|
||||
} else {
|
||||
app.canvas.hand = None;
|
||||
let mut tool = SessionTool::new(app, view_info, ui);
|
||||
let response = host_run_session(&mut tool, ui, pass);
|
||||
drop(tool);
|
||||
|
||||
@@ -89,6 +89,7 @@ pub fn tool_cursor(c: Cursor) -> cb::Cursor {
|
||||
Cursor::DirectAnchorSelected => tool("cursor-direct-anchor-selected", TIP, None),
|
||||
Cursor::ReshapeSegment => tool("cursor-reshape-segment", TIP, None),
|
||||
Cursor::GroupSelection => badged(CursorBadge::Add),
|
||||
Cursor::SelectionMove => badged(CursorBadge::Move),
|
||||
Cursor::SelectionCopy => badged(CursorBadge::Copy),
|
||||
Cursor::Move => system(CursorIcon::Move),
|
||||
Cursor::Crosshair => PaintedCursor::Crosshair.into(),
|
||||
@@ -195,7 +196,7 @@ pub(crate) fn request_busy(app: &crate::VectorcraftApp, ctx: &egui::Context) {
|
||||
|
||||
/// Every cursor with a look: its own, or the one it borrows.
|
||||
#[cfg(test)]
|
||||
const GLYPHS: [Cursor; 99] = [
|
||||
const GLYPHS: [Cursor; 100] = [
|
||||
Cursor::Hand,
|
||||
Cursor::HandGrab,
|
||||
Cursor::ZoomIn,
|
||||
@@ -207,6 +208,7 @@ const GLYPHS: [Cursor; 99] = [
|
||||
Cursor::ReshapeSegment,
|
||||
Cursor::GroupSelection,
|
||||
Cursor::SelectionCopy,
|
||||
Cursor::SelectionMove,
|
||||
Cursor::Move,
|
||||
Cursor::Crosshair,
|
||||
Cursor::ResizeH,
|
||||
|
||||
@@ -114,11 +114,19 @@ pub(super) fn render_preview(
|
||||
app: &mut VectorcraftApp,
|
||||
ctx: &egui::Context,
|
||||
doc: &vectorcraft_engine::doc::Document,
|
||||
) -> Option<Arc<egui::ColorImage>> {
|
||||
render_page_preview(&mut app.canvas.renderer, ctx.pixels_per_point(), doc)
|
||||
}
|
||||
|
||||
fn render_page_preview(
|
||||
renderer: &mut vectorcraft_render::Renderer,
|
||||
pixels_per_point: f32,
|
||||
doc: &vectorcraft_engine::doc::Document,
|
||||
) -> Option<Arc<egui::ColorImage>> {
|
||||
let region = doc.artboards.first()?.rect;
|
||||
let px = PREVIEW_PX * ctx.pixels_per_point() as f64;
|
||||
let px = PREVIEW_PX * pixels_per_point as f64;
|
||||
let scale = px / region.width().max(region.height()).max(1.0);
|
||||
let img = app.canvas.renderer.render_region(doc, region, scale, true);
|
||||
let img = renderer.render_region(doc, region, scale, true);
|
||||
Some(Arc::new(crate::canvas::color_image(&img)))
|
||||
}
|
||||
|
||||
@@ -286,6 +294,8 @@ pub(super) struct ImportPdfDialog {
|
||||
/// The preview shown for a (page, crop, text) revision; `None` for a page that could not be read, which is
|
||||
/// not asked for again.
|
||||
preview: Option<(Revision, Option<Arc<egui::ColorImage>>)>,
|
||||
/// One preview at a time. Page changes coalesce while the worker finishes.
|
||||
pending_preview: Option<(Revision, std::sync::mpsc::Receiver<Option<Arc<egui::ColorImage>>>)>,
|
||||
/// Why the last password did not open the file.
|
||||
password_error: Option<String>,
|
||||
/// The OK the pump has not answered.
|
||||
@@ -294,7 +304,7 @@ pub(super) struct ImportPdfDialog {
|
||||
|
||||
impl ImportPdfDialog {
|
||||
fn new(s: State) -> Self {
|
||||
ImportPdfDialog { id: dialog_id(KIND), s, preview: None, password_error: None, held: HeldAnswer::new() }
|
||||
ImportPdfDialog { id: dialog_id(KIND), s, preview: None, pending_preview: None, password_error: None, held: HeldAnswer::new() }
|
||||
}
|
||||
|
||||
/// The preview to render next: the revision of the shown page, crop and text, when the stored one differs.
|
||||
@@ -700,7 +710,14 @@ fn confirm(app: &mut VectorcraftApp, s: &State) -> Result<(), String> {
|
||||
if s.links_on() {
|
||||
p["linkPages"] = json!(true);
|
||||
}
|
||||
io::open_document(app, &s.name, &s.file.bytes, s.path.clone(), &p).map(|_| ())
|
||||
if crate::opening::available()
|
||||
&& let Some(path) = s.path.as_deref()
|
||||
{
|
||||
crate::opening::start_with(app, path, s.file.bytes.clone(), p);
|
||||
Ok(())
|
||||
} else {
|
||||
io::open_document(app, &s.name, &s.file.bytes, s.path.clone(), &p).map(|_| ())
|
||||
}
|
||||
};
|
||||
// Asked only for the password, the dialog showed no Text choice to keep; the choice for a `.ai`
|
||||
// or `.ait` file is not kept for PDFs.
|
||||
@@ -711,10 +728,10 @@ fn confirm(app: &mut VectorcraftApp, s: &State) -> Result<(), String> {
|
||||
}
|
||||
|
||||
/// The preview of the page and boxes `s` shows; `None` for a page that can't be read.
|
||||
fn preview_image(app: &mut VectorcraftApp, ctx: &egui::Context, s: &State) -> Option<Arc<egui::ColorImage>> {
|
||||
fn preview_image(renderer: &mut vectorcraft_render::Renderer, pixels_per_point: f32, s: &State) -> Option<Arc<egui::ColorImage>> {
|
||||
let opts = fileio::LoadOptions { crop: s.crop, password: s.password(), text_as: s.preview_text_as(), ..Default::default() };
|
||||
let (doc, _) = fileio::page_document(&s.file.bytes, s.page().saturating_sub(1), &opts).ok()?;
|
||||
render_preview(app, ctx, &doc)
|
||||
render_page_preview(renderer, pixels_per_point, &doc)
|
||||
}
|
||||
|
||||
/// The host pump: judges the OK the dialog holds (opening or placing the file; a refusal keeps the dialog open with
|
||||
@@ -730,10 +747,44 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) {
|
||||
dialog.answer_ok(answer);
|
||||
}
|
||||
});
|
||||
return;
|
||||
}
|
||||
let wanted = dialogs.with(|host| host.get::<ImportPdfDialog>().and_then(|d| Some((d.wanted_preview()?, d.s.clone()))));
|
||||
if let Some((revision, s)) = wanted {
|
||||
let image = preview_image(app, ctx, &s);
|
||||
let wanted = dialogs.with(|host| {
|
||||
let dialog = host.get_mut::<ImportPdfDialog>()?;
|
||||
if let Some((revision, pending)) = &dialog.pending_preview {
|
||||
let image = match pending.try_recv() {
|
||||
Ok(image) => image,
|
||||
Err(std::sync::mpsc::TryRecvError::Disconnected) => None,
|
||||
Err(std::sync::mpsc::TryRecvError::Empty) => return None,
|
||||
};
|
||||
if dialog.wanted_preview() == Some(*revision) {
|
||||
dialog.set_preview(*revision, image);
|
||||
}
|
||||
dialog.pending_preview = None;
|
||||
}
|
||||
Some((dialog.wanted_preview()?, dialog.s.clone()))
|
||||
});
|
||||
let Some((revision, state)) = wanted else { return };
|
||||
let pixels_per_point = ctx.pixels_per_point();
|
||||
if crate::opening::available() {
|
||||
let (sender, pending) = std::sync::mpsc::channel();
|
||||
dialogs.with(|host| {
|
||||
if let Some(dialog) = host.get_mut::<ImportPdfDialog>() {
|
||||
dialog.pending_preview = Some((revision, pending));
|
||||
}
|
||||
});
|
||||
let wake = ctx.clone();
|
||||
let scope = vectorcraft_engine::file_access::ScopeHandle::capture();
|
||||
app.jobs().spawn(
|
||||
"vectorcraft-pdf-preview",
|
||||
Box::new(move || {
|
||||
let image = scope.run(|| preview_image(&mut vectorcraft_render::Renderer::new(), pixels_per_point, &state));
|
||||
let _ = sender.send(image);
|
||||
wake.request_repaint();
|
||||
}),
|
||||
);
|
||||
} else {
|
||||
let image = preview_image(&mut app.canvas.renderer, pixels_per_point, &state);
|
||||
dialogs.with(|host| {
|
||||
if let Some(dialog) = host.get_mut::<ImportPdfDialog>() {
|
||||
dialog.set_preview(revision, image);
|
||||
|
||||
@@ -35,6 +35,7 @@ use egui::{Context, Ui};
|
||||
use serde_json::{Map, Value, json};
|
||||
|
||||
use crate::VectorcraftApp;
|
||||
use crate::caches::{FontsKey, MissingFontsCache};
|
||||
use crate::file_asks::{self, Owner};
|
||||
|
||||
/// The dialog's key and kind: the fonts a document opened without.
|
||||
@@ -327,19 +328,45 @@ fn after_open_for(app: &mut VectorcraftApp, r: &Value, web: bool) {
|
||||
}
|
||||
|
||||
/// Whether an opened document's Missing Fonts dialog waits for the frame's pump to open it.
|
||||
pub(crate) fn waiting(app: &VectorcraftApp) -> bool {
|
||||
app.ui.pending_fonts.iter().any(|&uid| dialog_for(app, uid).is_some())
|
||||
pub(crate) fn waiting(app: &mut VectorcraftApp) -> bool {
|
||||
let queued = app.ui.pending_fonts.clone();
|
||||
queued.into_iter().any(|uid| missing_rows(app, uid).is_some_and(|fonts| !fonts.is_empty()))
|
||||
}
|
||||
|
||||
/// The Missing Fonts dialog of the open document `uid`, when fonts it uses aren't available.
|
||||
fn dialog_for(app: &VectorcraftApp, uid: u64) -> Option<MissingFontsDialog> {
|
||||
fn dialog_for(app: &mut VectorcraftApp, uid: u64) -> Option<MissingFontsDialog> {
|
||||
let fonts = missing_rows(app, uid).filter(|f| !f.is_empty())?;
|
||||
let st = app.session.documents().iter().find(|d| d.uid == uid)?;
|
||||
let r = vectorcraft_engine::cmd::fontfiles::missing_fonts_of(st, app.session.search_rules.as_ref());
|
||||
let fonts = r["fonts"].as_array().filter(|f| !f.is_empty())?.clone();
|
||||
let next = r["fontsNextToDocument"].as_str().unwrap_or_default().to_string();
|
||||
let next = vectorcraft_engine::cmd::fontfiles::fonts_next_to_document(st, app.session.search_rules.as_ref()).unwrap_or_default();
|
||||
Some(MissingFontsDialog::new(State::new(uid, fonts, next, file_asks::can(app, PickKind::Folder))))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// How many times [`missing_rows`] worked out a document's missing fonts.
|
||||
static ROW_SCANS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// The `text.missingFonts` rows of the open document `uid` (`None` when it is closed), kept in
|
||||
/// [`crate::CanvasCache::missing_fonts`] and worked out again only for another version of its
|
||||
/// content or another font generation.
|
||||
fn missing_rows(app: &mut VectorcraftApp, uid: u64) -> Option<Vec<Value>> {
|
||||
let st = app.session.documents().iter().find(|d| d.uid == uid)?;
|
||||
// The generation is read first: fonts loaded while the rows are worked out leave the entry
|
||||
// under the older generation, so the next look works them out again.
|
||||
let key = FontsKey { uid, doc: std::sync::Arc::downgrade(&st.doc), generation: vectorcraft_text::FontDb::global().generation() };
|
||||
if let Some(c) = app.canvas.missing_fonts.iter().find(|c| c.key == key) {
|
||||
return Some(c.fonts.clone());
|
||||
}
|
||||
#[cfg(test)]
|
||||
ROW_SCANS.set(ROW_SCANS.get() + 1);
|
||||
let fonts = vectorcraft_engine::cmd::fontfiles::missing_font_rows(&st.doc);
|
||||
let cache = &mut app.canvas.missing_fonts;
|
||||
cache.retain(|c| c.key.uid != uid);
|
||||
cache.push(MissingFontsCache { key, fonts: fonts.clone() });
|
||||
Some(fonts)
|
||||
}
|
||||
|
||||
/// Once per frame: run what the finished dialog left to do, follow a running search, stop the search
|
||||
/// of a dialog that is gone, and with no dialog open open the dialog of the first queued document
|
||||
/// that is still open and still misses fonts.
|
||||
@@ -360,6 +387,9 @@ pub(crate) fn open_next(app: &mut VectorcraftApp) {
|
||||
}
|
||||
break;
|
||||
}
|
||||
// Only the documents that still wait keep their rows.
|
||||
let queued = &app.ui.pending_fonts;
|
||||
app.canvas.missing_fonts.retain(|c| queued.contains(&c.key.uid));
|
||||
}
|
||||
|
||||
/// Run what `answer` asks, and open the dialog again when it stays open (a search starts, a search
|
||||
|
||||
@@ -445,6 +445,40 @@ fn reopening_an_open_document_does_not_ask_about_its_fonts_again() {
|
||||
assert!(!is_open::<MissingFontsDialog>(&app));
|
||||
}
|
||||
|
||||
/// The frame after an open checks whether a Missing Fonts dialog waits (before a file that finished
|
||||
/// opening may come to the front) and then opens it: the document's missing fonts are worked out
|
||||
/// once for both.
|
||||
#[test]
|
||||
fn the_frame_after_an_open_works_out_the_missing_fonts_once() {
|
||||
let root = folder("once");
|
||||
let mut app = app_for(&root);
|
||||
let doc = root.join("doc.vectorcraft");
|
||||
save_doc(&mut app, &doc, "No Such Font Family", false);
|
||||
open(&mut app, &doc);
|
||||
ROW_SCANS.set(0);
|
||||
assert!(!crate::opening::may_switch(&mut app), "the dialog waits for the pump");
|
||||
pump(&mut app);
|
||||
assert_eq!(family(&app).as_deref(), Some("No Such Font Family"));
|
||||
assert_eq!(ROW_SCANS.get(), 1, "one look at the document's fonts");
|
||||
assert!(app.canvas.missing_fonts.is_empty(), "the rows go once the dialog opens");
|
||||
}
|
||||
|
||||
/// A document changed while its dialog waits lists the fonts of its new content.
|
||||
#[test]
|
||||
fn a_document_changed_while_its_dialog_waits_lists_its_new_fonts() {
|
||||
let root = folder("changed");
|
||||
let mut app = app_for(&root);
|
||||
let doc = root.join("doc.vectorcraft");
|
||||
save_doc(&mut app, &doc, "Alpha Missing Family", false);
|
||||
open(&mut app, &doc);
|
||||
assert!(!crate::opening::may_switch(&mut app));
|
||||
app.run("text.create", json!({"x": 10, "y": 80, "text": "More", "font": "Beta Missing Family"})).unwrap();
|
||||
pump(&mut app);
|
||||
let fonts = fields(&app).expect("the dialog is open")["fonts"].clone();
|
||||
let families: Vec<_> = fonts.as_array().unwrap().iter().map(|f| f["family"].as_str().unwrap_or_default()).collect();
|
||||
assert_eq!(families, ["Alpha Missing Family", "Beta Missing Family"]);
|
||||
}
|
||||
|
||||
/// A placed document that Links › Edit Original opens asks about its fonts, as File › Open does.
|
||||
#[test]
|
||||
fn edit_original_asks_about_the_placed_documents_fonts() {
|
||||
|
||||
@@ -42,7 +42,7 @@ use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
use craft::menu::Node;
|
||||
use craft::ui::contract::Show as _;
|
||||
use craft::ui::contract::{Bind, Show as _};
|
||||
use craft::ui::dialog::{DialogId, DialogResult, DialogStack, Prompt, StackDialog, dialog_id};
|
||||
use craft::ui::display::{Shade, Text};
|
||||
use craft::ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, Param, ParamDialog};
|
||||
@@ -548,7 +548,13 @@ pub(super) fn heading(plugin: &str, command: Option<&str>, gone: &str) -> String
|
||||
/// The builder of a hosted plug-in dialog over its values: the rows of `all` whose parameter is
|
||||
/// shown for the values (`m.visible`), after the description. The rows are made again in the UI
|
||||
/// language when it changes while the dialog is open; the field values stay as they are.
|
||||
fn build(key: &'static str, m: Manifest, all: Arc<[Param]>, look: Look) -> impl for<'b> Fn(&'b mut DialogFields) -> ParamDialog<'b> + Send + 'static {
|
||||
fn build(
|
||||
key: &'static str,
|
||||
m: Manifest,
|
||||
all: Arc<[Param]>,
|
||||
look: Look,
|
||||
canvas: Option<egui::Id>,
|
||||
) -> impl for<'b> Fn(&'b mut DialogFields) -> ParamDialog<'b> + Send + 'static {
|
||||
let rows_in = std::sync::Mutex::new((lang(), all));
|
||||
move |fields| {
|
||||
let all = {
|
||||
@@ -564,7 +570,10 @@ fn build(key: &'static str, m: Manifest, all: Arc<[Param]>, look: Look) -> impl
|
||||
rows.push(Param::read_only_text("description", "", look.description.clone()).full_width());
|
||||
}
|
||||
rows.extend(all.iter().filter(|p| shown.contains(p.key.as_str())).cloned());
|
||||
let mut dialog = ParamDialog::new(key, look.heading(), Cow::Owned(rows)).previews(look.previews);
|
||||
let mut dialog = ParamDialog::new(key, look.heading(), Cow::Owned(rows)).previews(look.previews).values(Bind::bound(fields));
|
||||
if let Some(canvas) = canvas.filter(|_| look.previews) {
|
||||
dialog = dialog.canvas(canvas);
|
||||
}
|
||||
if let Some(ok) = look.ok {
|
||||
dialog = dialog.ok_label(ok.into());
|
||||
}
|
||||
@@ -592,7 +601,8 @@ fn open_hosted(
|
||||
close_open(app);
|
||||
let all: Arc<[Param]> = form::plugin_params(&m, &values).into();
|
||||
let fields = form::fields_of(&all, &values);
|
||||
let dialog = HostedParamDialog::new(&ctx, key, fields, build(key, m, Arc::clone(&all), look)).instance(instance.to_string());
|
||||
let canvas = crate::doc_windows::current(app).map(crate::canvas::canvas_id);
|
||||
let dialog = HostedParamDialog::new(&ctx, key, fields, build(key, m, Arc::clone(&all), look, canvas)).instance(instance.to_string());
|
||||
let id = dialogs.with(|host| host.open(dialog));
|
||||
Ok((id, all))
|
||||
}
|
||||
|
||||
@@ -14,7 +14,6 @@ use craft::ui::contract::{Bind, CollectionEvent, Gap, Props as _, Show as _, Sho
|
||||
use craft::ui::layout_components::{Row, Stack};
|
||||
use craft::ui::patterns::form_dialogs::{CustomContext, DialogFields, FieldValue, HostedParamDialog, Param, ParamKind, ParamRows};
|
||||
use craft::ui::pickers::Select;
|
||||
use craft::ui::runtime::env::LengthUnits;
|
||||
use craft::ui::runtime::env::UnitKind;
|
||||
use craft::ui::sections::{DialogRole, FooterButton};
|
||||
use craft::ui::tabs::{Tab, TabKind, TabStrip};
|
||||
@@ -194,12 +193,11 @@ impl Rows<'_> {
|
||||
self.range(key, label, range, 1, UnitKind::Percent)
|
||||
}
|
||||
|
||||
/// A length in points, its unit shown as [`length_unit`](super::three_d_classic::length_unit) says.
|
||||
/// A length in points, shown in the general unit as [`length_units`](super::three_d_classic::length_units) says.
|
||||
fn length(&self, key: &str, label: &'static str, range: (f64, f64)) -> Param {
|
||||
// Stored in points; a pixel is a point, as the rulers count it.
|
||||
let lengths = LengthUnits::new(UnitKind::Points, crate::canvas::rulers::unit_kind(self.unit), 72.0);
|
||||
let shown = super::three_d_classic::length_unit(self.unit);
|
||||
self.range(key, label, range, 1, shown).length(crate::fields::bare_points(lengths, self.bare_points))
|
||||
let lengths = super::three_d_classic::length_units(self.unit, self.bare_points);
|
||||
let row = Param::new(key, label, ParamKind::range(range.0, range.1, self.default_number(key), SliderScale::Linear)).resettable();
|
||||
super::three_d_classic::as_length(row, lengths)
|
||||
}
|
||||
|
||||
fn flag(&self, key: &str, label: &'static str) -> Param {
|
||||
|
||||
@@ -494,10 +494,10 @@ fn the_bevel_repeat_and_the_revolve_segments_show_no_unit() {
|
||||
assert_eq!(unit(EXTRUDE, "object", "taper"), Some(Some(UnitKind::Percent)));
|
||||
}
|
||||
|
||||
/// The depth, bevel and offset rows of Extrude & Bevel and Revolve, classic ones included, are lengths in points: their
|
||||
/// sliders show "pt" in a points document, "px" in a pixels one, and points in a document of any other unit.
|
||||
/// The depth, bevel and offset rows of Extrude & Bevel and Revolve, classic ones included, hold points and show the
|
||||
/// document's unit: "pt" in a points document, "px" in a pixels one, "mm" in a millimeters one, "in" in an inches one.
|
||||
#[test]
|
||||
fn the_3d_length_rows_show_the_unit_of_the_number_they_hold() {
|
||||
fn the_3d_length_rows_show_the_document_unit() {
|
||||
use craft::ui::patterns::form_dialogs::DialogFields;
|
||||
use craft::ui::runtime::env::UnitKind;
|
||||
use vectorcraft_doc::Unit;
|
||||
@@ -510,7 +510,13 @@ fn the_3d_length_rows_show_the_unit_of_the_number_they_hold() {
|
||||
super::params(&data, &fields, super::Place::Dialog).into_iter().find(|p| p.key == key).map(|p| p.unit)
|
||||
};
|
||||
let mut checked = 0;
|
||||
for (general, shown) in [(Unit::Points, UnitKind::Points), (Unit::Pixels, UnitKind::Pixels), (Unit::Millimeters, UnitKind::Points)] {
|
||||
let units = [
|
||||
(Unit::Points, UnitKind::Points),
|
||||
(Unit::Pixels, UnitKind::Pixels),
|
||||
(Unit::Millimeters, UnitKind::Millimetres),
|
||||
(Unit::Inches, UnitKind::Inches),
|
||||
];
|
||||
for (general, shown) in units {
|
||||
for key in ["depth", "bevelWidth", "bevelHeight"] {
|
||||
assert_eq!(unit(general, EXTRUDE, "object", key), Some(Some(shown)), "{key} in {general:?}");
|
||||
checked += 1;
|
||||
@@ -526,7 +532,56 @@ fn the_3d_length_rows_show_the_unit_of_the_number_they_hold() {
|
||||
checked += 1;
|
||||
}
|
||||
}
|
||||
assert_eq!(checked, 21);
|
||||
assert_eq!(checked, 28);
|
||||
}
|
||||
|
||||
/// In a millimeters document the 3D dialogs' depth and offset fields show the 72 pt they hold as 25.4 mm, and a
|
||||
/// number typed there is read in millimeters and kept unrounded; Up steps by a millimeter step.
|
||||
#[test]
|
||||
fn a_3d_dialog_in_a_millimeters_document_shows_its_lengths_in_millimeters() {
|
||||
use craft::ui::contract::Role;
|
||||
let rows = [
|
||||
(CLASSIC_EXTRUDE, "object", "depth", "Depth"),
|
||||
(CLASSIC_REVOLVE, "object", "offset", "Offset"),
|
||||
(EXTRUDE, "object", "depth", "Depth"),
|
||||
(REVOLVE, "rotation", "offset", "Offset"),
|
||||
];
|
||||
for (effect, page, key, name) in rows {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width":300,"height":300,"units":"Millimeters"})).unwrap();
|
||||
app.run("path.create", json!({"d": SQUARE})).unwrap();
|
||||
let mut h = opened(app, json!({"effect": effect, "item": null}));
|
||||
h.set("__page", json!(page));
|
||||
h.set(key, json!(72.0));
|
||||
let field = |h: &ThreeD| {
|
||||
let tree = h.fixture.tree();
|
||||
h.fixture
|
||||
.by_role(Role::SPIN_BUTTON)
|
||||
.into_iter()
|
||||
.find(|t| tree.name_of(t.node) == Some(name))
|
||||
.unwrap_or_else(|| panic!("{effect}: no {name} field"))
|
||||
};
|
||||
let shown = h.fixture.tree().value_of(field(&h).node).map(str::to_owned);
|
||||
assert!(shown.as_deref().is_some_and(|s| s.contains("25.4") && s.contains("mm")), "{effect} {key}: 72 pt shows as 25.4 mm: {shown:?}");
|
||||
let target = field(&h);
|
||||
h.fixture.click(&target);
|
||||
// Tab commits the field and leaves the dialog open (Enter would press OK).
|
||||
h.fixture.key(Key::A, Modifiers::COMMAND).type_text("10").key(Key::Tab, Modifiers::NONE);
|
||||
h.settle();
|
||||
let stored = h.json(key);
|
||||
assert!(
|
||||
stored.as_f64().is_some_and(|points| (points - 10.0 * 72.0 / 25.4).abs() < 1e-3),
|
||||
"{effect} {key}: 10 mm is kept in points: {stored:?}"
|
||||
);
|
||||
// Up moves by the shown unit's own step, at least a tenth of a millimeter.
|
||||
let target = field(&h);
|
||||
h.fixture.click(&target);
|
||||
h.fixture.key(Key::ArrowUp, Modifiers::NONE).key(Key::Tab, Modifiers::NONE);
|
||||
h.settle();
|
||||
let moved = h.json(key).as_f64().zip(stored.as_f64()).map(|(after, before)| after - before);
|
||||
assert!(moved.is_some_and(|by| by >= 0.1 * 72.0 / 25.4 - 1e-6), "{effect} {key}: Up moves at least 0.1 mm: {moved:?}");
|
||||
h.cancel();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -117,6 +117,20 @@ fn pdf_page_footer_ok_opens_the_chosen_range() {
|
||||
assert_eq!(artboard_widths(h.state()), [200.0, 300.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn confirming_a_desktop_pdf_import_queues_the_read_and_closes_the_dialog() {
|
||||
crate::opening::tests::with_threads(|| {
|
||||
let mut app = app();
|
||||
io::open_bytes(&mut app, "three.pdf", &three_pages(), Some("three.pdf".into())).unwrap();
|
||||
set(&mut app, "allPages", json!(false));
|
||||
set(&mut app, "range", json!("2-3"));
|
||||
confirm(&mut app).unwrap();
|
||||
assert!(!is_open(&app));
|
||||
assert_eq!(app.opening.pending.len(), 1);
|
||||
assert_eq!(app.opening.pending[0].path, "three.pdf");
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn opening_a_multi_page_pdf_asks_for_the_pages() {
|
||||
let mut app = app();
|
||||
|
||||
@@ -20,7 +20,7 @@ use craft::ui::list::ThumbAspect;
|
||||
use craft::ui::patterns::form_dialogs::{CustomContext, DialogFields, FieldValue, HostedParamDialog, Param, ParamKind};
|
||||
use craft::ui::pickers::Select;
|
||||
use craft::ui::primitives::ContentPainterCx;
|
||||
use craft::ui::runtime::env::{Env, UnitKind};
|
||||
use craft::ui::runtime::env::{Env, LengthUnits, UnitKind};
|
||||
use craft::ui::sections::{DialogRole, FooterButton};
|
||||
use craft::ui::style::DataColor;
|
||||
use craft::ui::text::NumberField;
|
||||
@@ -50,13 +50,23 @@ const MAP_SYMBOL: &str = "mapSymbol";
|
||||
/// The Map Art page's rows of the shown surface's map: views of `mapArt`, never effect parameters.
|
||||
pub(super) const MAP_ROWS: [&str; 6] = [MAP_SYMBOL, MAP_KEYS[0], MAP_KEYS[1], MAP_KEYS[2], MAP_KEYS[3], MAP_KEYS[4]];
|
||||
|
||||
/// The unit shown after a 3D length row, whose slider shows the number of points it holds: the general `unit` when
|
||||
/// that counts the same number (points, or pixels at 72 per inch), and points otherwise.
|
||||
pub(super) fn length_unit(unit: Unit) -> UnitKind {
|
||||
match crate::canvas::rulers::unit_kind(unit) {
|
||||
UnitKind::Pixels => UnitKind::Pixels,
|
||||
_ => UnitKind::Points,
|
||||
}
|
||||
/// The lengths of a 3D length row: stored in points and shown in the general `unit` (a pixel is a point, as the rulers
|
||||
/// count it), a bare number read as Numbers Without Units Are Points (`bare_points`) says.
|
||||
pub(super) fn length_units(unit: Unit, bare_points: bool) -> LengthUnits {
|
||||
crate::fields::bare_points(LengthUnits::new(UnitKind::Points, crate::canvas::rulers::unit_kind(unit), 72.0), bare_points)
|
||||
}
|
||||
|
||||
/// `row`, a range row of points with no decimals set, as a length shown in `lengths.shown`. Without set decimals the
|
||||
/// field keeps the shown unit's own places and step, and the points are kept unrounded, so a value typed in
|
||||
/// millimeters or inches reads back as typed.
|
||||
pub(super) fn as_length(row: Param, lengths: LengthUnits) -> Param {
|
||||
row.unit(lengths.shown).length(lengths)
|
||||
}
|
||||
|
||||
/// A length row over `range` points with the effect's default, shown as [`as_length`] says.
|
||||
fn length_row(effect: &str, key: &str, label: &'static str, range: (f64, f64), lengths: LengthUnits) -> Param {
|
||||
let default = vectorcraft_effects::default_params(effect).and_then(|p| p.get(key).and_then(Value::as_f64)).unwrap_or(range.0);
|
||||
as_length(Param::new(key, label, ParamKind::range(range.0, range.1, default, SliderScale::Linear)).resettable(), lengths)
|
||||
}
|
||||
|
||||
/// Where the rows show: the 3D and Materials panel marks its fields with `__panel`.
|
||||
@@ -120,15 +130,15 @@ fn map_art_button(fields: &DialogFields) -> Option<Param> {
|
||||
/// Extrude & Bevel (Classic)'s Object page: depth and cap, then the bevel: its shape (a custom one included), its
|
||||
/// height and whether it is added around the shape or carved into it.
|
||||
pub(crate) fn object_params(data: &Data, fields: &DialogFields, effect: &str) -> Vec<Param> {
|
||||
let unit = Some(length_unit(data.unit));
|
||||
let lengths = length_units(data.unit, data.bare_points);
|
||||
let shaped: Vec<&str> = options_of(effect, "bevel").into_iter().map(|(value, _)| value).filter(|v| *v != "none").collect();
|
||||
let mut rows = vec![
|
||||
Param::section(tl!("Object")),
|
||||
range_row(effect, "depth", tl!("Depth"), (0.0, 2000.0), unit, 1),
|
||||
length_row(effect, "depth", tl!("Depth"), (0.0, 2000.0), lengths),
|
||||
cap_row(effect),
|
||||
Param::section(c3("Bevel")),
|
||||
bevel_row(data, CLASSIC_EXTRUDE, place_of(fields)),
|
||||
range_row(effect, "bevelHeight", tl!("Height"), (1.0, 100.0), unit, 1).enabled_when_in("bevel", shaped.clone()),
|
||||
length_row(effect, "bevelHeight", tl!("Height"), (1.0, 100.0), lengths).enabled_when_in("bevel", shaped.clone()),
|
||||
toggle_row(effect, "bevelInside", tl!("Bevel Inside")).enabled_when_in("bevel", shaped),
|
||||
];
|
||||
rows.extend(map_art_button(fields));
|
||||
@@ -141,7 +151,7 @@ pub(crate) fn revolve_params(data: &Data, fields: &DialogFields, effect: &str) -
|
||||
Param::section(tl!("Object")),
|
||||
range_row(effect, "angle", tl!("Angle"), (0.0, 360.0), Some(UnitKind::Degrees), 1),
|
||||
cap_row(effect),
|
||||
range_row(effect, "offset", tl!("Offset"), (0.0, 1000.0), Some(length_unit(data.unit)), 1),
|
||||
length_row(effect, "offset", tl!("Offset"), (0.0, 1000.0), length_units(data.unit, data.bare_points)),
|
||||
choice_row(effect, "edge", tl!("Axis side")),
|
||||
];
|
||||
rows.extend(map_art_button(fields));
|
||||
@@ -272,8 +282,9 @@ fn set_map_value(fields: &mut DialogFields, key: &str, value: Value) -> Result<(
|
||||
let n = value.as_f64().filter(|n| n.is_finite()).ok_or("not a number")?;
|
||||
let mut m = old.ok_or("the surface has no map")?;
|
||||
match key {
|
||||
"mapX" => m.x = round_clamp(n, 2, -GRAPHIC_MAX_OFFSET, GRAPHIC_MAX_OFFSET),
|
||||
"mapY" => m.y = round_clamp(n, 2, -GRAPHIC_MAX_OFFSET, GRAPHIC_MAX_OFFSET),
|
||||
// X and Y arrive in points converted from the document's unit: rounding them would move a typed 10 mm.
|
||||
"mapX" => m.x = n.clamp(-GRAPHIC_MAX_OFFSET, GRAPHIC_MAX_OFFSET),
|
||||
"mapY" => m.y = n.clamp(-GRAPHIC_MAX_OFFSET, GRAPHIC_MAX_OFFSET),
|
||||
"mapScaleX" => m.scale_x = round_clamp(n, 2, GRAPHIC_SCALE_RANGE.0, GRAPHIC_SCALE_RANGE.1),
|
||||
"mapScaleY" => m.scale_y = round_clamp(n, 2, GRAPHIC_SCALE_RANGE.0, GRAPHIC_SCALE_RANGE.1),
|
||||
"mapRotation" => m.rotation = n.clamp(-360.0, 360.0),
|
||||
@@ -370,6 +381,12 @@ fn map_of_box(state: &BoxState, rect: Rect, base: &SurfaceMap) -> SurfaceMap {
|
||||
}
|
||||
}
|
||||
|
||||
/// The map a box edit leaves, or none while the box is still the one `map` drew (`drawn`), so a frame without an edit
|
||||
/// keeps the map's numbers exactly as typed.
|
||||
fn map_after_edit(state: &BoxState, drawn: &BoxState, rect: Rect, map: &SurfaceMap) -> Option<SurfaceMap> {
|
||||
(state != drawn).then(|| map_of_box(state, rect, map)).filter(|moved| moved != map)
|
||||
}
|
||||
|
||||
/// The id of Map Art's Done, in the footer as Reset all is on the other pages.
|
||||
pub(crate) const MAP_DONE: &str = "mapDone";
|
||||
|
||||
@@ -406,6 +423,7 @@ fn flat_view(ui: &mut Ui, fields: &mut DialogFields, flat: &Flat) -> Response {
|
||||
}
|
||||
let (Some(m), Some(rect)) = (map.as_ref(), rect) else { return };
|
||||
let mut state = map_box(m, rect);
|
||||
let drawn = state;
|
||||
if m.rotation.abs() < 0.01
|
||||
&& let (Some(doc), Some((w, h))) = (flat.doc.as_ref(), flat.art)
|
||||
{
|
||||
@@ -422,8 +440,7 @@ fn flat_view(ui: &mut Ui, fields: &mut DialogFields, flat: &Flat) -> Response {
|
||||
.reference_point(false)
|
||||
.rotate_zone(RotateZone::border(18.0))
|
||||
.show_at(ui, body.rect);
|
||||
let moved = map_of_box(&state, rect, m);
|
||||
if moved != *m {
|
||||
if let Some(moved) = map_after_edit(&state, &drawn, rect, m) {
|
||||
edited = Some(moved);
|
||||
}
|
||||
});
|
||||
@@ -505,7 +522,7 @@ pub(crate) fn map_art_params(data: &Data, fields: &DialogFields, effect: &str) -
|
||||
let flat_row = flat.clone();
|
||||
rows.push(Param::custom("__mapFlat", "", move |ui, fields, _| flat_view(ui, fields, &flat_row)).full_width());
|
||||
if let Some(m) = &map {
|
||||
let unit = Some(length_unit(data.unit));
|
||||
let lengths = length_units(data.unit, data.bare_points);
|
||||
let values = [m.x, m.y, m.scale_x, m.scale_y, m.rotation];
|
||||
let labels = ["X", "Y", tl!("Horizontal Scale"), tl!("Vertical Scale"), tl!("Rotation")];
|
||||
let bounds = [
|
||||
@@ -515,14 +532,14 @@ pub(crate) fn map_art_params(data: &Data, fields: &DialogFields, effect: &str) -
|
||||
GRAPHIC_SCALE_RANGE,
|
||||
(-360.0, 360.0),
|
||||
];
|
||||
let kinds = [unit, unit, Some(UnitKind::Percent), Some(UnitKind::Percent), Some(UnitKind::Degrees)];
|
||||
// X and Y are lengths in points; the scales are shares and the rotation an angle.
|
||||
let kinds = [None, None, Some(UnitKind::Percent), Some(UnitKind::Percent), Some(UnitKind::Degrees)];
|
||||
for i in 0..MAP_KEYS.len() {
|
||||
let row = Param::new(MAP_KEYS[i], labels[i], ParamKind::range(bounds[i].0, bounds[i].1, values[i], SliderScale::Linear))
|
||||
.decimals(2)
|
||||
.on_set(set_map_value);
|
||||
let row =
|
||||
Param::new(MAP_KEYS[i], labels[i], ParamKind::range(bounds[i].0, bounds[i].1, values[i], SliderScale::Linear)).on_set(set_map_value);
|
||||
rows.push(match kinds[i] {
|
||||
Some(kind) => row.unit(kind),
|
||||
None => row,
|
||||
Some(kind) => row.decimals(2).unit(kind),
|
||||
None => as_length(row, lengths),
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -575,4 +592,26 @@ mod tests {
|
||||
let turned = map(190.0);
|
||||
assert_eq!(map_of_box(&map_box(&turned, rect), rect, &turned).rotation, -170.0, "a turn wraps to ±180");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn map_offsets_keep_the_points_a_document_unit_converts_to() {
|
||||
// 10 mm, as the X and Y rows hand it over in points.
|
||||
let ten_mm = 10.0 * 72.0 / 25.4;
|
||||
let mut fields = DialogFields::new();
|
||||
store_map(&mut fields, 1, Some(&map(0.0)));
|
||||
assert_eq!(set_map_value(&mut fields, "mapX", json!(ten_mm)), Ok(()));
|
||||
assert_eq!(set_map_value(&mut fields, "mapY", json!(-ten_mm)), Ok(()));
|
||||
let stored = maps_of(&fields).into_iter().find(|m| m.surface == 1).map(|m| (m.x, m.y));
|
||||
assert_eq!(stored, Some((ten_mm, -ten_mm)), "the typed offset is stored unrounded");
|
||||
assert_eq!(set_map_value(&mut fields, "mapX", json!(GRAPHIC_MAX_OFFSET * 2.0)), Ok(()));
|
||||
assert_eq!(maps_of(&fields).first().map(|m| m.x), Some(GRAPHIC_MAX_OFFSET), "the offset still keeps to its bounds");
|
||||
|
||||
// A frame without a box edit leaves those numbers as they are.
|
||||
let rect = art_rect((20.0, 10.0));
|
||||
let typed = SurfaceMap { x: ten_mm, y: -ten_mm, ..map(0.0) };
|
||||
let drawn = map_box(&typed, rect);
|
||||
assert_eq!(map_after_edit(&drawn, &drawn, rect, &typed), None);
|
||||
let dragged = drawn.moved(Vec2::new(1.0, 0.0));
|
||||
assert!(map_after_edit(&dragged, &drawn, rect, &typed).is_some(), "a drag still edits the map");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -150,11 +150,16 @@ pub(crate) fn open(app: &mut VectorcraftApp, kind: Kind, tool: &Value) {
|
||||
let document = app.session.active().map(|doc| (doc.uid, doc.reverts));
|
||||
let rows = rows(app, kind, &opening);
|
||||
let fields = fields_of(&rows, &opening);
|
||||
let canvas = crate::doc_windows::current(app).map(crate::canvas::canvas_id);
|
||||
let dialog = HostedParamDialog::new(&ctx, kind.command(), fields, move |f| {
|
||||
if kind == Kind::Move {
|
||||
link_distance_and_angle(f);
|
||||
}
|
||||
let dialog = ParamDialog::new(kind.command(), kind.title(), rows.clone()).previews(true).values(Bind::bound(f));
|
||||
let dialog = match canvas {
|
||||
Some(canvas) => dialog.canvas(canvas),
|
||||
None => dialog,
|
||||
};
|
||||
if kind == Kind::Move { dialog.remember(MOVE_KEY) } else { dialog }
|
||||
});
|
||||
// A dialog this one replaces leaves its preview behind otherwise.
|
||||
|
||||
@@ -114,7 +114,7 @@ pub(crate) fn family_picker<'a>(
|
||||
.filters(filters)
|
||||
.sets(sets)
|
||||
.scripts(&FontScript::ALL)
|
||||
.filter_layout(FilterLayout::Chips)
|
||||
.filter_layout(FilterLayout::Toolbar)
|
||||
}
|
||||
|
||||
/// What one pass of a picker reads of the app, for a host that has no `app` while it draws (a dialog).
|
||||
|
||||
@@ -92,6 +92,8 @@ pub use run::{check_params, run_ui_command};
|
||||
pub(crate) use run::{normalize_panel, opt_bool, opt_index, opt_number};
|
||||
#[cfg(test)]
|
||||
use slots::RECENT_FONT_IDS;
|
||||
#[cfg(test)]
|
||||
pub(crate) use state::WHY_OFF_ASKED;
|
||||
pub use state::{checked, enabled, plugin_revision, shortcut_of, shown_state};
|
||||
pub(crate) use state::{command_shortcuts, shown_state_with, why_off};
|
||||
pub(crate) use submenus::PATH_EFFECTS;
|
||||
|
||||
@@ -89,8 +89,10 @@ pub(crate) fn translate_label(english: &'static str) -> String {
|
||||
/// button pressed or released or a key pressed ([`last_press`]), changes once for each, which covers what the hash
|
||||
/// doesn't list (panels shown, a tool picked). While an
|
||||
/// interaction is open (for example a move, scale or shape drag, a dialog's or the font menu's
|
||||
/// preview, or a typing session), the revision, which each of its previews changes, is left out:
|
||||
/// the hash changes as the interaction begins and as it ends.
|
||||
/// preview, or a typing session), the hash takes the revision the interaction began from in place of the current one,
|
||||
/// which each of its previews changes, and changes as it ends. The hash stays the same as a tool's drag begins. An
|
||||
/// interaction that a dialog, a panel or the font menu begins changes the hash as it begins, since commands that check
|
||||
/// for an open interaction change state then and the menus stay open while it previews.
|
||||
pub(crate) fn state_key(app: &VectorcraftApp, input: Option<u64>) -> u64 {
|
||||
let mut h = DefaultHasher::new();
|
||||
input.hash(&mut h);
|
||||
@@ -101,8 +103,9 @@ pub(crate) fn state_key(app: &VectorcraftApp, input: Option<u64>) -> u64 {
|
||||
let s = &app.session;
|
||||
(s.journal.len(), s.active_index(), s.clipboard.is_empty(), s.tool_composing()).hash(&mut h);
|
||||
if let Some(d) = s.active() {
|
||||
let revision = d.interaction.is_none().then_some(d.revision);
|
||||
(d.uid, revision, d.history.undo.len(), d.history.redo.len(), d.transparency_grid, d.print_tiling).hash(&mut h);
|
||||
let revision = d.interaction.as_ref().map_or(d.revision, |it| it.revision);
|
||||
let previewing = d.interaction.as_ref().is_some_and(|it| !it.by_tool());
|
||||
(d.uid, revision, previewing, d.history.undo.len(), d.history.redo.len(), d.transparency_grid, d.print_tiling).hash(&mut h);
|
||||
}
|
||||
(app.system_paste, app.last_effect.is_some(), app.ui.recent_files.len(), app.ui.recent_files.first(), app.recent_fonts().len()).hash(&mut h);
|
||||
// Apply Last Filter and Last Filter… are named after the filter that ran last.
|
||||
@@ -257,7 +260,7 @@ fn rebuild(app: &mut VectorcraftApp, target: Target) {
|
||||
// The Glyphs panel menu's East Asian glyph forms read the faces that draw the selected text from the layout this keeps.
|
||||
crate::panels::glyphs::refresh_form_faces(app);
|
||||
let listed = Listed::of(app);
|
||||
let mut build = Build { app, lang: crate::i18n::current(), states: CommandStates::new(), refs: Vec::new() };
|
||||
let mut build = Build { app, lang: crate::i18n::current(), states: CommandStates::new(), refs: Vec::new(), checks: Checks::default() };
|
||||
let menus: Vec<Menu> = menu_tree_named(app.session.prefs.font_names_in_english, &listed)
|
||||
.into_iter()
|
||||
.map(|(title, nodes)| {
|
||||
@@ -267,7 +270,7 @@ fn rebuild(app: &mut VectorcraftApp, target: Target) {
|
||||
if translated { menu.english(title) } else { menu }
|
||||
})
|
||||
.collect();
|
||||
let Build { mut states, refs, .. } = build;
|
||||
let Build { mut states, refs, mut checks, .. } = build;
|
||||
|
||||
// The catalog is built again only when what its rows are made from changed; edits and selection changes change
|
||||
// the rows' states alone.
|
||||
@@ -291,7 +294,7 @@ fn rebuild(app: &mut VectorcraftApp, target: Target) {
|
||||
CatalogRows { inputs, defs, known, accepted }
|
||||
}
|
||||
};
|
||||
row_states(app, &rows, &mut states);
|
||||
row_states(app, &rows, &mut states, &mut checks);
|
||||
crate::panels::panel_menu_states(app, &mut states);
|
||||
|
||||
let bar = MenuBar::new(menus);
|
||||
@@ -395,10 +398,10 @@ fn build_catalog(app: &VectorcraftApp, listed: &Listed, plays: &[(String, craft:
|
||||
|
||||
/// The state of every catalog row the tree did not set, and of the engine commands the palette lists that no row
|
||||
/// names.
|
||||
fn row_states(app: &VectorcraftApp, rows: &CatalogRows, states: &mut CommandStates) {
|
||||
fn row_states(app: &VectorcraftApp, rows: &CatalogRows, states: &mut CommandStates, checks: &mut Checks) {
|
||||
for d in &rows.defs {
|
||||
if states.get(&d.command).is_none() {
|
||||
states.set(d.command.clone(), row_state(app, &d.command, &d.label));
|
||||
states.set(d.command.clone(), row_state(app, &d.command, &d.label, checks));
|
||||
}
|
||||
}
|
||||
// The engine commands the palette lists and no row names (Asset Export's Remove and Rename) are dimmed there and say
|
||||
@@ -406,11 +409,28 @@ fn row_states(app: &VectorcraftApp, rows: &CatalogRows, states: &mut CommandStat
|
||||
for c in crate::palette::listed_engine_commands().filter(|c| !rows.known.contains(c.id)) {
|
||||
let command = CommandRef::new(c.id);
|
||||
if states.get(&command).is_none() {
|
||||
states.set(command.clone(), row_state(app, &command, c.label));
|
||||
states.set(command.clone(), row_state(app, &command, c.label, checks));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What [`why_off`] answered for each command id during one rebuild. The answer depends on the id and the app's state,
|
||||
/// not on the row's params, so the rows that share an id (Effect's dialogs, Window's panels, the interface languages)
|
||||
/// run their command's check once.
|
||||
#[derive(Default)]
|
||||
struct Checks(std::collections::HashMap<String, Option<Option<String>>>);
|
||||
|
||||
impl Checks {
|
||||
fn why_off(&mut self, app: &VectorcraftApp, id: &str) -> Option<Option<String>> {
|
||||
if let Some(why) = self.0.get(id) {
|
||||
return why.clone();
|
||||
}
|
||||
let why = why_off(app, id);
|
||||
self.0.insert(id.to_owned(), why.clone());
|
||||
why
|
||||
}
|
||||
}
|
||||
|
||||
/// `defs` without the commands a linked framework set defines (Undo, Redo, Cut, Copy, Paste and Tab's panels toggles):
|
||||
/// the set's definition is the command's. With them, the keys each has beyond the set's, as the set's keys and those
|
||||
/// (Cut, Copy and Paste's F2, F3 and F4 outside macOS).
|
||||
@@ -445,10 +465,9 @@ fn linked_defaults(command: &CommandRef) -> Option<Vec<Binding>> {
|
||||
|
||||
/// The state of the row `command`, named `label` in the catalog: on or dimmed with its reason, checked, and its title
|
||||
/// where the app shows another.
|
||||
fn row_state(app: &VectorcraftApp, command: &CommandRef, label: &str) -> CommandState {
|
||||
fn row_state(app: &VectorcraftApp, command: &CommandRef, label: &str, checks: &mut Checks) -> CommandState {
|
||||
let state_id = crate::keymap::state_id(command);
|
||||
let why = why_off(app, state_id);
|
||||
let (enabled, checked) = shown_state_with(app, state_id, &command.params, &why).unwrap_or((false, None));
|
||||
let (enabled, checked) = shown_state_with(app, state_id, &command.params, &mut |id| checks.why_off(app, id)).unwrap_or((false, None));
|
||||
let mut state = CommandState::new().enabled(enabled);
|
||||
if let Some(on) = checked {
|
||||
state = state.checked(on);
|
||||
@@ -458,7 +477,7 @@ fn row_state(app: &VectorcraftApp, command: &CommandRef, label: &str) -> Command
|
||||
state = state.title(shown.clone());
|
||||
}
|
||||
if !enabled {
|
||||
state = state.hint(off_reason_with(app, command, &shown, why));
|
||||
state = state.hint(off_reason_with(app, command, &shown, checks.why_off(app, state_id)));
|
||||
}
|
||||
state
|
||||
}
|
||||
@@ -493,6 +512,7 @@ struct Build<'a> {
|
||||
states: CommandStates,
|
||||
/// Every command reference the tree holds, its English label, and whether it is checkable.
|
||||
refs: Vec<(CommandRef, String, bool)>,
|
||||
checks: Checks,
|
||||
}
|
||||
|
||||
impl Build<'_> {
|
||||
@@ -548,22 +568,25 @@ impl Build<'_> {
|
||||
return Some(item);
|
||||
}
|
||||
let (id, params) = (command.id.as_str(), &command.params);
|
||||
let why = why_off(self.app, id);
|
||||
let (enabled, checked) = shown_state_with(self.app, id, params, &why)?;
|
||||
let (app, checks) = (self.app, &mut self.checks);
|
||||
let (enabled, checked) = shown_state_with(app, id, params, &mut |id| checks.why_off(app, id))?;
|
||||
let title = self.item_title(id, params, &item.label);
|
||||
let mut state = CommandState::new().enabled(enabled).title(title.clone());
|
||||
if let Some(on) = checked {
|
||||
state = state.checked(on);
|
||||
}
|
||||
let mut item = item;
|
||||
let tip = if id == "ui.expandDialog" && vectorcraft_engine::cmd::expand::has_appearance(&self.app.session) {
|
||||
Some(crate::i18n::tr(self.lang, crate::dialogs::expand::appearance_first()).to_string())
|
||||
// Expand… dimmed for appearance attributes says so in its tooltip; `why` holds what its check found, kept from
|
||||
// the state above.
|
||||
let appearance_first = crate::dialogs::expand::appearance_first();
|
||||
let why = if id == "ui.expandDialog" { self.checks.why_off(self.app, id) } else { None };
|
||||
let tip = if why.as_ref().is_some_and(|w| w.as_deref() == Some(appearance_first)) {
|
||||
Some(crate::i18n::tr(self.lang, appearance_first).to_string())
|
||||
} else if enabled {
|
||||
None
|
||||
} else {
|
||||
// The reason reads the check of the command's state id, which is `id` but for the framework's own rows.
|
||||
let state_id = crate::keymap::state_id(&command);
|
||||
let why = if state_id == id { why } else { why_off(self.app, state_id) };
|
||||
let why = self.checks.why_off(self.app, crate::keymap::state_id(&command));
|
||||
Some(off_reason_with(self.app, &command, &title, why))
|
||||
};
|
||||
if let Some(tip) = tip {
|
||||
@@ -658,6 +681,23 @@ mod tests {
|
||||
assert!(app.menus.states.get(&CommandRef::new("object.group")).is_some_and(CommandState::is_enabled));
|
||||
}
|
||||
|
||||
/// A rebuild runs the check of a command that many rows share once: Effect's dialogs, Window's panels, the
|
||||
/// interface languages and Envelope Distort's Release, which decides whether Make or Reset is shown.
|
||||
#[test]
|
||||
fn a_rebuild_checks_a_shared_command_once() {
|
||||
let (mut app, ctx) = app_with_document();
|
||||
app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap();
|
||||
app.run("shape.rectangle", json!({"x": 20, "y": 0, "width": 10, "height": 10})).unwrap();
|
||||
app.run("select.all", json!({})).unwrap();
|
||||
super::super::state::WHY_OFF_ASKED.with_borrow_mut(Vec::clear);
|
||||
refresh(&mut app, &ctx);
|
||||
let asked = super::super::state::WHY_OFF_ASKED.take();
|
||||
for id in ["effect.dialog", "window.panel", "app.language", "object.envelope.release"] {
|
||||
assert_eq!(asked.iter().filter(|a| *a == id).count(), 1, "{id}");
|
||||
}
|
||||
assert!(app.menus.states.get(&CommandRef::new("object.group")).is_some_and(CommandState::is_enabled), "the states follow the selection");
|
||||
}
|
||||
|
||||
/// A rebuild asks each dimmed row's command once whether it can run, for its state and its reason together.
|
||||
#[test]
|
||||
fn a_rebuild_checks_each_dimmed_row_once() {
|
||||
@@ -677,4 +717,30 @@ mod tests {
|
||||
assert!(app.menus.states.get(&CommandRef::new(id)).is_some_and(|s| !s.is_enabled()), "{id} is still dimmed");
|
||||
}
|
||||
}
|
||||
|
||||
/// A rebuild walks the selection's appearance once for Object › Expand…, for its state and its tooltip together.
|
||||
#[test]
|
||||
fn a_rebuild_walks_the_appearance_once_for_expand() {
|
||||
let (mut app, ctx) = app_with_document();
|
||||
let expand = CommandRef::new("ui.expandDialog");
|
||||
let tooltip = |app: &VectorcraftApp| app.menus.bar.items().into_iter().find(|it| it.command == expand).and_then(|it| it.tooltip.clone());
|
||||
let walks = |app: &mut VectorcraftApp| {
|
||||
super::super::state::APPEARANCE_WALKS.set(0);
|
||||
refresh(app, &ctx);
|
||||
super::super::state::APPEARANCE_WALKS.get()
|
||||
};
|
||||
app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap();
|
||||
assert_eq!(walks(&mut app), 1, "a plain rectangle");
|
||||
assert!(app.menus.states.get(&expand).is_some_and(CommandState::is_enabled));
|
||||
assert_eq!(tooltip(&app), None);
|
||||
app.run("appearance.addFill", json!({})).unwrap();
|
||||
assert_eq!(walks(&mut app), 1, "two fills");
|
||||
assert!(app.menus.states.get(&expand).is_some_and(|s| !s.is_enabled()));
|
||||
assert_eq!(tooltip(&app).as_deref(), Some(crate::dialogs::expand::appearance_first()));
|
||||
app.run("select.none", json!({})).unwrap();
|
||||
assert_eq!(walks(&mut app), 0, "nothing selected");
|
||||
// Dimmed with nothing selected, the row keeps the general reason as its tooltip, as before.
|
||||
let tip = tooltip(&app);
|
||||
assert!(tip.as_deref().is_some_and(|t| t != crate::dialogs::expand::appearance_first()), "{tip:?}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -153,13 +153,14 @@ pub(super) fn hidden_when_disabled(id: &str) -> bool {
|
||||
|
||||
/// Menu items another item stands in for right now: Envelope Distort's Reset with Warp and Reset
|
||||
/// with Mesh take the place of Make with Warp and Make with Mesh while an envelope is selected.
|
||||
fn swapped_out(app: &VectorcraftApp, id: &str) -> bool {
|
||||
/// `why_off` answers [`why_off`] for Release's id.
|
||||
fn swapped_out(id: &str, why_off: &mut dyn FnMut(&str) -> Option<Option<String>>) -> bool {
|
||||
let reset = match id {
|
||||
"object.envelope.makeWithWarp" | "object.envelope.makeWithMesh" => false,
|
||||
"object.envelope.resetWithWarp" | "object.envelope.resetWithMesh" => true,
|
||||
_ => return false,
|
||||
};
|
||||
enabled(app, "object.envelope.release") != reset
|
||||
why_off("object.envelope.release").is_none() != reset
|
||||
}
|
||||
|
||||
/// Menu items shown only with Preferences › Type › Show East Asian Options on: Type › Composite
|
||||
@@ -173,16 +174,21 @@ fn east_asian_hidden(app: &VectorcraftApp, id: &str) -> bool {
|
||||
/// another stands in for ([`swapped_out`]) or an East Asian item with those options hidden
|
||||
/// ([`east_asian_hidden`]).
|
||||
pub fn shown_state(app: &VectorcraftApp, id: &str, p: &Value) -> Option<(bool, Option<bool>)> {
|
||||
shown_state_with(app, id, p, &why_off(app, id))
|
||||
shown_state_with(app, id, p, &mut |id| why_off(app, id))
|
||||
}
|
||||
|
||||
/// [`shown_state`] from `why`, what [`why_off`] answered for `id`: a caller that also writes the reason a dimmed row
|
||||
/// gives runs the command's check once.
|
||||
pub(crate) fn shown_state_with(app: &VectorcraftApp, id: &str, p: &Value, why: &Option<Option<String>>) -> Option<(bool, Option<bool>)> {
|
||||
let en = why.is_none()
|
||||
/// [`shown_state`] with `why_off` answering [`why_off`] for each command id it asks about: a caller that keeps the
|
||||
/// answers runs each command's check once.
|
||||
pub(crate) fn shown_state_with(
|
||||
app: &VectorcraftApp,
|
||||
id: &str,
|
||||
p: &Value,
|
||||
why_off: &mut dyn FnMut(&str) -> Option<Option<String>>,
|
||||
) -> Option<(bool, Option<bool>)> {
|
||||
let en = why_off(id).is_none()
|
||||
&& (id != crate::addons::select::link_status::COMMAND || crate::addons::select::link_status::enabled(app, p))
|
||||
&& (!vectorcraft_engine::cmd::plugin::is_command_id(id) || crate::dialogs::plugin::canvas_item_enabled(app, id, p));
|
||||
if (!en && hidden_when_disabled(id)) || swapped_out(app, id) || east_asian_hidden(app, id) {
|
||||
if (!en && hidden_when_disabled(id)) || swapped_out(id, why_off) || east_asian_hidden(app, id) {
|
||||
return None;
|
||||
}
|
||||
Some((en, checked(app, id, p)))
|
||||
@@ -295,9 +301,30 @@ pub(crate) fn why_off(app: &VectorcraftApp, id: &str) -> Option<Option<String>>
|
||||
Err(why) => Some(Some(why)),
|
||||
};
|
||||
}
|
||||
if id == "ui.expandDialog" {
|
||||
return expand_dialog_off(app);
|
||||
}
|
||||
(!ui_enabled(app, id)).then_some(None)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// How many times [`expand_dialog_off`] walked the selection's appearance on this thread.
|
||||
pub(crate) static APPEARANCE_WALKS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// Why Object › Expand… can't open now: dimmed with nothing selected, and with
|
||||
/// [`crate::dialogs::expand::appearance_first`] for appearance attributes, which Expand Appearance expands first
|
||||
/// (#3089). The selection's appearance is walked once, for the row's state and its tooltip together.
|
||||
fn expand_dialog_off(app: &VectorcraftApp) -> Option<Option<String>> {
|
||||
if !app.session.active().is_some_and(|d| !d.selection.is_empty()) {
|
||||
return Some(None);
|
||||
}
|
||||
#[cfg(test)]
|
||||
APPEARANCE_WALKS.set(APPEARANCE_WALKS.get() + 1);
|
||||
vectorcraft_engine::cmd::expand::has_appearance(&app.session).then(|| Some(crate::dialogs::expand::appearance_first().to_string()))
|
||||
}
|
||||
|
||||
/// Can UI command `id` run now?
|
||||
fn ui_enabled(app: &VectorcraftApp, id: &str) -> bool {
|
||||
match id {
|
||||
@@ -388,10 +415,6 @@ fn ui_enabled(app: &VectorcraftApp, id: &str) -> bool {
|
||||
id if id.starts_with(crate::panels::symbols::USER_SLOT) => crate::panels::symbols::user_library(app, id).is_some(),
|
||||
"ui.saveBrushLibrary" => crate::panels::brushes::has_brushes(app),
|
||||
id if id.starts_with(crate::panels::brushes::USER_SLOT) => crate::panels::brushes::user_library(app, id).is_some(),
|
||||
// Dimmed for appearance attributes, which Expand Appearance expands first (#3089).
|
||||
"ui.expandDialog" => {
|
||||
app.session.active().is_some_and(|d| !d.selection.is_empty()) && !vectorcraft_engine::cmd::expand::has_appearance(&app.session)
|
||||
}
|
||||
"ui.spotColors" => app.session.active().is_some(),
|
||||
"ui.menuDialog" => app.session.active().is_some_and(|d| !d.selection.is_empty()),
|
||||
"ui.simplifyAuto" | "ui.simplifyMoreOptions" => crate::dialogs::simplify_slider::showing(app),
|
||||
|
||||
@@ -147,9 +147,12 @@ fn track(app: &mut VectorcraftApp, path: &str, done: Receiver<Result<ReadFile, S
|
||||
}
|
||||
|
||||
/// May the active document change now ([`poll`])?
|
||||
pub(crate) fn may_switch(app: &VectorcraftApp) -> bool {
|
||||
pub(crate) fn may_switch(app: &mut VectorcraftApp) -> bool {
|
||||
if app.any_dialog_open() || crate::dialogs::missing_fonts::waiting(app) {
|
||||
return false;
|
||||
}
|
||||
let s = &app.session;
|
||||
!(app.any_dialog_open() || crate::dialogs::missing_fonts::waiting(app) || s.in_interaction() || (s.tool_busy() && s.pointer_held()))
|
||||
!(s.in_interaction() || (s.tool_busy() && s.pointer_held()))
|
||||
}
|
||||
|
||||
/// Open the files that are ready (each frame). Not while a dialog is open: a document that opens
|
||||
|
||||
@@ -681,13 +681,35 @@ pub(crate) fn mixed_paints(app: &VectorcraftApp, ctx: &egui::Context) -> (bool,
|
||||
match pstate::<Option<(Key, (bool, bool))>>(ctx, "proxy-mixed") {
|
||||
Some((k, mixed)) if k == key => mixed,
|
||||
_ => {
|
||||
let mixed = app.session.proxy_mixed();
|
||||
let mixed = walk_mixed_paints(app);
|
||||
set_pstate(ctx, "proxy-mixed", Some((key, mixed)));
|
||||
mixed
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// [`mixed_paints`] for readers without a `Ui`, such as the panel menus' states: from the same cache while the app
|
||||
/// has its interface context, else from a walk of the selection.
|
||||
pub(crate) fn mixed_paints_now(app: &VectorcraftApp) -> (bool, bool) {
|
||||
match &app.ui_ctx {
|
||||
Some(ctx) => mixed_paints(app, ctx),
|
||||
None => walk_mixed_paints(app),
|
||||
}
|
||||
}
|
||||
|
||||
/// [`vectorcraft_engine::Session::proxy_mixed`], which walks the selection.
|
||||
fn walk_mixed_paints(app: &VectorcraftApp) -> (bool, bool) {
|
||||
#[cfg(test)]
|
||||
MIXED_PAINT_WALKS.set(MIXED_PAINT_WALKS.get() + 1);
|
||||
app.session.proxy_mixed()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// How many times [`walk_mixed_paints`] walked the selection on this thread.
|
||||
pub(crate) static MIXED_PAINT_WALKS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// The stroke the Stroke panel, Control bar and Properties show: while the Type tool edits text,
|
||||
/// the selected characters' stroke, else [`vectorcraft_engine::Session::shown_stroke`].
|
||||
pub(crate) fn current_stroke(app: &VectorcraftApp) -> Option<StrokeLayer> {
|
||||
@@ -1108,6 +1130,31 @@ pub(crate) fn popover_body<R>(ui: &mut Ui, mut body: impl FnMut(&mut Ui) -> R) -
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// The panel menus' states (the Color and Color Wheel menus) read whether the fill and stroke differ from the
|
||||
/// proxies' cache: one walk of the selection for each revision, which the proxies read too.
|
||||
#[test]
|
||||
fn panel_menu_states_walk_the_mixed_paints_once_per_revision() {
|
||||
let mut app = crate::VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
|
||||
let ctx = crate::testing::ui_context();
|
||||
app.adopt_context(&ctx);
|
||||
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
|
||||
for x in [10, 60, 110] {
|
||||
app.run("shape.rectangle", json!({"x": x, "y": 10, "width": 40, "height": 40})).unwrap();
|
||||
}
|
||||
app.run("select.all", json!({})).unwrap();
|
||||
let walks = || MIXED_PAINT_WALKS.get();
|
||||
let start = walks();
|
||||
let mut states = CommandStates::new();
|
||||
panel_menu_states(&app, &mut states);
|
||||
assert_eq!(walks(), start + 1, "the menus walk the selection once");
|
||||
panel_menu_states(&app, &mut states);
|
||||
assert_eq!(mixed_paints(&app, &ctx), (false, false));
|
||||
assert_eq!(walks(), start + 1, "the same revision is not walked again, by the menus or the proxies");
|
||||
app.run("paint.setFill", json!({"color": "#ff0000"})).unwrap();
|
||||
panel_menu_states(&app, &mut states);
|
||||
assert_eq!(walks(), start + 2, "an edit is walked again");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn proxy_events_run_their_commands() {
|
||||
let ran = |activated, double, swap, defaults| -> Vec<(&'static str, Value)> { proxy_commands(activated, double, swap, defaults) };
|
||||
|
||||
@@ -158,7 +158,7 @@ pub(crate) fn step_place(step: usize, in_batch: Option<usize>) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// `text` as a status message shows it: control characters become `�`, and text past 80
|
||||
/// `text` as a status message shows it: control characters become `\u{FFFD}`, and text past 80
|
||||
/// characters ends in `…`.
|
||||
pub(crate) fn shown_text(text: &str) -> String {
|
||||
const MAX: usize = 80;
|
||||
|
||||
@@ -89,7 +89,9 @@ fn actions_play_on_the_artboard_active_when_they_play() {
|
||||
app.ui.actions.push(Action { set, ..Action::new(name, steps) }).unwrap();
|
||||
set_actions(app, 0).len() - 1
|
||||
};
|
||||
app.view_mut().unwrap().artboard = 1;
|
||||
app.run("edit.copy", json!({})).unwrap();
|
||||
app.view_mut().unwrap().artboard = 0;
|
||||
let align = record(&mut app, "Align Left", "object.align", json!({"horizontal": "left", "to": "artboard"}));
|
||||
assert_eq!(bounds(&app, &[rect]).x0, boards[0].x0, "aligned to artboard 0 while recording");
|
||||
let paste = record(&mut app, "Paste in Place", "edit.pasteInPlace", json!({}));
|
||||
|
||||
@@ -529,13 +529,22 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
let has_art = !st.selection.is_empty();
|
||||
let (selection, saving, reveal_save) = (&mut model.selection, &mut model.saving, &mut model.reveal_save);
|
||||
let (mut export_clicked, mut footer, mut screens) = (false, None, false);
|
||||
// The settings scroll in at most half the panel's height, so a long list of format rows stays reachable.
|
||||
// The preset name row stays below them, in view when Save As Preset opens it.
|
||||
let settings_room = ui.available_height() / 2.0;
|
||||
let settings_id = ui.scope_id().with(("asset-export-settings", uid));
|
||||
let mut settings_part = |ui: &mut Ui| {
|
||||
crate::panels::section(tl!("Export Settings")).show(ui, |ui, _| {
|
||||
let (change, files_each) = settings(ui, st);
|
||||
(seen.change, seen.files_each) = (change, files_each);
|
||||
seen.format_3d = format_3d(ui, st, &sel_or_all(&shown_sel, &all));
|
||||
seen.save = save_row(ui, saving, reveal_save);
|
||||
});
|
||||
Stack::new().id(settings_id).label(tl!("Export Settings")).fill_width().scroll(Scroll::vertical()).room_height(settings_room).show(
|
||||
ui,
|
||||
|ui, _| {
|
||||
crate::panels::section(tl!("Export Settings")).show(ui, |ui, _| {
|
||||
let (change, files_each) = settings(ui, st);
|
||||
(seen.change, seen.files_each) = (change, files_each);
|
||||
seen.format_3d = format_3d(ui, st, &sel_or_all(&shown_sel, &all));
|
||||
});
|
||||
},
|
||||
);
|
||||
seen.save = save_row(ui, saving, reveal_save);
|
||||
Row::new().fill_width().align(RowAlign::End).show(ui, |ui, _| {
|
||||
let label = if shown_sel.is_empty() || shown_sel.len() == all.len() {
|
||||
tl!("Export").to_string()
|
||||
|
||||
@@ -6,7 +6,6 @@ use std::cell::RefCell;
|
||||
use std::collections::HashSet;
|
||||
use std::rc::Rc;
|
||||
use std::sync::{Arc, Mutex, Weak};
|
||||
use std::time::SystemTime;
|
||||
|
||||
// PLAN: assumed the framework paths below (craft::text::ui re-exports, craft_ui widgets and runtime, craft::font_manager).
|
||||
use craft::behavior::EditEvent;
|
||||
@@ -47,12 +46,15 @@ use crate::font_menu;
|
||||
/// attributes of the paragraph the selection starts in (else of the first paragraph).
|
||||
/// Font/paragraph controls and named-style capture use this; dimensional fields use `shared_effective`.
|
||||
pub(crate) fn text_style(app: &VectorcraftApp) -> Option<(CharStyle, vectorcraft_doc::ParaStyle)> {
|
||||
let state = app.session.active()?;
|
||||
// Hover changes the canvas, but the picker compares its next row click against the committed font.
|
||||
let doc = state.interaction.as_ref().filter(|_| app.font_preview_owner.is_some()).map_or(&state.doc, |preview| &preview.doc);
|
||||
if let Some((id, a, b)) = text_editing(app)
|
||||
&& let Some(NodeKind::Text(t)) = app.session.active().and_then(|d| d.doc.node(id)).map(|n| &n.kind)
|
||||
&& let Some(NodeKind::Text(t)) = doc.node(id).map(|n| &n.kind)
|
||||
{
|
||||
return Some((vectorcraft_text::edit::insertion_style(&t.runs, a, b), t.para_at(t.paragraphs_in(a, a).start).clone()));
|
||||
}
|
||||
let t = first_selected_text(app)?;
|
||||
let NodeKind::Text(t) = &first_selected_text_node_in(state, doc)?.kind else { return None };
|
||||
Some((t.first_style(), t.para_at(0).clone()))
|
||||
}
|
||||
|
||||
@@ -68,7 +70,11 @@ pub(crate) fn first_selected_text(app: &VectorcraftApp) -> Option<&vectorcraft_d
|
||||
/// their descendants, in selection order, then paint order within each selected object.
|
||||
pub(crate) fn first_selected_text_node(app: &VectorcraftApp) -> Option<&vectorcraft_doc::Node> {
|
||||
let st = app.session.active()?;
|
||||
for node in st.selection.objects.iter().filter_map(|id| st.doc.node(*id)) {
|
||||
first_selected_text_node_in(st, &st.doc)
|
||||
}
|
||||
|
||||
fn first_selected_text_node_in<'a>(state: &DocState, doc: &'a vectorcraft_doc::Document) -> Option<&'a vectorcraft_doc::Node> {
|
||||
for node in state.selection.objects.iter().filter_map(|id| doc.node(*id)) {
|
||||
let mut text = None;
|
||||
node.walk(&mut |n| {
|
||||
if text.is_none() && matches!(n.kind, NodeKind::Text(_)) {
|
||||
@@ -1219,19 +1225,17 @@ pub(crate) fn controls(app: &mut VectorcraftApp, ui: &mut Ui, rows: CharacterRow
|
||||
let languages: Option<Vec<(String, String)>> =
|
||||
rows.contains(CharacterRows::STYLE_TOGGLES).then(|| LANGUAGES.iter().map(|(name, _, _)| (name.to_string(), name.to_string())).collect());
|
||||
let catalog = vectorcraft_text::FontDb::global().catalog();
|
||||
let before = font_menu::picker_settings(app);
|
||||
let mut settings = before.clone();
|
||||
let document = font_menu::document_family_set(app);
|
||||
let recent = font_menu::recently_added_set(app, SystemTime::now());
|
||||
let sets = font_menu::family_sets(Some(&document[..]), &recent[..]);
|
||||
let mut hold = font_menu::hold(app);
|
||||
let before = hold.settings.clone();
|
||||
let sets = font_menu::family_sets(hold.document.as_deref(), &hold.recently_added);
|
||||
let sample = font_menu::sample_text(app);
|
||||
let unit = type_unit(app);
|
||||
let mut source = FontPickerSource::new(catalog)
|
||||
.settings(Bind::bound(&mut settings))
|
||||
.filters(Bind::bound(&mut app.ui.font_filters))
|
||||
.settings(Bind::bound(&mut hold.settings))
|
||||
.filters(Bind::bound(&mut hold.filters))
|
||||
.sets(&sets)
|
||||
.scripts(&FontScript::ALL)
|
||||
.filter_layout(FilterLayout::Chips);
|
||||
.filter_layout(FilterLayout::Toolbar);
|
||||
if let Some(text) = &sample {
|
||||
source = source.preview_text(text);
|
||||
}
|
||||
@@ -1248,7 +1252,7 @@ pub(crate) fn controls(app: &mut VectorcraftApp, ui: &mut Ui, rows: CharacterRow
|
||||
controls = controls.axes(FaceAxes::new(axes, instances).italic(face_of(¤t.font_style).2));
|
||||
}
|
||||
let out = controls.show(ui);
|
||||
font_menu::store_picker_settings(app, &before, settings);
|
||||
hold.store(app, &before);
|
||||
let CharacterControlsOutput { picker, preview_family, edits, .. } = out;
|
||||
if let Some(owner) = picker {
|
||||
font_menu::apply_preview(app, owner, preview_family);
|
||||
|
||||
@@ -314,14 +314,14 @@ fn target(app: &VectorcraftApp, ui: &Ui) -> Target {
|
||||
target_with(app, super::active_mixed(app, ui.ctx()))
|
||||
}
|
||||
|
||||
/// Whether the active proxy is "?", read from the session (the panel reads its per-frame cache).
|
||||
/// Whether the active proxy is "?", from the proxies' cache ([`super::mixed_paints_now`]).
|
||||
fn mixed_now(app: &VectorcraftApp) -> bool {
|
||||
let (fill, stroke) = app.session.proxy_mixed();
|
||||
let (fill, stroke) = super::mixed_paints_now(app);
|
||||
if app.session.fill_active { fill } else { stroke }
|
||||
}
|
||||
|
||||
/// [`target`] with `mixed` for a "?" active proxy: the panel reads it from its per-frame cache,
|
||||
/// `ui.colorPanel` from the session.
|
||||
/// `ui.colorPanel` and the panel menus through [`mixed_now`].
|
||||
fn target_with(app: &VectorcraftApp, mixed: bool) -> Target {
|
||||
if mixed {
|
||||
return Target::Paint(None, None);
|
||||
@@ -440,7 +440,7 @@ pub(crate) fn apply_output(app: &mut VectorcraftApp, out: &ColorPanelOutput) {
|
||||
apply_with(app, &tgt, out);
|
||||
}
|
||||
|
||||
/// [`target`] with the session's "?" state, for callers without the panel's pass.
|
||||
/// [`target`] with the "?" state of [`mixed_now`], for callers without the panel's pass.
|
||||
pub(crate) fn target_now(app: &VectorcraftApp) -> Target {
|
||||
target_with(app, mixed_now(app))
|
||||
}
|
||||
@@ -616,8 +616,9 @@ pub(crate) fn menu_rows(_app: &VectorcraftApp) -> Vec<PanelRow> {
|
||||
/// The checks, titles and enabled states of [`menu_rows`]: the mode the panel shows is checked, and
|
||||
/// the rows that need a colour are off without one.
|
||||
pub(crate) fn menu_states(app: &VectorcraftApp, states: &mut CommandStates) {
|
||||
let tgt = target_now(app);
|
||||
let has_color = tgt.color().is_some() || mixed_now(app);
|
||||
let mixed = mixed_now(app);
|
||||
let tgt = target_with(app, mixed);
|
||||
let has_color = tgt.color().is_some() || mixed;
|
||||
for (command, state) in ColorPanelMenu::states(LAYOUT, &app.ui.color_panel, &shown(app, &tgt), has_color) {
|
||||
let state = if command == ColorPanelCommand::NewSwatch && !crate::menus::enabled(app, "swatch.new") { state.enabled(false) } else { state };
|
||||
states.set(command, state);
|
||||
|
||||
@@ -618,14 +618,15 @@ pub(crate) fn menu_rows(_app: &VectorcraftApp) -> Vec<PanelRow> {
|
||||
/// without a solid color, and CSS oklch() also while the active document's RGB space is not sRGB.
|
||||
pub(crate) fn menu_states(app: &VectorcraftApp, states: &mut CommandStates) {
|
||||
let srgb = cms::active().rgb_is_srgb();
|
||||
for item in items(&app.ui.color_wheel, srgb, target_now(app).color()) {
|
||||
let color = target_now(app).color();
|
||||
for item in items(&app.ui.color_wheel, srgb, color) {
|
||||
let mut state = CommandState::new().title(item.label).enabled(item.enabled).checked(item.checked);
|
||||
if let Some(hint) = item.hint {
|
||||
state = state.hint(hint);
|
||||
}
|
||||
states.set(CommandRef::new(row_id(&item.id)), state);
|
||||
}
|
||||
let has_color = target_now(app).color().is_some();
|
||||
let has_color = color.is_some();
|
||||
for (notation, label) in copy_notations() {
|
||||
let oklch = notation == "oklch";
|
||||
let mut state = CommandState::new().title(label.to_string()).enabled(has_color && (srgb || !oklch));
|
||||
|
||||
@@ -59,6 +59,12 @@ pub(crate) fn copy_value(ui: &mut Ui, label: &str, value: &str, mono: bool) -> b
|
||||
/// The same guarded full-value copy for an already shown readout. An elided path remains
|
||||
/// static text: selection indices must describe the text actually shown by the framework.
|
||||
pub(crate) fn copy_shown(ui: &mut Ui, shown: &egui::Response, value: &str) -> bool {
|
||||
// A container's measuring run shows the readout in an invisible sizing pass before the frame's real run, with the
|
||||
// same id and the same input. It neither copies nor reads or clears the remembered press: clearing it there would
|
||||
// leave the real run's release without its press.
|
||||
if ui.is_sizing_pass() {
|
||||
return false;
|
||||
}
|
||||
// The click's own position and keys: a move or a key change after the release in the same
|
||||
// frame leaves the pointer and the held keys elsewhere. A frame with more than one release
|
||||
// copies nothing, since the click flags below do not say which release they describe.
|
||||
|
||||
@@ -182,8 +182,9 @@ pub struct LayersUi {
|
||||
/// The selection square clicked last in each open document, by the document's `uid`: where a Shift-click on another
|
||||
/// square starts.
|
||||
pub art_anchors: HashMap<u64, NodeId>,
|
||||
/// The active document's rows with the [`LayerRows::key`] they were listed at.
|
||||
rows: Option<(u64, Tracked<LayerRows>)>,
|
||||
/// The active document's rows with the [`LayerRows::key`] they were listed at and the document's `uid` and
|
||||
/// `reverts`.
|
||||
rows: Option<(u64, (u64, u64), Tracked<LayerRows>)>,
|
||||
}
|
||||
|
||||
impl Default for LayersUi {
|
||||
@@ -223,7 +224,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
thumbnails.hold(app.session.active().is_some_and(|st| st.interaction.is_some()) || app.session.tool_busy());
|
||||
let settings = app.ui.layers_panel.settings();
|
||||
refresh_rows(app);
|
||||
let (Some(st), Some((_, kept))) = (app.session.active(), &app.ui.layers_ui.rows) else { return };
|
||||
let (Some(st), Some((_, _, kept))) = (app.session.active(), &app.ui.layers_ui.rows) else { return };
|
||||
let tree = DocLayers::of(st, kept);
|
||||
let source = thumbs::LayerThumbs { doc: &st.doc };
|
||||
let mut panel = LayersPanel::new(kept)
|
||||
@@ -294,13 +295,23 @@ fn unrevealed<T>(app: &mut VectorcraftApp, f: impl FnOnce(&mut VectorcraftApp) -
|
||||
r
|
||||
}
|
||||
|
||||
/// Lists the active document's rows again when what they are listed from changed.
|
||||
/// Lists the active document's rows again when what they are listed from changed. The new rows go into the kept
|
||||
/// [`Tracked`] while the document is the same, so the panel keeps its display order when the
|
||||
/// [order revision](LayerRows::order_of) stays; another document, or the same one after File › Revert, gets a new one.
|
||||
fn refresh_rows(app: &mut VectorcraftApp) {
|
||||
let Some(st) = app.session.active() else { return };
|
||||
let key = LayerRows::key(app, st);
|
||||
if app.ui.layers_ui.rows.as_ref().is_none_or(|(kept, _)| *kept != key) {
|
||||
let rows = Tracked::new(LayerRows::new(app, st));
|
||||
app.ui.layers_ui.rows = Some((key, rows));
|
||||
let doc = (st.uid, st.reverts);
|
||||
if app.ui.layers_ui.rows.as_ref().is_some_and(|(kept, _, _)| *kept == key) {
|
||||
return;
|
||||
}
|
||||
let new = LayerRows::new(app, st);
|
||||
match &mut app.ui.layers_ui.rows {
|
||||
Some((kept, of, rows)) if *of == doc => {
|
||||
rows.edit(|rows| *rows = new);
|
||||
*kept = key;
|
||||
}
|
||||
slot => *slot = Some((key, doc, Tracked::new(new))),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -202,6 +202,14 @@ pub(super) struct LayerRows {
|
||||
/// In isolation mode, the isolated node: the top row.
|
||||
#[plain_data(assume = "a node id is an integer")]
|
||||
root: Option<NodeId>,
|
||||
/// What the display order is built from ([`LayerRows::order_of`]).
|
||||
order: u64,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// How many times [`LayerRows::children`] was asked on this thread.
|
||||
pub(super) static CHILDREN_CALLS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// [`LayerRows`] with the editing state of their document, for the panel's host code in one pass.
|
||||
@@ -243,7 +251,9 @@ impl LayerRows {
|
||||
let guide_rows = ruler.iter().enumerate().filter_map(|(i, g)| Some((g.id?, i))).collect();
|
||||
let blends = st.selection.objects.iter().copied().filter(|id| doc.node(*id).is_some_and(|n| matches!(n.kind, NodeKind::Blend { .. })));
|
||||
let selected: HashSet<NodeId> = st.selection.objects.iter().copied().collect();
|
||||
let root = st.isolation.and_then(|i| isolated_root(doc, i)).map(|(n, ..)| n.id);
|
||||
Self {
|
||||
order: Self::order_of(doc, &st.layers_open, app.ui.layers_panel.layers_only, root),
|
||||
doc: doc.clone(),
|
||||
opts: app.ui.layers_panel.clone(),
|
||||
xml_id: by_xml_id(app),
|
||||
@@ -258,10 +268,20 @@ impl LayerRows {
|
||||
holding: super::rows::holding(doc, &selected),
|
||||
selected,
|
||||
blends: blends.collect(),
|
||||
root: st.isolation.and_then(|i| isolated_root(doc, i)).map(|(n, ..)| n.id),
|
||||
root,
|
||||
}
|
||||
}
|
||||
|
||||
/// A hash of everything the display order reads ([`LayerTree::children`] and [`LayerTree::is_open`]): the
|
||||
/// document, which an edit replaces and a selection change keeps (its ruler guides and an opacity mask being
|
||||
/// edited are in it), the open rows, Show Layers Only and the isolated node. The selection, the highlighted rows,
|
||||
/// the current layer, the names and the other Panel Options are not in it.
|
||||
fn order_of(doc: &Arc<Document>, open: &OpenRows, layers_only: bool, root: Option<NodeId>) -> u64 {
|
||||
let mut hasher = DefaultHasher::new();
|
||||
(Arc::as_ptr(doc) as usize, open.generation(), layers_only, root).hash(&mut hasher);
|
||||
hasher.finish()
|
||||
}
|
||||
|
||||
/// What the rows of `st` are listed from: the document and its revision (which every edit and
|
||||
/// selection change moves), the open rows, isolation mode, the highlighted rows and the current
|
||||
/// layer, the Panel Options, Identify Objects By and the language.
|
||||
@@ -461,6 +481,8 @@ impl LayerTree for LayerRows {
|
||||
/// The top rows are the layers (only the opacity mask's while one is edited), or in isolation
|
||||
/// mode the isolated layer, sublayer, group or object.
|
||||
fn children(&self, parent: Option<&RowId>) -> Vec<RowId> {
|
||||
#[cfg(test)]
|
||||
CHILDREN_CALLS.with(|c| c.set(c.get() + 1));
|
||||
match parent {
|
||||
None => match self.root {
|
||||
Some(root) => vec![RowId::Node(root)],
|
||||
@@ -491,6 +513,11 @@ impl LayerTree for LayerRows {
|
||||
false
|
||||
}
|
||||
|
||||
/// The display order changes only with what [`LayerRows::order_of`] hashes: a selection change keeps it.
|
||||
fn order_revision(&self) -> Option<u64> {
|
||||
Some(self.order)
|
||||
}
|
||||
|
||||
fn info(&self, id: &RowId) -> LayerInfo {
|
||||
match *id {
|
||||
RowId::Node(id) => match self.doc.node(id) {
|
||||
|
||||
@@ -1352,3 +1352,78 @@ fn idle_frames_walk_no_node_for_the_selection_squares() {
|
||||
}
|
||||
assert!((1..=12).contains(&(visits() - before)), "a new selection walks the tree once: {}", visits() - before);
|
||||
}
|
||||
|
||||
/// A selection change keeps the panel's display order: no row is asked for the rows inside it. Closing a row, Show
|
||||
/// Layers Only and an edit build the order again, and the rows follow.
|
||||
#[test]
|
||||
fn a_selection_change_keeps_the_display_order() {
|
||||
use crate::tests::panel_harness::Panel;
|
||||
let calls = || super::model::CHILDREN_CALLS.with(std::cell::Cell::get);
|
||||
let (mut app, [_, sub, _, b, a, c]) = nested();
|
||||
for (id, name) in [(sub, "Sub"), (b, "B"), (a, "A"), (c, "C")] {
|
||||
name_row(&mut app, id, name);
|
||||
}
|
||||
app.session.execute("select.set", &json!({"ids": [b.0]})).unwrap();
|
||||
let mut panel = Panel::new(app, show);
|
||||
panel.frame();
|
||||
let before = calls();
|
||||
panel.app().session.execute("select.set", &json!({"ids": [a.0]})).unwrap();
|
||||
for _ in 0..3 {
|
||||
panel.frame();
|
||||
}
|
||||
assert_eq!(calls() - before, 0, "a selection change asks no row for its rows");
|
||||
assert!(panel.shows("A") && panel.shows("B"), "the rows stay");
|
||||
|
||||
expand(&mut panel.app(), &json!({"ids": [sub.0], "open": false})).unwrap();
|
||||
let before = calls();
|
||||
panel.frame();
|
||||
panel.frame();
|
||||
assert!(calls() > before, "closing a row builds the order again");
|
||||
assert!(!panel.shows("A") && panel.shows("Sub") && panel.shows("C"), "the closed sublayer's rows are gone");
|
||||
|
||||
panel.app().ui.layers_panel.layers_only = true;
|
||||
panel.frame();
|
||||
panel.frame();
|
||||
assert!(!panel.shows("C") && panel.shows("Sub"), "Show Layers Only leaves the objects out");
|
||||
|
||||
panel.app().ui.layers_panel.layers_only = false;
|
||||
panel.app().session.execute("object.isolate", &json!({"id": sub.0})).unwrap();
|
||||
panel.frame();
|
||||
panel.frame();
|
||||
assert!(panel.shows("Sub") && !panel.shows("C"), "isolation mode lists only the isolated sublayer");
|
||||
panel.app().session.execute("object.exitIsolation", &json!({})).unwrap();
|
||||
expand(&mut panel.app(), &json!({"ids": [sub.0], "open": true})).unwrap();
|
||||
let made = panel.app().session.execute("shape.rectangle", &json!({"x": 200, "y": 200, "width": 10, "height": 10})).unwrap();
|
||||
let d = NodeId(made["id"].as_u64().unwrap());
|
||||
name_row(&mut panel.app(), d, "D");
|
||||
panel.frame();
|
||||
panel.frame();
|
||||
assert!(panel.shows("D") && panel.shows("C"), "an edit lists the new object");
|
||||
}
|
||||
|
||||
/// The order revision stays through a selection change and moves with the document, the open rows, Show Layers Only
|
||||
/// and isolation mode.
|
||||
#[test]
|
||||
fn the_order_revision_follows_what_the_display_order_reads() {
|
||||
let order = |app: &VectorcraftApp| LayerRows::new(app, app.session.active().unwrap()).order_revision();
|
||||
let (mut app, [_, sub, g, b, a, _]) = nested();
|
||||
let first = order(&app);
|
||||
assert!(first.is_some(), "the rows report an order revision");
|
||||
app.session.execute("select.set", &json!({"ids": [b.0]})).unwrap();
|
||||
assert_eq!(order(&app), first, "a selection change keeps it");
|
||||
app.session.execute("object.isolate", &json!({"id": sub.0})).unwrap();
|
||||
let isolated = order(&app);
|
||||
assert_ne!(isolated, first, "isolation mode moves it");
|
||||
app.session.execute("object.exitIsolation", &json!({})).unwrap();
|
||||
let left = order(&app);
|
||||
assert_ne!(left, isolated, "leaving isolation mode moves it");
|
||||
app.ui.layers_panel.layers_only = true;
|
||||
assert_ne!(order(&app), left, "Show Layers Only moves it");
|
||||
app.ui.layers_panel.layers_only = false;
|
||||
assert_eq!(order(&app), left, "and turning it off gives it back");
|
||||
expand(&mut app, &json!({"ids": [g.0], "open": false})).unwrap();
|
||||
let closed = order(&app);
|
||||
assert_ne!(closed, left, "closing a row moves it");
|
||||
name_row(&mut app, a, "A");
|
||||
assert_ne!(order(&app), closed, "an edit moves it");
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user