mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-02 14:51:20 -05:00
Merge main into fix/windows-signing-test-annotation
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()
|
||||
@@ -1,11 +1,10 @@
|
||||
name: Cache prune
|
||||
|
||||
# A pass of the cache prune after every CI attempt on main. ci.yml's `cache prune` job prunes while
|
||||
# a run's jobs save their entries, but "Re-run failed jobs" re-runs only the failed jobs: a re-run
|
||||
# `cache warm` leg saves a new entry, and the prune job, which succeeded in the first attempt, does
|
||||
# not run again. The entry it replaced would stay until the next main run, and with it the cache
|
||||
# would be over its 10 GB budget, where GitHub evicts entries a run still needs. This runs once
|
||||
# after every attempt, re-runs and canceled runs included (craft-common-actions actions/cache-prune).
|
||||
# Keeps one rolling gate entry on main, so the repository stays within its 10 GB Actions cache
|
||||
# budget, where GitHub evicts entries a run still needs. Each main CI attempt's `cache warm` leg
|
||||
# saves a new rolling entry; this deletes the entry it replaced once the attempt ends. It runs once
|
||||
# after every attempt, re-runs of failed jobs and canceled runs included (craft-common-actions
|
||||
# actions/cache-prune).
|
||||
on:
|
||||
workflow_run:
|
||||
workflows: [CI]
|
||||
|
||||
+26
-33
@@ -26,7 +26,7 @@ jobs:
|
||||
uses: storytold/craft-common-actions/.github/workflows/gate.yml@main
|
||||
with:
|
||||
# Same craft-fonts commit as release.yml.
|
||||
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
|
||||
craft-fonts-ref: 16bbfc3d451fad51971ca3f2a28c1e69e279b67c
|
||||
# A cold `cache warm` leg (the nightly run, or any run after a toolchain or lockfile change)
|
||||
# took 90 minutes to reach its last three steps on 2026-11-27 and was canceled there; with
|
||||
# those steps and the save it needs about two hours.
|
||||
@@ -47,11 +47,27 @@ jobs:
|
||||
test-shards: 6
|
||||
shard-command: cargo xtask ci shard
|
||||
warm-command: cargo xtask ci warm
|
||||
# A pull request runs only the test shards whose crates its changes reach: the crates that
|
||||
# own a changed file or declare a read of it (`[package.metadata.craft] reads`), and every
|
||||
# crate that depends on them. Shard 6 runs on every event. The `select legs` log lists the
|
||||
# shards left out and why; pushes to main, the nightly run and the `full-ci` label run all
|
||||
# six. `shard-members` names each shard's crates, as xtask/src/shards.rs › GROUPS does.
|
||||
select-tests: true
|
||||
shard-members: |
|
||||
vectorcraft-ui-egui
|
||||
vectorcraft-ui-egui
|
||||
vectorcraft-engine
|
||||
vectorcraft vectorcraft-web vectorcraft-cli vectorcraft-mcp xtask
|
||||
(rest)
|
||||
(always)
|
||||
# The warm build runs as one `cache warm <k>/6` leg per shard, in parallel (each builds what
|
||||
# its shard builds), and `cache warm` puts their files into the one entry it saves.
|
||||
warm-split: true
|
||||
# The dependency cache also keeps the compiled workspace crates and test executables, so a
|
||||
# pull request's shards rebuild only the crates its changes reach. Each main run's `cache
|
||||
# warm` leg saves a rolling entry of its own, every leg restores the newest one, and
|
||||
# `cache-prune` below deletes the one it replaced. The nightly run restores nothing and
|
||||
# builds everything from source.
|
||||
# cache-prune.yml deletes the one it replaced after each attempt. The nightly run restores
|
||||
# nothing and builds everything from source.
|
||||
cache-workspace-crates: true
|
||||
cold-build: ${{ github.event_name == 'schedule' }}
|
||||
packages: >-
|
||||
@@ -59,46 +75,23 @@ jobs:
|
||||
libxrandr-dev libxi-dev libfontconfig1-dev libfreetype-dev mesa-vulkan-drivers
|
||||
libgl1-mesa-dev
|
||||
|
||||
# Keeps one rolling gate entry on main, so the repository stays within its 10 GB Actions cache
|
||||
# budget. It runs beside the gate and prunes each time the `cache warm` leg finishes saving. A
|
||||
# failed prune warns instead of failing the run, and cache-prune.yml prunes again after every
|
||||
# attempt, re-runs of failed jobs included. `watch-minutes` is longer than the gate's
|
||||
# `timeout-minutes`, so the watch outlasts a cold `cache warm` leg.
|
||||
cache-prune:
|
||||
name: cache prune
|
||||
if: github.event_name != 'pull_request' && github.ref == 'refs/heads/main'
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 170
|
||||
permissions:
|
||||
actions: write
|
||||
steps:
|
||||
- name: Harden runner
|
||||
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
|
||||
with:
|
||||
egress-policy: audit
|
||||
- name: Prune replaced cache entries
|
||||
uses: storytold/craft-common-actions/actions/cache-prune@main
|
||||
continue-on-error: true
|
||||
with:
|
||||
watch: true
|
||||
watch-minutes: 160
|
||||
saving-jobs: |
|
||||
^gate( / cache warm \(.*\))?$
|
||||
|
||||
# The nightly cold run never restores the rolling crates entry, so the old entry is only overlap
|
||||
# while the cold run saves its own: two entries of about 4.6 GB, which with the others go over the
|
||||
# 10 GB cache limit and get the corpus, SonarCloud and Windows ARM64 entries evicted. This deletes
|
||||
# the old entries when the `cache warm` leg starts saving (scripts/ci-clear-rolling-cache.py).
|
||||
# When the leg fails or is canceled, before its save or during it, this job fails too, so "Re-run
|
||||
# failed jobs" runs it again beside the re-run leg. The leg starts after `gate / select legs` and a
|
||||
# free runner: the script fails when the leg has not started within 120 minutes, and then waits
|
||||
# up to 160 minutes from the leg's start. This job's timeout is longer than both together, so the
|
||||
# script reports a leg that starts late with its own error before the job times out.
|
||||
# free runner, and with `warm-split` after every `cache warm <k>/6` leg. The script suspends its
|
||||
# start deadline while any split leg is queued or running, then allows 180 minutes from the last
|
||||
# split completion for the saving leg to start. Without split legs, it allows 180 minutes from
|
||||
# the script's start. A failed split leg fails this job too. The script then waits up to 160
|
||||
# minutes from the saving leg's start. GitHub's 360-minute job limit can end this job before the
|
||||
# script's deadlines expire when split builds or runner waits take too long.
|
||||
cold-cache-clear:
|
||||
name: cold cache clear
|
||||
if: github.event_name == 'schedule'
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 290
|
||||
timeout-minutes: 360
|
||||
permissions:
|
||||
actions: write
|
||||
steps:
|
||||
|
||||
@@ -29,7 +29,7 @@ jobs:
|
||||
uses: storytold/craft-common-actions/.github/workflows/freebsd.yml@main
|
||||
with:
|
||||
require-craft-fonts: true
|
||||
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
|
||||
craft-fonts-ref: 16bbfc3d451fad51971ca3f2a28c1e69e279b67c
|
||||
run-package-check: true
|
||||
# The test builds of this workspace's largest crates (engine, ui-egui) need more than the
|
||||
# VM's 12 GB when two compile at once: the build was killed (exit 137) every night with
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -47,7 +47,7 @@ jobs:
|
||||
- name: Check out craft-fonts
|
||||
uses: storytold/craft-common-actions/actions/checkout-craft-fonts@main
|
||||
with:
|
||||
ref: b076417b5880bd4154bd22f00695b1d28c6bea83
|
||||
ref: 16bbfc3d451fad51971ca3f2a28c1e69e279b67c
|
||||
- id: rust
|
||||
uses: storytold/craft-common-actions/actions/rust-channel@main
|
||||
with:
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
name: VectorCraft unsigned nightly
|
||||
|
||||
# Enabled for supervised manual runs by the reviewed manual actor only; no schedule yet.
|
||||
# A later explicit opt-in may add a cadence (and turn on nightly-dispatch.yml with it).
|
||||
# Automated daily nightly builds at 06:30 UTC, plus supervised manual runs by reviewed manual actors.
|
||||
on:
|
||||
schedule:
|
||||
- cron: '30 6 * * *'
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
@@ -27,7 +28,7 @@ jobs:
|
||||
tooling-revision: main
|
||||
app-name: vectorcraft
|
||||
manual-actors: '["bflatastic","dylanmtaylor","echelon","FredApps","skylartaylor"]'
|
||||
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
|
||||
craft-fonts-ref: 16bbfc3d451fad51971ca3f2a28c1e69e279b67c
|
||||
# One producer run builds every listed platform for one all-or-nothing release. The pin is the
|
||||
# craft-common-actions main commit that merged the exact-analysis admission (#371, after #370,
|
||||
# #369 and #364).
|
||||
|
||||
@@ -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,7 +43,8 @@ jobs:
|
||||
app-name: vectorcraft
|
||||
app-title: VectorCraft
|
||||
macos-runner: macos-15
|
||||
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
|
||||
macos-split-build: true
|
||||
craft-fonts-ref: 16bbfc3d451fad51971ca3f2a28c1e69e279b67c
|
||||
web-craft-fonts: true
|
||||
version: ${{ inputs.version }}
|
||||
contributors-artifact: ${{ needs.credits.outputs.artifact-name }}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -69,7 +69,7 @@ VectorCraft is an open-source, Rust-native vector illustration app (Illustrator-
|
||||
- `crates/*`: engine, tools, format, svg, pdf, text, theme, mcp and the egui frontend `crates/ui-egui`; `apps/{vectorcraft, vectorcraft-cli, vectorcraft-web}`; `xtask`. `cargo xtask layers` enforces the layering: nothing below L6 depends on egui, eframe, winit or rfd.
|
||||
- Commands live in `crates/engine/src/cmd/*` (id, label, menu path, shortcut, params doc, `enabled`, `run`); UI-only commands in `crates/ui-egui/src/menus.rs` (`UI_COMMANDS`). Colours come from `theme::Tokens`.
|
||||
- Control channel methods: `crates/ui-egui/src/control.rs`. MCP: `docs/mcp.md`.
|
||||
- `ROADMAP.md` (stage, numbers, progress log), `docs/gaps.md` (ranked work list), `docs/target-app-parity.md`, `docs/roadmap.md` and the parity checklists in `docs/` track progress. Feature PRs update the rows they touch.
|
||||
- `ROADMAP.md` (stage, numbers, progress log), `docs/gaps.md` (ranked work list), `docs/target-app-parity.md`, `docs/roadmap.md` and the parity checklists in `docs/` track progress. Feature PRs update the rows they touch. Headless ([RFC-0052](https://github.com/storytold/craft-contrib/blob/main/rfcs/0052-headless-reach.md)): `docs/ui-parity.md` has a Headless column on the Summary table and every behaviour table; every row is `unknown` until checked (350 unknown today). A checked row may be marked `no (<reach>)` or `partial (<reach>)` with `window`, `os` or `engine-gap` (a `partial` row's notes say which part works); `yes` only when the row cites a registry command id (LightCraft's `cmd:<id>` is the model). Some rows already cite ids such as `toolbar.show`, but none is a registry command id yet, and desktop-only ids (including `crates/mcp/src/ui_catalog.rs`) do not count. Update the summary counts when you mark rows.
|
||||
- Build, test, fonts, localisation, cursors and robustness details: [`docs/development.md`](docs/development.md). Releases: [`docs/releasing.md`](docs/releasing.md).
|
||||
|
||||
### Checks
|
||||
|
||||
Generated
+191
-179
File diff suppressed because it is too large
Load Diff
+52
-50
@@ -4,55 +4,57 @@ members = ["crates/*", "apps/*", "xtask"]
|
||||
default-members = ["crates/*", "apps/vectorcraft", "apps/vectorcraft-cli", "xtask"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.25.0"
|
||||
version = "0.25.1"
|
||||
edition = "2024"
|
||||
license = "MIT OR Apache-2.0"
|
||||
rust-version = "1.95"
|
||||
|
||||
[workspace.dependencies]
|
||||
craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735", default-features = false, features = ["interpret", "write"] }
|
||||
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6", default-features = false, features = ["interpret", "write"] }
|
||||
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
# 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 = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
# 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 = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
# `.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 = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6", 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 = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
# 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 = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
# 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 = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6", features = ["tree"] }
|
||||
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
# 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 = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
# 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 = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
# 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 = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6", default-features = false, features = ["read", "write"] }
|
||||
craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
# 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 = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
# 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 = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
# Nightly profile isolation, launch protocol, and security fence.
|
||||
craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
# internal
|
||||
vectorcraft-geom = { path = "crates/geom" }
|
||||
vectorcraft-color = { path = "crates/color" }
|
||||
@@ -192,22 +194,22 @@ lto = "thin"
|
||||
codegen-units = 1
|
||||
|
||||
[patch.crates-io]
|
||||
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
krilla = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
emath = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
epaint = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
egui = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
eframe = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" }
|
||||
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
krilla = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "861d60a65c50850e995bbb3dcee7c1f3b06815f6" }
|
||||
emath = { git = "https://github.com/storytold/egui.git", rev = "861d60a65c50850e995bbb3dcee7c1f3b06815f6" }
|
||||
epaint = { git = "https://github.com/storytold/egui.git", rev = "861d60a65c50850e995bbb3dcee7c1f3b06815f6" }
|
||||
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "861d60a65c50850e995bbb3dcee7c1f3b06815f6" }
|
||||
egui = { git = "https://github.com/storytold/egui.git", rev = "861d60a65c50850e995bbb3dcee7c1f3b06815f6" }
|
||||
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "861d60a65c50850e995bbb3dcee7c1f3b06815f6" }
|
||||
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "861d60a65c50850e995bbb3dcee7c1f3b06815f6" }
|
||||
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "861d60a65c50850e995bbb3dcee7c1f3b06815f6" }
|
||||
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "861d60a65c50850e995bbb3dcee7c1f3b06815f6" }
|
||||
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "861d60a65c50850e995bbb3dcee7c1f3b06815f6" }
|
||||
eframe = { git = "https://github.com/storytold/egui.git", rev = "861d60a65c50850e995bbb3dcee7c1f3b06815f6" }
|
||||
winit = { git = "https://github.com/storytold/winit.git", rev = "0dfcec0eb62fda5904137a63a6dd0c3d83295f45" }
|
||||
|
||||
@@ -233,8 +233,8 @@ VectorCraft is under active development. [**ROADMAP.md**](ROADMAP.md) has the st
|
||||
and what's next; [`docs/target-app-parity.md`](docs/target-app-parity.md) the full parity assessment and
|
||||
[`docs/gaps.md`](docs/gaps.md) the ranked list of what's missing.
|
||||
|
||||
**Where we are (2026-10-10): alpha.** About 88% of core menu items, tools, effects and formats exist
|
||||
(92.5% of menu items do something), feature depth is ~75%, and we estimate ~65% ready for real work for a mainstream illustrator (~62% across all tracked features): everyday
|
||||
**Where we are (2026-11-30): alpha.** About 96% of core menu items, tools, effects and formats exist
|
||||
(99.9% of menu items do something), feature depth is ~79%, and we estimate ~65% ready for real work for a mainstream illustrator (~67% across all tracked features): everyday
|
||||
vector illustration is close to usable: drawing and path tools,
|
||||
Pathfinder and Shape Builder, paint, gradients, appearance and transparency, type with styles, threading and Hebrew/Arabic bidirectional layout, and
|
||||
files (SVG, PDF and PDF-compatible `.ai` with PDF/X, legacy version 7 `.ai` keeping layers, groups and type, EPS, DXF, EMF/WMF, raster formats, PSD out, PSD/PSB opened with their layers and placed as their merged image, JPEG XL in, Print, Package).
|
||||
|
||||
+34
-29
@@ -10,7 +10,7 @@ control channel. This page is the summary; the evidence is in [`docs/target-app-
|
||||
and the work list in [`docs/gaps.md`](docs/gaps.md).
|
||||
|
||||
**Why alpha:** the core workflows exist end to end (drawing and path editing, Pathfinder, paint and appearance,
|
||||
type, SVG/PDF/EPS, print, export) and feature depth is ~75%, but a professional can't yet switch: Illustrator's
|
||||
type, SVG/PDF/EPS, print, export) and feature depth is ~79%, but a professional can't yet switch: Illustrator's
|
||||
own `.ai` files open with a wrong layer structure in real cases and are saved back with an editing copy that
|
||||
keeps live effects only on paths, compound paths and groups that qualify (at most a fill and a stroke, a non-zero fill rule when filled, no large canvas) and whose appearance and effects the art-style writer supports (see [docs/file-format-parity.md](docs/file-format-parity.md)), and writes live objects as their art, the interaction details have never been checked side by side, and some machines fail to start the
|
||||
app. Beta needs those closed (the beta list in [gaps.md](docs/gaps.md)). It passes the core-workflow
|
||||
@@ -24,8 +24,8 @@ blocking it ([Alpha gate](docs/roadmap.md#alpha-gate)).
|
||||
|
||||
| | Value | Kind |
|
||||
|---|---|---|
|
||||
| **Feature breadth** (Illustrator's menu items, tools, effects, formats exist) | **~88%** | measured in part: menu items 717/719 wired (99.7%), tools 89/92, Illustrator effects 46/50, Photoshop effects 57/57, 3D 4/4 (initial types, no materials) |
|
||||
| **Feature depth** (weighted by use, scored by behaviour) | **~75%** | estimated |
|
||||
| **Feature breadth** (Illustrator's menu items, tools, effects, formats exist) | **~96%** | measured in part: menu items 815/816 wired (99.9%), tools 91/92, Illustrator effects 50/50, Photoshop effects 57/57, 3D 4/4 plus 3 Classic (initial types, graphics on the Materials page (#6960), no base materials) |
|
||||
| **Feature depth** (weighted by use, scored by behaviour) | **~79%** | estimated |
|
||||
| **To beta** | **~170–270 h** one agent · ~50–80 h with 4–6 agents | estimated |
|
||||
| **To full parity** | **~360–590 h** one agent · ~95–165 h with 4–6 agents | estimated |
|
||||
|
||||
@@ -33,9 +33,9 @@ blocking it ([Alpha gate](docs/roadmap.md#alpha-gate)).
|
||||
|
||||
| Audience | Ready % | Opus 5.5 agent hours to ~95% (one agent) | With 4–6 agents | Work that dominates |
|
||||
|---|---:|---:|---:|---|
|
||||
| **Full Illustrator** (ready for real work; decides the stage) | **~62%** (57–67%) | **~340–560 h** | ~95–160 h | the mainstream work below, plus 3D (50–85 h), raster effects (23–39 h), advanced type (20–28 h), generative AI (30–60 h), localization (50–85 h) and ecosystem |
|
||||
| **Full Illustrator** (ready for real work; decides the stage) | **~67%** (62–72%) | **~340–560 h** | ~95–160 h | the mainstream work below, plus 3D (50–85 h), raster effects (23–39 h), advanced type (20–28 h), generative AI (30–60 h), localization (50–85 h) and ecosystem |
|
||||
| **Mainstream illustrator** | **~65%** (60–70%) | **~230–380 h** | ~65–110 h | the interaction-fidelity pass (60–90 h), hardening and QA (30–50 h), stability (20–35 h), performance budgets (15–25 h), `.ai` exchange (10–20 h), the remaining depth of the everyday areas |
|
||||
| **Essentials user** | **~75%** (70–80%) | **~60–105 h** | ~25–45 h | launch and stability on Windows (20–35 h), in-app help and onboarding (8–15 h), basic QA (10–15 h), Shape Builder depth (4–8 h; #937's reproduced case is fixed, unconfirmed on the reporter's file), UI polish |
|
||||
| **Essentials user** | **~77%** (72–82%) | **~60–105 h** | ~25–45 h | launch and stability on Windows (20–35 h), the Windows print crashes (#8021, #9261), help articles and onboarding (8–15 h), basic QA (10–15 h), Shape Builder depth (4–8 h; #937's reproduced case is fixed, unconfirmed on the reporter's file), UI polish |
|
||||
|
||||
Hours are Opus 5.5 agent wall-clock hours, calibrated from this repo's merged-PR timestamps (e.g. 0.7–1.2 h per
|
||||
Photoshop-style filter, ~0.8 h per medium feature); see [calibration](docs/target-app-parity.md#calibration).
|
||||
@@ -46,15 +46,15 @@ everything is measured from our code against Illustrator's public documentation.
|
||||
|
||||
| Dimension | % | One agent (h) | Doc |
|
||||
|---|---:|---:|---|
|
||||
| Features (depth) | 75% | 220–360 | [target-app-parity.md](docs/target-app-parity.md) |
|
||||
| UI/UX fidelity | 55% | 70–110 | [ui-parity.md](docs/ui-parity.md) |
|
||||
| Features (depth) | 79% | 220–360 | [target-app-parity.md](docs/target-app-parity.md) |
|
||||
| UI/UX fidelity | 60% | 70–110 | [ui-parity.md](docs/ui-parity.md) |
|
||||
| File formats | 75% | 15–30 | [file-format-parity.md](docs/file-format-parity.md) |
|
||||
| Hardware (GPU, pen, touch, displays) | 35% | 25–45 | [hardware-parity.md](docs/hardware-parity.md) |
|
||||
| Localization (12 key languages) | 74% (measured) | 50–85 | [localization-parity.md](docs/localization-parity.md) |
|
||||
| Hardware (GPU, pen, touch, displays) | 45% | 25–45 | [hardware-parity.md](docs/hardware-parity.md) |
|
||||
| Localization (12 key languages) | 87% (measured) | 50–85 | [localization-parity.md](docs/localization-parity.md) |
|
||||
| Performance | ~60% | 15–25 | [gaps.md › G15](docs/gaps.md#g15-performance-budgets-and-a-gpu-renderer) |
|
||||
| Stability | ~60% | 30–50 | [gaps.md › G10](docs/gaps.md#g10-launch-and-stability-on-real-machines) |
|
||||
| Platforms | 80% | 15–25 | [gaps.md › G8](docs/gaps.md#g8-hardening-at-scale) |
|
||||
| Ecosystem and plug-ins | 15% | 30–60 | [gaps.md › G17](docs/gaps.md#g17-ecosystem-third-party-plug-ins) |
|
||||
| Stability | ~55% | 30–50 | [gaps.md › G10](docs/gaps.md#g10-launch-and-stability-on-real-machines) |
|
||||
| Platforms | 82% | 15–25 | [gaps.md › G8](docs/gaps.md#g8-hardening-at-scale) |
|
||||
| Ecosystem and plug-ins | 30% | 30–60 | [gaps.md › G17](docs/gaps.md#g17-ecosystem-third-party-plug-ins) |
|
||||
| AI features (generative) | 0% | 30–60 + owner decision | [gaps.md › G18](docs/gaps.md#g18-generative-ai-features) |
|
||||
| Agent automation | beyond Illustrator | — | [mcp.md](docs/mcp.md) |
|
||||
|
||||
@@ -64,26 +64,26 @@ The dimension hours overlap (feature rows hold some UI, format and AI work), so
|
||||
|
||||
| Area | % | One agent (h) |
|
||||
|---|---:|---:|
|
||||
| Selection, transform & align | 85% | 4–6 |
|
||||
| Drawing tools | 85% | 8–13 |
|
||||
| Path operations, Pathfinder, Shape Builder, Live Paint | 80% | 4–8 |
|
||||
| Selection, transform & align | 86% | 4–6 |
|
||||
| Drawing tools | 88% | 8–13 |
|
||||
| Path operations, Pathfinder, Shape Builder, Live Paint | 85% | 4–8 |
|
||||
| Colour, swatches, gradients, patterns, mesh, recolor | 92% | 4–7 |
|
||||
| Strokes, brushes, width profiles | 88% | 8–15 |
|
||||
| Strokes, brushes, width profiles | 90% | 8–15 |
|
||||
| Appearance, transparency, graphic styles, masks | 97% | 1–2 |
|
||||
| Live vector effects | 85% | 4–8 |
|
||||
| Raster effects (Effect Gallery) — [effects-parity.md](docs/effects-parity.md) | 88% | — |
|
||||
| 3D and Materials | ~25% | 30–55 |
|
||||
| Type core — [type-parity.md](docs/type-parity.md) | 80% | 14–19 |
|
||||
| Type advanced (CJK, spelling, Touch Type) | 50% | 20–28 |
|
||||
| Symbols, blends, envelopes, Repeat, perspective | 88% | 4–7 |
|
||||
| Image Trace, graphs, image tools | 75% | 5–8 |
|
||||
| Layers, artboards, document setup | 78% | 5–8 |
|
||||
| View & navigation | 70% | 9–14 |
|
||||
| Live vector effects | 90% | 4–8 |
|
||||
| Raster effects (Effect Gallery) — [effects-parity.md](docs/effects-parity.md) | 55% | — |
|
||||
| 3D and Materials | ~35% | 30–55 |
|
||||
| Type core — [type-parity.md](docs/type-parity.md) | 83% | 14–19 |
|
||||
| Type advanced (CJK, spelling, Touch Type) | 60% | 20–28 |
|
||||
| Symbols, blends, envelopes, Repeat, perspective | 90% | 4–7 |
|
||||
| Image Trace, graphs, image tools | 78% | 5–8 |
|
||||
| Layers, artboards, document setup | 82% | 5–8 |
|
||||
| View & navigation | 80% | 9–14 |
|
||||
| Guides, grids, smart guides, snapping | 80% | 4–7 |
|
||||
| File formats — [file-format-parity.md](docs/file-format-parity.md) | 75% | 10–20 |
|
||||
| Export for Screens, Asset Export, slices | 85% | 2–4 |
|
||||
| Export for Screens, Asset Export, slices | 87% | 2–4 |
|
||||
| Print, colour management, separations | 80% | 2–4 |
|
||||
| Automation (Actions, Variables, scripting) | 60% | 8–14 |
|
||||
| Automation (Actions, Variables, scripting) | 80% | 8–14 |
|
||||
| UI chrome (panels, Properties, preferences) | 80% | 13–20 |
|
||||
| Libraries, Links, Package | 82% | 2–3 |
|
||||
| Generative AI | 0% | 30–60 |
|
||||
@@ -95,7 +95,7 @@ Weights, evidence and the missing items per area: [target-app-parity.md](docs/ta
|
||||
| Language | Code | Status | Translated |
|
||||
|---|---|---|---:|
|
||||
| English | `en` | full | 100% |
|
||||
| Simplified Chinese | `zh-hans` | partial (messages in English) | 85% |
|
||||
| Simplified Chinese | `zh-hans` | partial (messages translated, #2578) | 85% |
|
||||
| Spanish | `es` | full | 100% |
|
||||
| Hindi | `hi` | catalog complete; machine-assisted draft, native review pending | complete under the scanner |
|
||||
| Gujarati | `gu` | 4,673 contributor-reviewed catalog rows; 11 corrections applied to the 387 additions | menus and dialogs; status/error messages partial |
|
||||
@@ -119,7 +119,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
|
||||
1. **Interaction-fidelity pass** (G1), tool by tool from [ui-parity.md](docs/ui-parity.md): 60–90 h.
|
||||
2. **`.ai` files from real users** (G9): layer structure, guides, speed: 10–20 h.
|
||||
3. **Launch and stability on real machines** (G10): 20–35 h.
|
||||
4. **Core-tool correctness** (G11: the unit preference reverting to points, #864, SVG export units fixed; a Transform effect in a fill's or stroke's own effects, #885; Shape Builder regions and Asset Export borders are fixed): 6–13 h.
|
||||
4. **Core-tool correctness** (G11: the unit preference reverting to points, #864, SVG export units fixed; a Transform effect in a fill's or stroke's own effects (#5221, #885), Shape Builder regions and Asset Export borders are fixed): 6–13 h.
|
||||
5. **Then:** type core and advanced type (G4), the Illustrator 2026 additions (G13), 3D (G3). The Effect Gallery's filter thumbnails and in-dialog preview are in (G2).
|
||||
|
||||
## Progress log
|
||||
@@ -155,16 +155,20 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
|
||||
- 2026-11-19: Quick Pen tool, in the Pen tool's group (Alt+P, Option+P on macOS): clicks or drags add straight lines, continuous arcs or sharp-corner arcs; Alt tapped on its own switches the action, C flips the last arc, `[` and `]` size it, a click on the first point closes the path and a click on an open end continues it (`path.quickPen`, part of #2660). Headline numbers unchanged.
|
||||
- 2026-11-19: Quick Pen length handles: a handle beyond the start and the end of the path being drawn, or of the selected path, makes the line or arc there longer or shorter when dragged; a line keeps its direction and an arc its circle (`path.quickPenLength`, part of #2660). Headline numbers unchanged.
|
||||
- 2026-11-19: Quick Pen toolbar on the canvas while the tool is active: Straight Line, Continuous Arc and Sharp Corner Arc, Flip Arc, and More Options with Hide Toolbar, Pin Toolbar Position and Reset Toolbar Position; it follows the drawing beside the path's last point and its handle drags it (`tool.quickPen.flipArc`, `window.quickPenToolbar`, Window › Quick Pen Toolbar; part of #2660). Headline numbers unchanged.
|
||||
- 2026-11-19: Quick Pen arc size with Ctrl+wheel: over the canvas, a touchpad scroll or a mouse wheel turned with Ctrl makes the arc size 15° larger or smaller per step, as `]` and `[` do, and the view stays put (`tool.quickPen.arcLarger`, `tool.quickPen.arcSmaller`; part of #2660). Headline numbers unchanged.
|
||||
- 2026-11-19: Quick Pen editing: with no path being drawn, a drag on an anchor or a segment of a selected path moves it, a line staying a line and an arc an arc beside a moved corner anchor (at a smooth anchor the handles stay in line and the segments bend to meet); a click selects an anchor, Shift-click adds one, and the canvas context menu's Delete removes the selected anchors (`path.moveAnchors`, `edit.clear`; #2660). Headline numbers unchanged.
|
||||
- 2026-10-31: Pattern libraries: Window › Swatch Libraries › Patterns and the Swatches panel's library menu open Geometric Patterns, a built-in library of eleven pattern swatches (dots, stripes, checks, a grid and shapes); clicking one adds its pattern and swatch to the document, once, and applies it to the active fill or stroke (`swatch.library.add`).
|
||||
- 2026-11-11: Pattern libraries: Patterns › Grit Textures, a second built-in pattern library, holds eight seamless black textures (Fine Grain, Coarse Grit, Sand, Speckle, Stipple, Scratches, Sparse Flecks and Dense Flecks) on tiles of 18 to 36 pt, each drawn the same way every time; marks that reach past a tile edge continue on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged.
|
||||
- 2026-11-11: Pattern libraries: Patterns › Optical Effects, a third built-in pattern library, of VectorCraft's own designs, holds eight black wave, moiré and op-art tiles (Sine Bands, Ripple Lines, Interference Rings, Offset Rings, Warped Checks, Pinched Stripes, Chevron Pulse and Radiating Lenses) of 32 to 48 pt, each drawn the same way every time; each tile is one period of its design, and art that reaches past a tile edge continues on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged.
|
||||
- 2026-11-01: Find Nearest Swatch joins the Color Effects add-on (Object › Plug-ins › Color Effects): for each colour of the selection, the closest swatches of the document, a built-in library or a library or colour book the user loaded, with their CIEDE2000 difference; Apply gives each colour its nearest swatch as one undo step, linking global and spot swatches and adding a library's to the document first, so a process colour becomes the closest spot colour (`addon.color.nearestSwatch`, `addon.color.applyNearestSwatch`, #4923).
|
||||
- 2026-11-29: Randomize Fill Colors joins the Color Effects add-on (Object › Plug-ins › Color Effects): each selected filled path, compound path and live compound shape, inside groups and graph series too, gets a fill color of its own at random: any color, tints of a global or spot swatch, or grays between a minimum and a maximum percent, with a seed that repeats the result and Preview, as one undo step (`addon.color.randomFill`); art on a locked artboard keeps its fill (also when `ids` names it), except new art made there while it is still selected.
|
||||
- 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: Mark Bounds of Each joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): each selected object gets its own inward corner marks, or a rectangle, on its geometric or visual bounds, stroked in the color and weight given, stacked directly above it; clip groups are measured by their clipping path. A dialog with Preview, one undo step (`addon.arrange.markBounds`). A VectorCraft addition: headline numbers unchanged.
|
||||
- 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-29: Group by Row joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects whose visual bounds overlap from top to bottom go into one group for each row (or, by column, from left to right), within their own layer or group and artboard, at the stacking place of their frontmost member; an object alone in its row stays as it is. One undo step, with a previewed dialog (`addon.arrange.groupRows`). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-15: Tangent Circle joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the circles that touch two selected paths or compound paths at a set radius, or three of them (up to eight for three circles), touching each outline without crossing it; circles, rotated ellipses and other paths alike. A dialog that previews every circle or one picked by number, the current paint, one undo step (`addon.pathtools.tangentCircle`). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-17: Add Bounding Rectangle and Add Bounding Circle join the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): a live rectangle on the selection's geometric bounding box, or the smallest live circle that holds its outlines, around the whole selection or around each object, with the current paint and one undo step; the menu items open a dialog with Offset, One per Object and Preview (`addon.pathtools.boundingRectangle`, `addon.pathtools.boundingCircle`, #6966). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-22: Add Inscribed Circle joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the largest live circle inside each selected closed path or compound path, in the area it fills under its fill rule, with the current paint and one undo step (`addon.pathtools.inscribedCircle`, #6966). A VectorCraft addition: headline numbers unchanged.
|
||||
@@ -179,6 +183,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
|
||||
- 2026-11-28: The Three-Point Arc tool joins an arc to the open paths whose ends its ends are placed on, with Join to Open Path Ends (Tool Options, or J while drawing; `shape.threePointArc` `join`), and in direction mode snaps the third point to where the arc carries an open path on, the same way or turned back (Snap Where the Arc Continues a Path, on by default). Headline numbers unchanged.
|
||||
- 2026-11-15: Smooth Bridge joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): two selected circles become one closed outline joined by two concave arcs that touch both circles, so every anchor is smooth; the arcs' radius is a percentage of the smaller circle's radius (1 to 1000%, 100% by default), and Keep Originals adds the outline above the circles instead of replacing them. A dialog with Preview, one undo step (`addon.pathtools.bridge`). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-18: Smooth Bridge also joins three or more circles: every two whose outlines are within Reach (10 pt by default) are joined, the bridges that connect become one shape each, and a circle bridged to no other stays as it is (at most 2000 circles); with Constant Gap the arcs' radius is the smaller circle's radius plus a gap (#8030). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-12-01: Common Tangents and Smooth Bridge are one dialog, Common Tangents… (#10465): Connect tangents joins the two tangents of each kind into one closed shape, and with External, Straight or Curved picks between the tangent lines and Smooth Bridge's curved outline, with Radius, Constant Gap, Reach and Keep Originals; the Smooth Bridge… menu item is gone, and `addon.pathtools.bridge` still runs and opens the dialog with External and Curved (`connect` and `curved` on `addon.pathtools.commonTangents`). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-03: Text Tweaker, the first tool of the Type Tools add-on (Object › Plug-ins › Type Tools): one character attribute (size, baseline shift, rotation, horizontal or vertical scale, tracking, leading or stroke weight) goes letter by letter from a start value to an end value along a straight ramp, an ease, a bow, a spike or at random with a seed, set as the Character panel sets it, while the text stays live; a dialog with Preview, one undo step (`addon.type.textTweaker`, #4924). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-01: Group Overlapping Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects whose visual bounds overlap or touch, chains included, go into one group each, within their own layer or group, at the stacking place of their frontmost member; objects that overlap nothing stay as they are. One undo step, a sweep along x so thousands of loose pieces group quickly (at most 20000 objects). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-10-31: Export for Screens works as the reference app's dialog: Artboards and Assets tabs with a grid or list of thumbnails, Clear Selection and Prefix, Create Sub-folders by Scale or Format (on by default), Export PDFs As Single File (the chosen artboards as one PDF's pages, `pdfs: "single"`) or Multiple Files, iOS and Android rows, format presets in a ☰ menu, and a count of the files the export writes (#4895). About 55 community PRs and fixes landed the same day: Find Font, Replace Font, Outline Stroke and Expand leave hidden and locked art alone (with a warning); DXF export writes LINE and ELLIPSE entities and outlines only the strokes a CAD line can't draw; Blob Brush Angle and Roundness; Shift-constrained Perspective Selection; Grid Repeat Options Preview; a gradient mesh from a file budgeted at about a million quads; width-profile strokes keep their shape zoomed out; `.ai`/EPS import fidelity (area type, envelopes, transparency in dictionaries, character styles); PDF import finds hyphenated and CMap-suffixed font names; Windows renders follow the process's core affinity; Enter or Escape in a floating panel's field no longer reaches the canvas (#4803); Properties shows Blend Options for any selected blend (#4817); Artwork Cleanup finds doubled type (#4835) and joins stacked lines into one object (Join Point Text, #4826). Headline numbers unchanged.
|
||||
|
||||
@@ -48,3 +48,14 @@ objc2-core-text = { version = "0.3", default-features = false, features = ["std"
|
||||
tempfile = "3"
|
||||
vectorcraft-testkit = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
|
||||
# The files of other crates that this crate compiles or its tests read, for CI's test selection.
|
||||
[package.metadata.craft]
|
||||
reads = [
|
||||
"apps/vectorcraft/src/mac_fonts.rs",
|
||||
"apps/vectorcraft/src/prefs_dir.rs",
|
||||
"apps/vectorcraft/src/profile.rs",
|
||||
"apps/vectorcraft/src/system_fonts.rs",
|
||||
"apps/vectorcraft/src/windows_cores.rs",
|
||||
"crates/plugins/tests/fixtures/desaturate.wasm",
|
||||
]
|
||||
|
||||
@@ -629,6 +629,7 @@ mod tests {
|
||||
|
||||
/// On Windows `busy_cores` gives a number between 0 and the cores.
|
||||
#[cfg(windows)]
|
||||
// test-lint: allow never-run Windows only; CI runs tests on Linux and FreeBSD
|
||||
#[test]
|
||||
fn windows_reads_how_many_cores_are_busy() {
|
||||
let cores = std::thread::available_parallelism().map_or(1, |c| c.get());
|
||||
@@ -639,6 +640,7 @@ mod tests {
|
||||
/// On Windows `rss_mb` gives this process's working set: more than 0 MB and less than
|
||||
/// 10,000 MB.
|
||||
#[cfg(windows)]
|
||||
// test-lint: allow never-run Windows only; CI runs tests on Linux and FreeBSD
|
||||
#[test]
|
||||
fn windows_reads_the_working_set() {
|
||||
let mb = rss_mb().map(|(mb, _)| mb);
|
||||
@@ -654,8 +656,7 @@ mod tests {
|
||||
let held = rss_mb();
|
||||
drop(buffer);
|
||||
let (Some((held, _)), Some((now, peak))) = (held, rss_mb()) else {
|
||||
eprintln!("no memory reading (Linux without `ps`): nothing to check");
|
||||
return;
|
||||
panic!("rss_mb gave no memory reading");
|
||||
};
|
||||
assert!(peak.is_some_and(|peak| peak > held - 16.0), "holding 64 MB: {held:.1} MB, after freeing it: {now:.1} MB, peak {peak:?}");
|
||||
}
|
||||
|
||||
@@ -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 = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6", version = "0.1.0" }
|
||||
|
||||
wasm-bindgen = "0.2"
|
||||
serde_json = { workspace = true }
|
||||
|
||||
@@ -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 }
|
||||
|
||||
+53
-11
@@ -1,4 +1,4 @@
|
||||
#[cfg(all(target_os = "macos", feature = "accessibility", feature = "wgpu"))]
|
||||
#[cfg(feature = "wgpu")]
|
||||
use super::gpu;
|
||||
use super::nightly_session;
|
||||
use super::prefs::{flush, save_tick};
|
||||
@@ -44,7 +44,7 @@ impl eframe::App for App {
|
||||
if let Some(window_frame) = self.window_frame.as_mut() {
|
||||
window_frame();
|
||||
}
|
||||
// The characters Alt + keypad codes typed (#5108).
|
||||
// The keypad digits of Alt + keypad codes leave the frame (#5108).
|
||||
#[cfg(windows)]
|
||||
super::windows_alt_codes::raw_input_hook(raw);
|
||||
// Symbol-font characters a keyboard tool typed (NHM Writer legacy Tamil).
|
||||
@@ -107,7 +107,7 @@ impl eframe::App for App {
|
||||
// Plug-ins still loading end before the launch marker does (the macOS exit below skips
|
||||
// dropping the app).
|
||||
self.app.session.cancel_plugin_loads();
|
||||
end_before_teardown(self.frames);
|
||||
end_before_teardown(self.frames, self.graphics_loss.happened());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -202,16 +202,58 @@ impl App {
|
||||
/// its own class, which AppKit's Touch Bar support was observing it under, and AppKit aborts the
|
||||
/// app as it quits on Macs with a Touch Bar. On a normal quit, only the launch marker is needed
|
||||
/// after the window, so it is ended here as `main` ends it after the window on other platforms.
|
||||
/// On every platform, the process also ends here when the window's graphics device was lost
|
||||
/// (`device_lost`, #6374). A frame the lost device could not present stays acquired, and releasing
|
||||
/// the window's surface as eframe tears it down then panics in wgpu (gfx-rs/wgpu#9277).
|
||||
/// Not while the window is still starting up (`frames` below [`gpu::STARTUP_FRAMES`]): a graphics
|
||||
/// failure then starts the app again on another adapter (#651).
|
||||
#[allow(unused_variables)]
|
||||
fn end_before_teardown(frames: u64) {
|
||||
#[cfg(all(target_os = "macos", feature = "accessibility", feature = "wgpu"))]
|
||||
if frames >= gpu::STARTUP_FRAMES {
|
||||
safe_mode::end_launch();
|
||||
log::info!("quitting");
|
||||
log::logger().flush();
|
||||
std::process::exit(0);
|
||||
fn end_before_teardown(frames: u64, device_lost: bool) {
|
||||
if !ends_before_teardown(frames, device_lost) {
|
||||
return;
|
||||
}
|
||||
if device_lost {
|
||||
log::info!("the graphics device was lost: quitting before the window's graphics are torn down");
|
||||
}
|
||||
// `main` does these after the window, which this exit skips.
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
single_instance::resign();
|
||||
safe_mode::end_launch();
|
||||
log::info!("quitting");
|
||||
log::logger().flush();
|
||||
std::process::exit(0);
|
||||
}
|
||||
|
||||
/// Whether [`end_before_teardown`] ends the process: after the window's start-up, on macOS with
|
||||
/// accessibility, or once the graphics device was lost.
|
||||
#[cfg(feature = "wgpu")]
|
||||
fn ends_before_teardown(frames: u64, device_lost: bool) -> bool {
|
||||
frames >= gpu::STARTUP_FRAMES && (device_lost || cfg!(all(target_os = "macos", feature = "accessibility")))
|
||||
}
|
||||
|
||||
/// Without wgpu there is no device-lost report, and the window is torn down as usual.
|
||||
#[cfg(not(feature = "wgpu"))]
|
||||
fn ends_before_teardown(_frames: u64, _device_lost: bool) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
#[cfg(all(test, feature = "wgpu"))]
|
||||
mod tests {
|
||||
use vectorcraft_ui_egui::graphics::GraphicsLoss;
|
||||
|
||||
use super::*;
|
||||
|
||||
/// A device lost while the app runs ends the process before eframe releases the window's
|
||||
/// surface, on every platform; before the window has started, the start-up restart takes over.
|
||||
#[test]
|
||||
fn a_lost_graphics_device_ends_the_process_before_teardown() {
|
||||
let always = cfg!(all(target_os = "macos", feature = "accessibility"));
|
||||
let (loss, ctx) = (GraphicsLoss::default(), egui::Context::default());
|
||||
assert_eq!(ends_before_teardown(gpu::STARTUP_FRAMES, loss.happened()), always, "no loss: the usual teardown");
|
||||
let (l, c) = (loss.clone(), ctx.clone());
|
||||
std::thread::spawn(move || l.report(&c, "Unknown: Device is lost")).join().unwrap();
|
||||
assert!(loss.take().is_some(), "a frame handles the report");
|
||||
assert!(ends_before_teardown(gpu::STARTUP_FRAMES, loss.happened()), "after a loss the window is not torn down");
|
||||
assert!(!ends_before_teardown(gpu::STARTUP_FRAMES - 1, loss.happened()), "during start-up the adapter restart runs");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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)");
|
||||
}
|
||||
}
|
||||
|
||||
+117
-16
@@ -32,6 +32,12 @@
|
||||
//! that adapter, as the next one in the order would be tried. Each restart leaves out one more
|
||||
//! adapter, so it ends when none is left.
|
||||
//!
|
||||
//! When no adapter is picked at all, because none is left or no graphics backend started (wgpu
|
||||
//! needs Vulkan, OpenGL 3.3 or OpenGL ES 3.0, and the driver of Intel's Ironlake graphics offers
|
||||
//! none of them, so the window's surface failed "for any enabled backend" with no backend listed,
|
||||
//! #2654), Linux and the BSDs start once more on Mesa's software renderer ([`Software`]); after
|
||||
//! that, the error that ends the app says what the graphics driver needs.
|
||||
//!
|
||||
//! An adapter can also hang instead of failing: on a hybrid laptop with High Performance chosen,
|
||||
//! the discrete GPU never put the window's first frame on the screen, with no error and no panic,
|
||||
//! and the app stayed in the background without a window (#964). [`watch_first_frame`] gives the
|
||||
@@ -853,7 +859,7 @@ pub fn watch_first_frame(startup: Arc<Startup>) {
|
||||
// The new app records its own start.
|
||||
startup.ended();
|
||||
skip.push(failed.to_string());
|
||||
match restart(&skip.join(",")) {
|
||||
match restart(&skip.join(","), false) {
|
||||
Ok(()) => std::process::exit(0),
|
||||
Err(e) => {
|
||||
log::error!("starting again failed: {e}");
|
||||
@@ -950,6 +956,94 @@ fn restart_without<'a>(graphics_failed: bool, frames: u64, picked: Option<&'a st
|
||||
picked.filter(|p| graphics_failed && frames < STARTUP_FRAMES && !skip.iter().any(|s| s == p))
|
||||
}
|
||||
|
||||
/// Whether a start whose window no graphics adapter could show may start again on Mesa's software
|
||||
/// renderer, which draws OpenGL on the CPU (llvmpipe).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Software {
|
||||
/// Linux and the BSDs, where Mesa provides OpenGL, and this start isn't on it yet.
|
||||
Possible,
|
||||
/// This start already draws on it: the app started again with [`SOFTWARE_ENV`], or the user
|
||||
/// set `LIBGL_ALWAYS_SOFTWARE`.
|
||||
Tried,
|
||||
/// Windows and macOS, or a start that `WGPU_BACKEND` or `WGPU_ADAPTER_NAME` chooses.
|
||||
Unavailable,
|
||||
}
|
||||
|
||||
impl Software {
|
||||
/// This start's [`Software`], from the platform and the environment.
|
||||
pub fn from_env() -> Self {
|
||||
if cfg!(any(windows, target_os = "macos")) || explicit_choice() {
|
||||
Software::Unavailable
|
||||
} else if software_start() || std::env::var_os("LIBGL_ALWAYS_SOFTWARE").is_some() {
|
||||
Software::Tried
|
||||
} else {
|
||||
Software::Possible
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Set by the app when it starts again on Mesa's software renderer because no graphics adapter
|
||||
/// could show the window (#2654).
|
||||
pub const SOFTWARE_ENV: &str = "VECTORCRAFT_GPU_SOFTWARE";
|
||||
|
||||
/// Whether this start is the one the app made on Mesa's software renderer ([`SOFTWARE_ENV`]).
|
||||
pub fn software_start() -> bool {
|
||||
std::env::var_os(SOFTWARE_ENV).is_some()
|
||||
}
|
||||
|
||||
/// The graphics APIs the window can draw with on this platform, for the error that ends the app
|
||||
/// when no adapter can show it and for the note of a start on Mesa's software renderer.
|
||||
pub const NEEDS: &str = if cfg!(windows) {
|
||||
"Direct3D 12, OpenGL 3.3 or OpenGL ES 3.0"
|
||||
} else if cfg!(target_os = "macos") {
|
||||
"Metal"
|
||||
} else {
|
||||
"Vulkan, OpenGL 3.3 or OpenGL ES 3.0"
|
||||
};
|
||||
|
||||
/// What follows the window's run ([`next`]).
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
enum Next {
|
||||
/// The window closed normally.
|
||||
Done,
|
||||
/// Start again without the adapters in `skip`, on Mesa's software renderer when `software`.
|
||||
Restart { skip: Vec<String>, software: bool },
|
||||
/// End the app with this error.
|
||||
Stop(String),
|
||||
}
|
||||
|
||||
/// What follows the window's run: `why` it failed (`None` when it closed normally), whether the
|
||||
/// graphics failed, the `frames` the UI ran, the adapter `picked`, those left out (`skip`) and
|
||||
/// whether the software renderer is still to try. A failure on an adapter while starting up starts
|
||||
/// again without it. When no adapter was picked, because none can show the window or no graphics
|
||||
/// backend started at all (an old GPU whose driver offers neither Vulkan nor OpenGL 3.3 or OpenGL
|
||||
/// ES 3.0, such as Intel's Ironlake graphics, #2654), Linux and the BSDs start once more on Mesa's
|
||||
/// software renderer, and after that the error says what the window needs.
|
||||
fn next(why: Option<String>, graphics_failed: bool, frames: u64, picked: Option<&str>, mut skip: Vec<String>, software: Software) -> Next {
|
||||
let Some(why) = why else { return Next::Done };
|
||||
if let Some(failed) = restart_without(graphics_failed, frames, picked, &skip) {
|
||||
log::error!("the window failed on graphics adapter {failed} ({why}): starting again without it");
|
||||
skip.push(failed.to_string());
|
||||
return Next::Restart { skip, software: false };
|
||||
}
|
||||
if !graphics_failed {
|
||||
return Next::Stop(why);
|
||||
}
|
||||
if picked.is_some() || frames >= STARTUP_FRAMES {
|
||||
return Next::Stop(format!("{why} ({HELP})"));
|
||||
}
|
||||
match software {
|
||||
Software::Possible => {
|
||||
log::error!("no graphics adapter could show the window ({why}): starting again on Mesa's software renderer, which draws on the CPU");
|
||||
Next::Restart { skip, software: true }
|
||||
}
|
||||
Software::Tried => Next::Stop(format!(
|
||||
"{why}: no graphics adapter could show the window, not even Mesa's software renderer (the graphics driver needs {NEEDS}; {HELP})"
|
||||
)),
|
||||
Software::Unavailable => Next::Stop(format!("{why}: no graphics adapter could show the window (the graphics driver needs {NEEDS}; {HELP})")),
|
||||
}
|
||||
}
|
||||
|
||||
/// After the window's run: `Ok` when it closed normally or the app started again (see the module
|
||||
/// docs), otherwise why it failed. `outcome` is eframe's result, or the message of a panic that
|
||||
/// ended it.
|
||||
@@ -957,28 +1051,35 @@ pub fn finish(outcome: Result<eframe::Result, String>, startup: &Startup) -> Res
|
||||
// Whatever follows, this start didn't crash; a new app records its own start.
|
||||
startup.ended();
|
||||
let (why, graphics_failed) = match outcome {
|
||||
Ok(Ok(())) => return Ok(()),
|
||||
Ok(Err(e @ eframe::Error::Wgpu(_))) => (e.to_string(), true),
|
||||
Ok(Err(e)) => (e.to_string(), false),
|
||||
Err(panic) => (panic, GRAPHICS_PANIC.load(Ordering::Relaxed)),
|
||||
Ok(Ok(())) => (None, false),
|
||||
Ok(Err(e @ eframe::Error::Wgpu(_))) => (Some(e.to_string()), true),
|
||||
Ok(Err(e)) => (Some(e.to_string()), false),
|
||||
Err(panic) => (Some(panic), GRAPHICS_PANIC.load(Ordering::Relaxed)),
|
||||
};
|
||||
let frames = startup.ui.get().map_or(0, egui::Context::cumulative_frame_nr);
|
||||
let mut skip = skipped();
|
||||
let Some(failed) = restart_without(graphics_failed, frames, startup.adapter.get().map(String::as_str), &skip) else {
|
||||
return Err(if graphics_failed { format!("{why} ({HELP})") } else { why });
|
||||
};
|
||||
log::error!("the window failed on graphics adapter {failed} ({why}): starting again without it");
|
||||
skip.push(failed.to_string());
|
||||
restart(&skip.join(",")).map_err(|e| format!("{why}; starting again failed: {e}"))
|
||||
let picked = startup.adapter.get().map(String::as_str);
|
||||
match next(why.clone(), graphics_failed, frames, picked, skipped(), Software::from_env()) {
|
||||
Next::Done => Ok(()),
|
||||
Next::Stop(e) => Err(e),
|
||||
Next::Restart { skip, software } => {
|
||||
let why = why.unwrap_or_default();
|
||||
restart(&skip.join(","), software).map_err(|e| format!("{why}; starting again failed: {e}"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Start the app again with the same arguments, leaving out the adapters in `skip`. On Unix the
|
||||
/// new app replaces this process (same process id, so an AppImage keeps its files mounted), and
|
||||
/// this returns only on failure; on Windows it starts beside this one, which then exits.
|
||||
fn restart(skip: &str) -> std::io::Result<()> {
|
||||
/// Start the app again with the same arguments, leaving out the adapters in `skip`, and on Mesa's
|
||||
/// software renderer when `software` (`LIBGL_ALWAYS_SOFTWARE`, with [`SOFTWARE_ENV`] so it is
|
||||
/// tried once). On Unix the new app replaces this process (same process id, so an AppImage keeps
|
||||
/// its files mounted), and this returns only on failure; on Windows it starts beside this one,
|
||||
/// which then exits.
|
||||
fn restart(skip: &str, software: bool) -> std::io::Result<()> {
|
||||
log::logger().flush();
|
||||
let mut c = std::process::Command::new(std::env::current_exe()?);
|
||||
c.args(std::env::args_os().skip(1)).env(SKIP_ENV, skip);
|
||||
if software {
|
||||
c.env("LIBGL_ALWAYS_SOFTWARE", "1").env(SOFTWARE_ENV, "1");
|
||||
}
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::process::CommandExt as _;
|
||||
|
||||
@@ -553,10 +553,9 @@ fn the_saved_engine_preference_is_found() {
|
||||
let saved = prefs.to_json();
|
||||
assert_eq!(power_preference(saved.get("gpuPreference").and_then(serde_json::Value::as_str), None), power);
|
||||
}
|
||||
// Every choice Preferences offer means something here.
|
||||
for (value, _) in vectorcraft_engine::cmd::prefscmds::GPU_PREFERENCES {
|
||||
assert!(["automatic", "lowPower", "highPerformance"].contains(value), "{value}");
|
||||
}
|
||||
// Preferences offer the three choices read above, and no other.
|
||||
let offered: Vec<&str> = vectorcraft_engine::cmd::prefscmds::GPU_PREFERENCES.iter().map(|(value, _)| *value).collect();
|
||||
assert_eq!(offered, ["automatic", "lowPower", "highPerformance"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -602,15 +601,52 @@ fn only_a_graphics_failure_while_starting_up_restarts_without_the_adapter() {
|
||||
fn a_normal_exit_or_another_failure_does_not_restart() {
|
||||
let startup = Startup::default();
|
||||
assert_eq!(finish(Ok(Ok(())), &startup), Ok(()));
|
||||
// No adapter was picked (none can show the window): the error is returned, nothing restarts.
|
||||
let none = eframe::Error::Wgpu(eframe::egui_wgpu::WgpuError::CustomNativeAdapterSelectionError("no graphics adapter can show the window".into()));
|
||||
assert_eq!(
|
||||
finish(Ok(Err(none)), &startup),
|
||||
Err(format!("WGPU error: Adapter selection failed: no graphics adapter can show the window ({HELP})"))
|
||||
);
|
||||
let _ = startup.adapter.set("Vulkan:1002:164e".into());
|
||||
GRAPHICS_PANIC.store(false, Ordering::Relaxed);
|
||||
assert_eq!(finish(Err("a bug".into()), &startup), Err("a bug".into()));
|
||||
// The same, decided without starting anything.
|
||||
let amd = Some("Vulkan:1002:164e");
|
||||
for software in [Software::Possible, Software::Tried, Software::Unavailable] {
|
||||
assert_eq!(next(None, false, 0, amd, vec![], software), Next::Done);
|
||||
assert_eq!(next(Some("a bug".into()), false, 0, None, vec![], software), Next::Stop("a bug".into()));
|
||||
// A failure after start-up, or on an adapter already left out, is not the start's.
|
||||
assert_eq!(next(Some("lost".into()), true, STARTUP_FRAMES, amd, vec![], software), Next::Stop(format!("lost ({HELP})")));
|
||||
let skip = vec!["Vulkan:1002:164e".to_string()];
|
||||
assert_eq!(next(Some("lost".into()), true, 0, amd, skip, software), Next::Stop(format!("lost ({HELP})")));
|
||||
}
|
||||
// An adapter that failed while starting up is left out, never with the software renderer.
|
||||
assert_eq!(
|
||||
next(Some("lost".into()), true, 0, amd, vec!["Gl:8086:0046".into()], Software::Possible),
|
||||
Next::Restart { skip: vec!["Gl:8086:0046".into(), "Vulkan:1002:164e".into()], software: false }
|
||||
);
|
||||
}
|
||||
|
||||
/// #2654: on a ThinkPad T510 with Intel's Ironlake graphics, whose driver offers neither Vulkan
|
||||
/// nor OpenGL 3.3 or OpenGL ES 3.0, wgpu started no backend, so the window's surface failed before
|
||||
/// any adapter was listed and the app ended; started with `LIBGL_ALWAYS_SOFTWARE=1`, it ran on
|
||||
/// llvmpipe. With no adapter picked, Linux starts once more on Mesa's software renderer, keeping
|
||||
/// the adapters already left out, and the error after that says what the driver needs.
|
||||
#[test]
|
||||
fn a_start_no_adapter_can_show_tries_the_software_renderer_once() {
|
||||
let surface = "WGPU error: Failed to create surface for any enabled backend: {}";
|
||||
let skip = vec!["Vulkan:8086:0046".to_string()];
|
||||
assert_eq!(next(Some(surface.into()), true, 0, None, skip.clone(), Software::Possible), Next::Restart { skip: skip.clone(), software: true });
|
||||
// No adapter left that can show the window, after restarts without each.
|
||||
let none = "WGPU error: Adapter selection failed: no graphics adapter can show the window";
|
||||
assert_eq!(next(Some(none.into()), true, 0, None, skip.clone(), Software::Possible), Next::Restart { skip: skip.clone(), software: true });
|
||||
// Already on the software renderer: the app ends, saying what the window needs.
|
||||
let Next::Stop(tried) = next(Some(surface.into()), true, 0, None, skip.clone(), Software::Tried) else {
|
||||
panic!("a start already on the software renderer starts again")
|
||||
};
|
||||
assert!(tried.starts_with(surface), "{tried}");
|
||||
assert!(tried.contains("not even Mesa's software renderer") && tried.contains(NEEDS) && tried.contains(HELP), "{tried}");
|
||||
// Windows, macOS or a backend the user chose: no software renderer to start on.
|
||||
let Next::Stop(unavailable) = next(Some(surface.into()), true, 0, None, skip, Software::Unavailable) else {
|
||||
panic!("a start without the software renderer starts again")
|
||||
};
|
||||
assert!(unavailable.contains(NEEDS) && unavailable.contains(HELP) && !unavailable.contains("Mesa"), "{unavailable}");
|
||||
// A failure outside the graphics never starts again.
|
||||
assert_eq!(next(Some("a bug".into()), false, 0, None, vec![], Software::Possible), Next::Stop("a bug".into()));
|
||||
}
|
||||
|
||||
/// A log folder of its own for each test.
|
||||
|
||||
@@ -3,8 +3,8 @@
|
||||
//! mark for [`STALL`] while inside a stage of its frame, the thread writes what the app knows to the
|
||||
//! log (`logs/vectorcraft.log`) and to `logs/hang-report-<process id>.txt`: the stage, a clipboard
|
||||
//! call in progress, the last commands, the last frames' times, the platform, the window system, the
|
||||
//! graphics processor and the present mode the app asked for, and how long the session has run with
|
||||
//! how many documents open. The process holds a lock on the file until the interface thread answers
|
||||
//! graphics processor, its driver when known, and the present mode the app asked for, and how long
|
||||
//! the session has run with how many documents open. The process holds a lock on the file until the interface thread answers
|
||||
//! again; then the log says after how long and the file is removed. A file nobody holds at a later
|
||||
//! launch was left by a session that was closed while it did not answer, and a locked one belongs to
|
||||
//! another instance that is stalled now and is left alone. That launch writes the report to the log,
|
||||
@@ -113,6 +113,8 @@ pub struct Facts {
|
||||
pub flatpak: bool,
|
||||
/// The graphics processor the window draws with.
|
||||
pub graphics: Option<String>,
|
||||
/// The active graphics driver's identity, when the backend reports it.
|
||||
graphics_driver: Option<String>,
|
||||
/// The present mode and frame queue the app asked the window surface for.
|
||||
pub surface: String,
|
||||
}
|
||||
@@ -128,14 +130,29 @@ impl Facts {
|
||||
session_type: value("XDG_SESSION_TYPE"),
|
||||
flatpak: flatpak_info || env("FLATPAK_ID").is_some_and(|v| !v.is_empty()),
|
||||
graphics,
|
||||
graphics_driver: None,
|
||||
surface,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "wgpu", test))]
|
||||
pub fn with_graphics_driver(mut self, driver: &str, info: &str) -> Facts {
|
||||
// D3D12 reports 0.0.0.0 when the driver version could not be read.
|
||||
let mut fields = [driver, info].map(clean).into_iter().filter(|value| !value.is_empty() && value != "0.0.0.0");
|
||||
self.graphics_driver = fields.next().map(|mut detail| {
|
||||
if let Some(info) = fields.next().filter(|info| info != &detail) {
|
||||
detail.push_str(" / ");
|
||||
detail.push_str(&info);
|
||||
}
|
||||
detail
|
||||
});
|
||||
self
|
||||
}
|
||||
|
||||
/// The facts as report lines.
|
||||
pub fn lines(&self) -> String {
|
||||
let or_unknown = |v: &Option<String>| v.clone().unwrap_or_else(|| "unknown".to_string());
|
||||
format!(
|
||||
let mut lines = format!(
|
||||
"VectorCraft {} on {} {}\nWindow system: {}; desktop: {}; session type: {}; Flatpak: {}\nGraphics: {}; {}\n",
|
||||
vectorcraft_ui_egui::os_window::version(),
|
||||
std::env::consts::OS,
|
||||
@@ -146,7 +163,13 @@ impl Facts {
|
||||
if self.flatpak { "yes" } else { "no" },
|
||||
or_unknown(&self.graphics),
|
||||
self.surface,
|
||||
)
|
||||
);
|
||||
if let Some(driver) = &self.graphics_driver {
|
||||
lines.push_str("Graphics driver: ");
|
||||
lines.push_str(driver);
|
||||
lines.push('\n');
|
||||
}
|
||||
lines
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -279,3 +279,22 @@ fn troubleshooting_info_holds_both_sessions_reports() {
|
||||
assert!(text.contains("(it was closed while it did not answer):\nVectorCraft hang report, last session\n"));
|
||||
assert!(text.contains("Recent commands, oldest first: none"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn troubleshooting_info_distinguishes_drivers_on_the_same_adapter() {
|
||||
let mut shared = shared(None);
|
||||
let beacon = Beacon::new();
|
||||
for (driver, info, expected) in [
|
||||
(" 32.0.16.1088 ", "", Some("32.0.16.1088")),
|
||||
("32.0.16.2124", "", Some("32.0.16.2124")),
|
||||
("Mesa\nRADV", "Mesa 25.2", Some("MesaRADV / Mesa 25.2")),
|
||||
("Mesa", "Mesa", Some("Mesa")),
|
||||
("0.0.0.0", "", None),
|
||||
("", "", None),
|
||||
] {
|
||||
shared.facts = facts().with_graphics_driver(driver, info);
|
||||
let text = troubleshooting(&shared, &beacon, UNIX_EPOCH);
|
||||
assert!(text.contains("Graphics: Test GPU"), "the adapter description is still in the report");
|
||||
assert_eq!(text.lines().find_map(|line| line.strip_prefix("Graphics driver: ")), expected);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -188,7 +188,7 @@ pub(crate) fn services(window: Parent) -> Services {
|
||||
check_application: Some(Box::new(|p| check_app(std::path::Path::new(p)))),
|
||||
open_in_application: Some(Box::new(open_in_application)),
|
||||
// File → Print: the system's printers and print queue.
|
||||
print: Some(Box::new(printing::SystemPrint)),
|
||||
print: Some(Box::new(printing::SystemPrint::default())),
|
||||
// The tablet driver's Wintab context, which reads an airbrush pen's finger wheel, opens
|
||||
// only while the active tool uses the wheel.
|
||||
#[cfg(all(windows, not(target_vendor = "win7")))]
|
||||
|
||||
@@ -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"]));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -99,6 +99,7 @@ mod tests {
|
||||
}
|
||||
|
||||
/// A layer without a color space is tagged sRGB once; the second call leaves it as it is.
|
||||
// test-lint: allow never-run macOS only; CI runs tests on Linux and FreeBSD
|
||||
#[test]
|
||||
fn an_untagged_layer_becomes_srgb() {
|
||||
let layer = CAMetalLayer::new();
|
||||
@@ -110,6 +111,7 @@ mod tests {
|
||||
}
|
||||
|
||||
/// A layer with a color space of its own keeps it.
|
||||
// test-lint: allow never-run macOS only; CI runs tests on Linux and FreeBSD
|
||||
#[test]
|
||||
fn a_layer_with_a_color_space_keeps_it() {
|
||||
let layer = CAMetalLayer::new();
|
||||
@@ -121,6 +123,7 @@ mod tests {
|
||||
|
||||
/// The Metal layer is found as the view's layer or as one of its sublayers, and only Metal
|
||||
/// layers are returned.
|
||||
// test-lint: allow never-run macOS only; CI runs tests on Linux and FreeBSD
|
||||
#[test]
|
||||
fn metal_layers_are_found_under_the_view_layer() {
|
||||
let metal = CAMetalLayer::new();
|
||||
|
||||
@@ -52,6 +52,7 @@ mod tests {
|
||||
use objc2_core_text::{CTFontManagerRegisterFontsForURL, CTFontManagerScope, CTFontManagerUnregisterFontsForURL};
|
||||
|
||||
/// CoreText lists the installed fonts, by their files' full paths.
|
||||
// test-lint: allow never-run macOS only; CI runs tests on Linux and FreeBSD
|
||||
#[test]
|
||||
fn coretext_lists_the_installed_font_files() {
|
||||
let files = super::font_files();
|
||||
@@ -61,6 +62,7 @@ mod tests {
|
||||
|
||||
/// A font registered with CoreText from another folder, as apps and font managers register
|
||||
/// fonts, is listed while it is registered.
|
||||
// test-lint: allow never-run macOS only; CI runs tests on Linux and FreeBSD
|
||||
#[test]
|
||||
fn fonts_registered_from_other_folders_are_listed() {
|
||||
let dir = tempfile::Builder::new().prefix("vectorcraft-mac-fonts-").tempdir().unwrap();
|
||||
|
||||
+136
-62
@@ -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.
|
||||
@@ -359,21 +396,48 @@ fn read_command_line(
|
||||
/// Whether the window opens through XWayland, for Linux Display Server `pref` (`main`).
|
||||
#[cfg(target_os = "linux")]
|
||||
fn opens_through_xwayland(pref: Option<&str>) -> bool {
|
||||
if !xwayland::wanted(pref, |name| std::env::var_os(name), xwayland::pen_attached) {
|
||||
use xwayland::Choice;
|
||||
let choice = xwayland::choose(pref, |name| std::env::var_os(name), xwayland::pen_attached);
|
||||
// On native Wayland winit 0.30 receives no pen input, so the log says why the window stays there.
|
||||
match &choice {
|
||||
Choice::NotWayland | Choice::Chosen | Choice::Pen(_) => {}
|
||||
Choice::NoXDisplay { x11: true } => {
|
||||
log::warn!("Linux Display Server is X11, but there is no X display (DISPLAY is unset): opening the window on Wayland")
|
||||
}
|
||||
Choice::NoXDisplay { x11: false } => log::info!(
|
||||
"opening the window on Wayland, where a pen does not reach it: there is no X display (DISPLAY is unset) to open it through XWayland"
|
||||
),
|
||||
Choice::NativeWayland => log::info!("VECTORCRAFT_NATIVE_WAYLAND is set: opening the window on Wayland, where a pen does not reach it"),
|
||||
Choice::NoPen => log::info!("no pen in /proc/bus/input/devices: opening the window on Wayland"),
|
||||
Choice::NoDeviceList(e) => log::warn!("can't look for a pen ({e}): opening the window on Wayland, where a pen does not reach it"),
|
||||
}
|
||||
if !choice.xwayland() {
|
||||
return false;
|
||||
}
|
||||
if !xwayland::x11_libraries_found() {
|
||||
log::warn!("Linux Display Server is X11, but the X11 libraries aren't all installed: opening the window on Wayland");
|
||||
if let Choice::Pen(name) = &choice {
|
||||
log::warn!(
|
||||
"pen found ({name}), but the X11 libraries aren't all installed: opening the window on Wayland, where the pen does not reach it"
|
||||
);
|
||||
} else {
|
||||
log::warn!("Linux Display Server is X11, but the X11 libraries aren't all installed: opening the window on Wayland");
|
||||
}
|
||||
return false;
|
||||
}
|
||||
if pref != Some("x11") {
|
||||
log::info!("pen found: opening the window through XWayland, where the pen works (VECTORCRAFT_NATIVE_WAYLAND=1 keeps Wayland)");
|
||||
if let Choice::Pen(name) = &choice {
|
||||
log::info!("pen found ({name}): opening the window through XWayland, where the pen works (VECTORCRAFT_NATIVE_WAYLAND=1 keeps Wayland)");
|
||||
} else {
|
||||
log::info!("opening the window through XWayland (Preferences › Performance › Linux Display Server)");
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// The docking runtime needs the backend the desktop window is opened on.
|
||||
fn desktop_shell_info(detected: Backend, forced_to_x11: bool) -> ShellInfo {
|
||||
let backend = if forced_to_x11 { Backend::X11 } else { detected };
|
||||
ShellInfo::current().backend(backend)
|
||||
}
|
||||
|
||||
/// The nightly channel this build is, as a string for the log.
|
||||
fn channel_name() -> &'static str {
|
||||
match build_flavor::COMPILED {
|
||||
@@ -384,58 +448,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 +506,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 +573,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)]
|
||||
@@ -670,10 +724,10 @@ fn main() -> std::process::ExitCode {
|
||||
// A window forced onto XWayland runs on X11, whose window manager draws the frame: the
|
||||
// framework decides the frame for that backend, from the platform, `VECTORCRAFT_TITLEBAR` and
|
||||
// Preferences › User Interface › System Title Bar.
|
||||
let shell_info = if forced_to_x11 { ShellInfo::current().backend(Backend::X11) } else { ShellInfo::current() };
|
||||
let shell_info = desktop_shell_info(Backend::from_env(), forced_to_x11);
|
||||
// On Wayland with no cursor theme, the system pointer stays and no tool cursor is painted
|
||||
// beside it (#2450, #5311).
|
||||
let wayland = !forced_to_x11 && Backend::from_env() == Backend::Wayland;
|
||||
let wayland = shell_info.backend == Backend::Wayland;
|
||||
let caps = cursor_theme::shell_caps(shell_info.caps, wayland, cursor_theme::theme_missing);
|
||||
let shell_info = shell_info.caps(caps);
|
||||
let titlebar_pref =
|
||||
@@ -695,14 +749,14 @@ fn main() -> std::process::ExitCode {
|
||||
// With Windows Ink, winit reports a pen as a touch and drops its barrel button and which end
|
||||
// is down; the message hook notes each pointer contact and whether it starts with the barrel
|
||||
// button held, and writes the pen's end into the pen feed (`windows_stylus`). It also notes the
|
||||
// characters Alt + keypad codes type (`windows_alt_codes`).
|
||||
// keypad digits of Alt + keypad codes (`windows_alt_codes`).
|
||||
#[cfg(windows)]
|
||||
let options = {
|
||||
use winit::platform::windows::EventLoopBuilderExtWindows as _;
|
||||
let mut options = options;
|
||||
options.event_loop_builder = Some(Box::new(|builder| {
|
||||
builder.with_msg_hook(|msg| {
|
||||
// Alt + keypad codes (#5108), which winit drops; neither hook consumes a message.
|
||||
// Alt + keypad codes (#5108); neither hook consumes a message.
|
||||
windows_alt_codes::msg_hook(msg);
|
||||
windows_stylus::msg_hook(msg)
|
||||
});
|
||||
@@ -791,9 +845,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 +866,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 +874,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 +900,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.
|
||||
@@ -887,7 +947,13 @@ fn main() -> std::process::ExitCode {
|
||||
let summary = adapter_summary(&rs.adapter.get_info());
|
||||
log::info!("rendering with {summary} (power preference {power:?})");
|
||||
created.created(&cc.egui_ctx);
|
||||
if !gpu::skipped().is_empty() {
|
||||
if gpu::software_start() {
|
||||
// No graphics processor could show the window, so Mesa draws it on the CPU (#2654).
|
||||
app.status(format!(
|
||||
"No graphics processor could show the window, so VectorCraft started again on {summary}, which draws on the CPU and is slower. Showing it on the graphics processor needs a driver with {}",
|
||||
gpu::NEEDS
|
||||
));
|
||||
} else if !gpu::skipped().is_empty() {
|
||||
// A processor chosen in Settings can be the one that can't show the window.
|
||||
if chosen_gpu {
|
||||
app.status(format!(
|
||||
@@ -921,14 +987,22 @@ fn main() -> std::process::ExitCode {
|
||||
.map(|_| (format!("{:?}", requested_surface.present_mode), requested_surface.desired_maximum_frame_latency));
|
||||
#[cfg(not(feature = "wgpu"))]
|
||||
let surface = None;
|
||||
let facts = hang_watch::Facts::new(
|
||||
|name| std::env::var(name).ok(),
|
||||
std::path::Path::new("/.flatpak-info").exists(),
|
||||
hang_watch::window_system(winit_window.as_deref()),
|
||||
app.graphics_adapter.clone(),
|
||||
hang_watch::surface(surface),
|
||||
);
|
||||
#[cfg(feature = "wgpu")]
|
||||
let facts = if let Some(rs) = &cc.wgpu_render_state {
|
||||
let info = rs.adapter.get_info();
|
||||
facts.with_graphics_driver(&info.driver, &info.driver_info)
|
||||
} else {
|
||||
facts
|
||||
};
|
||||
let hang = std::sync::Arc::new(hang_watch::Shared {
|
||||
facts: hang_watch::Facts::new(
|
||||
|name| std::env::var(name).ok(),
|
||||
std::path::Path::new("/.flatpak-info").exists(),
|
||||
hang_watch::window_system(winit_window.as_deref()),
|
||||
app.graphics_adapter.clone(),
|
||||
hang_watch::surface(surface),
|
||||
),
|
||||
facts,
|
||||
started: std::time::Instant::now(),
|
||||
last: std::sync::Mutex::new(None),
|
||||
previous: previous_hang.clone(),
|
||||
|
||||
@@ -94,6 +94,7 @@ mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Files queue until the UI takes them; URLs that aren't files are left out.
|
||||
// test-lint: allow never-run macOS only; CI runs tests on Linux and FreeBSD
|
||||
#[test]
|
||||
fn opened_files_wait_for_the_ui() {
|
||||
let web = NSURL::URLWithString(&NSString::from_str("https://example.com/a.svg")).unwrap();
|
||||
|
||||
@@ -4,7 +4,7 @@ use std::path::PathBuf;
|
||||
use std::sync::{Mutex, PoisonError};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use craft::settings::{LegacyFile, LoadReport, Location, OpenOptions, SettingsStore, SharedSettings};
|
||||
use craft::settings::{LegacyFile, LoadReport, Location, OpenOptions, SectionError, SettingsStore, SharedSettings};
|
||||
use vectorcraft_ui_egui::{AppSettings, from_app, parse_legacy};
|
||||
|
||||
use super::{VectorcraftApp, prefs_dir};
|
||||
@@ -18,6 +18,15 @@ fn legacy_dir() -> Option<PathBuf> {
|
||||
prefs_dir::profile::prefs_dir(true)
|
||||
}
|
||||
|
||||
/// Parses the one `ui.json` slot of a legacy import: its bytes, or why it could not be read.
|
||||
fn parse_legacy_slot(slots: &[Result<Option<&[u8]>, &std::io::Error>]) -> Result<(AppSettings, Vec<SectionError>), String> {
|
||||
match slots.first() {
|
||||
Some(Ok(Some(bytes))) => parse_legacy(bytes),
|
||||
Some(Err(e)) => Err(e.to_string()),
|
||||
_ => Err("the preferences file is missing".to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Where the log files live: `logs` in the preferences folder (see `logging`).
|
||||
pub(crate) fn log_dir() -> Option<PathBuf> {
|
||||
Some(prefs_dir::prefs_dir()?.join("logs"))
|
||||
@@ -34,7 +43,7 @@ pub(crate) fn prefs_enabled() -> bool {
|
||||
pub(crate) fn open_store() -> (SharedSettings<AppSettings>, LoadReport) {
|
||||
let (location, legacy) = match prefs_dir::prefs_dir().filter(|_| prefs_enabled()) {
|
||||
Some(dir) => {
|
||||
let file = |dir: PathBuf| LegacyFile { path: dir.join(LEGACY_FILE), parse: parse_legacy };
|
||||
let file = |dir: PathBuf| LegacyFile { paths: vec![dir.join(LEGACY_FILE)], parse: parse_legacy_slot };
|
||||
let legacy = std::iter::once(file(dir.clone())).chain(legacy_dir().map(file)).collect();
|
||||
(Location::Dir(dir), legacy)
|
||||
}
|
||||
|
||||
@@ -1,11 +1,16 @@
|
||||
//! Desktop printer transport. VectorCraft composes every page and copy before submission;
|
||||
//! craft-print owns discovery and spooling.
|
||||
use std::process::Command;
|
||||
use vectorcraft_ui_egui::print::{PrintJob, PrintService, Printer};
|
||||
use vectorcraft_ui_egui::print::{Paper, Papers, PrintJob, PrintService, Printer};
|
||||
|
||||
mod direct_pdf;
|
||||
|
||||
pub struct SystemPrint;
|
||||
#[derive(Default)]
|
||||
pub struct SystemPrint {
|
||||
/// The paper-size lookup in flight, dropped when its worker answers or disconnects.
|
||||
papers: PaperLookup,
|
||||
}
|
||||
|
||||
impl PrintService for SystemPrint {
|
||||
fn printers(&mut self) -> Vec<Printer> {
|
||||
system::printers()
|
||||
@@ -15,7 +20,7 @@ impl PrintService for SystemPrint {
|
||||
Ok(sent(job.title, job.printer, ¬e))
|
||||
}
|
||||
fn shared_print(&self) -> Option<vectorcraft_ui_egui::print::SharedPrintFn> {
|
||||
Some(std::sync::Arc::new(|job| SystemPrint.print(job)))
|
||||
Some(std::sync::Arc::new(|job| system::print(job).map(|note| sent(job.title, job.printer, ¬e))))
|
||||
}
|
||||
fn turns_landscape(&self) -> bool {
|
||||
// macOS's `lp` doesn't turn a landscape page to the paper: it cuts it off on upright
|
||||
@@ -28,6 +33,46 @@ impl PrintService for SystemPrint {
|
||||
fn setup(&mut self, printer: Option<&str>) -> Result<(), String> {
|
||||
system::setup(printer)
|
||||
}
|
||||
fn scripts_may_print(&self) -> bool {
|
||||
true
|
||||
}
|
||||
fn papers(&mut self, printer: &str, fresh: bool) -> Papers {
|
||||
self.papers.poll(printer, fresh, |printer| installed_papers(&printer))
|
||||
}
|
||||
}
|
||||
|
||||
/// The paper-size lookup in flight: the printer it reads and its worker's channel.
|
||||
#[derive(Default)]
|
||||
struct PaperLookup(Option<(String, std::sync::mpsc::Receiver<Vec<Paper>>)>);
|
||||
|
||||
impl PaperLookup {
|
||||
/// Poll the lookup of `printer`. A new lookup runs `read` on a worker when `fresh` is set, when the one in flight
|
||||
/// reads another printer, or when none is in flight; the earlier one's answer is dropped.
|
||||
fn poll(&mut self, printer: &str, fresh: bool, read: impl FnOnce(String) -> Vec<Paper> + Send + 'static) -> Papers {
|
||||
if fresh || self.0.as_ref().is_none_or(|(p, _)| p != printer) {
|
||||
let (send, receive) = std::sync::mpsc::channel();
|
||||
let name = printer.to_string();
|
||||
let _ = std::thread::Builder::new().name("printer-papers".into()).spawn(move || {
|
||||
let _ = send.send(read(name));
|
||||
});
|
||||
self.0 = Some((printer.to_string(), receive));
|
||||
}
|
||||
let result = match self.0.as_ref().map(|(_, receive)| receive.try_recv()) {
|
||||
Some(Ok(papers)) => Papers::Ready(papers),
|
||||
Some(Err(std::sync::mpsc::TryRecvError::Empty)) => return Papers::Pending,
|
||||
Some(Err(std::sync::mpsc::TryRecvError::Disconnected)) | None => Papers::Ready(Vec::new()),
|
||||
};
|
||||
self.0 = None;
|
||||
result
|
||||
}
|
||||
}
|
||||
|
||||
/// Look up only an installed printer's own name.
|
||||
fn installed_papers(printer: &str) -> Vec<Paper> {
|
||||
if printer.is_empty() || !system::printers().iter().any(|p| p.name == printer) {
|
||||
return Vec::new();
|
||||
}
|
||||
system::papers(printer)
|
||||
}
|
||||
|
||||
/// The status after the job `title` went to `printer` (the default one without a name), with the
|
||||
@@ -40,10 +85,80 @@ fn sent(title: &str, printer: Option<&str>, note: &str) -> String {
|
||||
}
|
||||
|
||||
mod system {
|
||||
use super::{Command, PrintJob, Printer};
|
||||
use super::{Command, Paper, PrintJob, Printer};
|
||||
pub fn printers() -> Vec<Printer> {
|
||||
craft::print::printers().into_iter().map(Printer::from).collect()
|
||||
}
|
||||
/// The paper sizes of an installed printer's driver: its CUPS PPD, or Windows' printer settings.
|
||||
pub fn papers(printer: &str) -> Vec<Paper> {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
// The name goes in as an environment variable, never into the script's text.
|
||||
const SCRIPT: &str = "[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; Add-Type -AssemblyName System.Drawing; $s = New-Object System.Drawing.Printing.PrinterSettings; \
|
||||
$s.PrinterName = $env:VC_PRINTER; foreach ($p in $s.PaperSizes) { \"$($p.RawKind)`t$($p.PaperName)`t$($p.Width)`t$($p.Height)\" }";
|
||||
use std::os::windows::process::CommandExt as _;
|
||||
// CREATE_NO_WINDOW: no console window opens over the app.
|
||||
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
|
||||
let mut command = Command::new("powershell.exe");
|
||||
command.args(["-NoProfile", "-NonInteractive", "-Command", SCRIPT]).env("VC_PRINTER", printer).creation_flags(CREATE_NO_WINDOW);
|
||||
paper_output(&mut command).map(|out| vectorcraft_ui_egui::print::windows_papers(&String::from_utf8_lossy(&out))).unwrap_or_default()
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
use std::io::Read as _;
|
||||
// CUPS queue names never hold `/`, so the name can't leave the PPD folder.
|
||||
if printer.contains(['/', '\\']) || printer.starts_with('.') {
|
||||
return Vec::new();
|
||||
}
|
||||
const PPD_CAP: u64 = 16 << 20;
|
||||
let mut bytes = Vec::new();
|
||||
let read = std::fs::File::open(format!("/etc/cups/ppd/{printer}.ppd")).and_then(|f| f.take(PPD_CAP).read_to_end(&mut bytes));
|
||||
if read.is_err() {
|
||||
return Vec::new();
|
||||
}
|
||||
vectorcraft_ui_egui::print::ppd_papers(&craft::print::ppd_text(&bytes))
|
||||
}
|
||||
}
|
||||
/// Drain output while polling the child, and stop discovery after ten seconds.
|
||||
#[cfg(windows)]
|
||||
fn paper_output(command: &mut Command) -> Option<Vec<u8>> {
|
||||
use std::io::Read as _;
|
||||
use std::process::Stdio;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
const LIMIT: Duration = Duration::from_secs(10);
|
||||
let started = Instant::now();
|
||||
let mut child = command.stdout(Stdio::piped()).stderr(Stdio::null()).spawn().ok()?;
|
||||
let (send, receive) = std::sync::mpsc::channel();
|
||||
let stdout = child.stdout.take();
|
||||
let reader = std::thread::Builder::new().name("printer-paper-output".into()).spawn(move || {
|
||||
let mut bytes = Vec::new();
|
||||
// Retain at most 16 MiB, but drain the rest so the child can finish.
|
||||
let read = stdout.map(|mut out| {
|
||||
out.by_ref().take(16 << 20).read_to_end(&mut bytes)?;
|
||||
std::io::copy(&mut out, &mut std::io::sink())
|
||||
});
|
||||
let _ = send.send(read.and_then(Result::ok).map(|_| bytes));
|
||||
});
|
||||
if reader.is_err() {
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
return None;
|
||||
}
|
||||
loop {
|
||||
match child.try_wait() {
|
||||
Ok(Some(status)) => {
|
||||
return if status.success() { receive.recv_timeout(LIMIT.saturating_sub(started.elapsed())).ok().flatten() } else { None };
|
||||
}
|
||||
Ok(None) if started.elapsed() < LIMIT => std::thread::sleep(Duration::from_millis(25)),
|
||||
_ => {
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
return None;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
pub fn print(job: &PrintJob) -> Result<String, String> {
|
||||
if job.direct_pdf {
|
||||
return super::direct_pdf::print(job);
|
||||
@@ -130,6 +245,55 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod paper_lookup_tests {
|
||||
use super::PaperLookup;
|
||||
use vectorcraft_ui_egui::print::{Paper, Papers};
|
||||
|
||||
fn paper(key: &str) -> Vec<Paper> {
|
||||
vec![Paper { key: key.into(), label: key.into(), width: 100.0, height: 200.0 }]
|
||||
}
|
||||
|
||||
/// Start a fresh lookup of `printer` that answers `key`, and poll it until it answers.
|
||||
fn answer(lookup: &mut PaperLookup, printer: &str, key: &'static str) -> Vec<Paper> {
|
||||
let mut polled = lookup.poll(printer, true, move |_| paper(key));
|
||||
loop {
|
||||
match polled {
|
||||
Papers::Ready(papers) => return papers,
|
||||
Papers::Pending => std::thread::yield_now(),
|
||||
}
|
||||
polled = lookup.poll(printer, false, |_| panic!("polling starts no lookup"));
|
||||
}
|
||||
}
|
||||
|
||||
/// A read that answers `key` once `gate` lets it.
|
||||
fn gated(key: &'static str) -> (std::sync::mpsc::Sender<()>, impl FnOnce(String) -> Vec<Paper> + Send + 'static) {
|
||||
let (open, gate) = std::sync::mpsc::channel::<()>();
|
||||
(open, move |_| {
|
||||
let _ = gate.recv();
|
||||
paper(key)
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fresh_lookup_drops_the_answer_of_an_earlier_one() {
|
||||
let mut lookup = PaperLookup::default();
|
||||
let (open, read) = gated("Old");
|
||||
assert!(matches!(lookup.poll("Card", true, read), Papers::Pending));
|
||||
let (other, read) = gated("Office");
|
||||
assert!(matches!(lookup.poll("Office", true, read), Papers::Pending));
|
||||
let _ = open.send(());
|
||||
let _ = other.send(());
|
||||
// Back on the card printer.
|
||||
assert_eq!(answer(&mut lookup, "Card", "New"), paper("New"));
|
||||
// The dialog opens again on the card printer while a lookup of it is still running.
|
||||
let (open, read) = gated("Stale");
|
||||
assert!(matches!(lookup.poll("Card", true, read), Papers::Pending));
|
||||
let _ = open.send(());
|
||||
assert_eq!(answer(&mut lookup, "Card", "Newer"), paper("Newer"));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod turn_tests {
|
||||
use super::sent;
|
||||
|
||||
@@ -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));
|
||||
|
||||
@@ -41,7 +41,7 @@
|
||||
//! the rotation's range is 0°, and an axis a pen lacks reads nothing.
|
||||
#![cfg_attr(not(target_os = "linux"), allow(dead_code))]
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
use craft::behavior::PointerSample;
|
||||
use craft::ui::runtime::pen::PenSource;
|
||||
@@ -189,6 +189,8 @@ enum Update {
|
||||
struct Pens {
|
||||
devices: HashMap<u16, Device>,
|
||||
last: HashMap<u16, [Option<f32>; 5]>,
|
||||
/// The pens an event has come from, for the log.
|
||||
heard: HashSet<u16>,
|
||||
}
|
||||
|
||||
impl Pens {
|
||||
@@ -197,10 +199,37 @@ impl Pens {
|
||||
/// same id starts without them.
|
||||
fn set_devices(&mut self, devices: impl IntoIterator<Item = Device>) {
|
||||
let devices: HashMap<u16, Device> = devices.into_iter().take(MAX_DEVICES).map(|d| (d.id, d)).collect();
|
||||
self.last.retain(|id, _| devices.get(id).is_some_and(|d| self.devices.get(id) == Some(d)));
|
||||
let unchanged = |id: &u16| devices.get(id).is_some_and(|d| self.devices.get(id) == Some(d));
|
||||
self.last.retain(|id, _| unchanged(id));
|
||||
self.heard.retain(|id| unchanged(id));
|
||||
self.devices = devices;
|
||||
}
|
||||
|
||||
/// The names of the pens listed, by device id, for the log.
|
||||
fn pen_names(&self) -> Vec<&str> {
|
||||
let mut pens: Vec<&Device> = self.devices.values().filter(|d| d.is_pen()).collect();
|
||||
pens.sort_by_key(|d| d.id);
|
||||
pens.into_iter().map(|d| d.name.as_str()).collect()
|
||||
}
|
||||
|
||||
/// The pens listed, as the log line says it: under XWayland on a Wayland session this tells
|
||||
/// whether XWayland lists the pen at all (#5622).
|
||||
fn summary(&self) -> String {
|
||||
let names = self.pen_names();
|
||||
if names.is_empty() {
|
||||
"the X server lists no pen (a pointer device with an \"Abs Pressure\" valuator): a pen draws at full pressure".to_string()
|
||||
} else {
|
||||
format!("pens listed: {}", names.join(", "))
|
||||
}
|
||||
}
|
||||
|
||||
/// The name of pen `id` when this is the first event from it since it was listed, for the log:
|
||||
/// it tells whether the pen's events reach the app at all.
|
||||
fn first_event(&mut self, id: u16) -> Option<&str> {
|
||||
let device = self.devices.get(&id).filter(|d| d.is_pen())?;
|
||||
self.heard.insert(id).then_some(device.name.as_str())
|
||||
}
|
||||
|
||||
/// A raw motion or button event of device `id`, with the valuators that changed.
|
||||
fn handle(&mut self, id: u16, valuators: impl IntoIterator<Item = (u16, f64)>) -> Update {
|
||||
let Some(device) = self.devices.get(&id) else { return Update::Keep };
|
||||
@@ -231,6 +260,9 @@ impl Pens {
|
||||
/// A raw event as the X server sends it: its valuator mask and the values of the valuators
|
||||
/// set in it. A pen's sample or another pointer's `None` goes into `pen`.
|
||||
fn raw_event(&mut self, pen: &PenSource, id: u16, mask: &[u32], values: &[f64]) {
|
||||
if let Some(name) = self.first_event(id) {
|
||||
log::info!("tablet: events arrive from the pen {name:?}");
|
||||
}
|
||||
if let Update::Set(sample) = self.handle(id, valuators(mask, values)) {
|
||||
pen.set(sample);
|
||||
}
|
||||
@@ -304,6 +336,7 @@ mod x11 {
|
||||
.map_err(|e| format!("XISelectEvents failed: {e}"))?;
|
||||
let mut pens = Pens::default();
|
||||
pens.set_devices(query_devices(&conn));
|
||||
log::info!("tablet: {}", pens.summary());
|
||||
std::thread::Builder::new()
|
||||
.name("vectorcraft-tablet-x11".into())
|
||||
.spawn(move || run(&conn, &mut pens, &pen))
|
||||
@@ -321,7 +354,14 @@ mod x11 {
|
||||
let values: Vec<f64> = e.axisvalues.iter().map(|v| fp3232(v.integral, v.frac)).collect();
|
||||
pens.raw_event(pen, e.deviceid, &e.valuator_mask, &values);
|
||||
}
|
||||
Event::XinputHierarchy(_) | Event::XinputDeviceChanged(_) => pens.set_devices(query_devices(conn)),
|
||||
Event::XinputHierarchy(_) | Event::XinputDeviceChanged(_) => {
|
||||
let before = pens.summary();
|
||||
pens.set_devices(query_devices(conn));
|
||||
let after = pens.summary();
|
||||
if after != before {
|
||||
log::info!("tablet: {after}");
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
@@ -623,6 +663,31 @@ mod tests {
|
||||
assert!(s.pressure < 0.001, "{}", s.pressure);
|
||||
}
|
||||
|
||||
/// #5622: the log names the pens the X server lists (XWayland's included) and the first event
|
||||
/// from each, once, again after the pen is listed anew, and never for a mouse.
|
||||
#[test]
|
||||
fn the_log_names_the_pens_listed_and_the_first_event_from_each() {
|
||||
let stylus = Device::new(11, "xwayland-tablet stylus:16", Some("xwayland-tablet stylus"), pen_valuators());
|
||||
let eraser = Device::new(12, "xwayland-tablet eraser:16", Some("xwayland-tablet eraser"), pen_valuators());
|
||||
let mut pens = Pens::default();
|
||||
assert!(pens.summary().contains("lists no pen"), "{}", pens.summary());
|
||||
pens.set_devices([eraser.clone(), mouse(4), stylus.clone()]);
|
||||
assert_eq!(pens.summary(), "pens listed: xwayland-tablet stylus:16, xwayland-tablet eraser:16");
|
||||
assert_eq!(pens.first_event(11), Some("xwayland-tablet stylus:16"));
|
||||
assert_eq!(pens.first_event(11), None, "once");
|
||||
assert_eq!(pens.first_event(4), None, "a mouse");
|
||||
assert_eq!(pens.first_event(99), None, "a device not listed");
|
||||
// Listed again unchanged: still heard. Another device under the same id: heard anew.
|
||||
pens.set_devices([eraser.clone(), mouse(4), stylus]);
|
||||
assert_eq!(pens.first_event(11), None);
|
||||
pens.set_devices([eraser, mouse(4), pen(11)]);
|
||||
assert_eq!(pens.first_event(11), Some("Wacom Intuos Pro M Pen stylus"));
|
||||
// The events go into the feed as before.
|
||||
let source = PenSource::default();
|
||||
pens.raw_event(&source, 12, &[0b100], &[65535.0]);
|
||||
assert_eq!(source.current().map(|s| (s.eraser, s.pressure)), Some((true, 1.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fixed_point_values() {
|
||||
assert_eq!(fp3232(3, 1 << 31), 3.5);
|
||||
|
||||
@@ -1,5 +1,18 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn desktop_shell_reports_the_backend_selected_for_docking() {
|
||||
let wayland = desktop_shell_info(Backend::Wayland, false);
|
||||
assert_eq!(wayland.backend, Backend::Wayland);
|
||||
assert!(!wayland.window_positions(), "native Wayland keeps palettes inside the window");
|
||||
|
||||
for (detected, force_x11) in [(Backend::Wayland, true), (Backend::X11, false)] {
|
||||
let x11 = desktop_shell_info(detected, force_x11);
|
||||
assert_eq!(x11.backend, Backend::X11);
|
||||
assert!(x11.window_positions(), "X11 and XWayland can place native palettes");
|
||||
}
|
||||
}
|
||||
|
||||
/// The saved UI state of an old `ui.json`, as the legacy import reads it.
|
||||
fn legacy_ui(bytes: &[u8]) -> Option<vectorcraft_ui_egui::UiState> {
|
||||
vectorcraft_ui_egui::parse_legacy(bytes).ok().map(|(settings, _)| settings.ui)
|
||||
|
||||
@@ -4,14 +4,12 @@
|
||||
//! Windows does the work: when Alt comes up after keypad digits, `TranslateMessage` posts a
|
||||
//! `WM_CHAR` holding the character the code stands for (in the system's ANSI code page for a code
|
||||
//! with a leading 0, else its OEM code page), the convention every Windows text field follows
|
||||
//! (<https://learn.microsoft.com/en-us/windows/win32/inputdev/about-keyboard-input>). winit
|
||||
//! 0.30 reads a `WM_CHAR` only as part of the key press before it, so it drops this one, which
|
||||
//! follows a key release, and egui never sees the text. winit's message hook ([`msg_hook`]) sees
|
||||
//! the message before winit handles it: [`AltCodes`] notes keypad digits typed with Alt held, takes
|
||||
//! the character that follows Alt's release, and [`raw_input_hook`] hands it to the frame as typed
|
||||
//! text, so the Type tool (or a panel's text field) types it like any other character, in the
|
||||
//! same undo step as the typing round it. The keypad digits themselves are taken out of the frame,
|
||||
//! so they don't run a shortcut bound to Alt and a digit.
|
||||
//! (<https://learn.microsoft.com/en-us/windows/win32/inputdev/about-keyboard-input>). winit reports
|
||||
//! that character as a key press of its own with the character as its text (storytold/winit W36),
|
||||
//! so egui types it like any other character. Each keypad digit typed with Alt held also arrives
|
||||
//! as Alt and a digit, which would run a shortcut bound to Alt and that digit: winit's message
|
||||
//! hook ([`msg_hook`]) sees each message before winit handles it, [`AltCodes`] notes the keypad
|
||||
//! digits typed with Alt held, and [`raw_input_hook`] takes them out of the frame.
|
||||
//!
|
||||
//! With NumLock off the keypad keys arrive as Insert, End, Down, Page Down, Left, Clear, Right,
|
||||
//! Home, Up and Page Up, and Windows still composes the code from them. They are told from the
|
||||
@@ -29,11 +27,11 @@ use std::cell::RefCell;
|
||||
|
||||
use egui::{Event, Key};
|
||||
|
||||
#[cfg(windows)]
|
||||
const WM_KEYDOWN: u32 = 0x0100;
|
||||
const WM_KEYUP: u32 = 0x0101;
|
||||
const WM_CHAR: u32 = 0x0102;
|
||||
const WM_SYSKEYDOWN: u32 = 0x0104;
|
||||
const WM_SYSKEYUP: u32 = 0x0105;
|
||||
#[cfg(windows)]
|
||||
const WM_SYSCHAR: u32 = 0x0106;
|
||||
/// `VK_NUMPAD0` to `VK_NUMPAD9` (`winuser.h`): keypad digits with NumLock on.
|
||||
const VK_NUMPAD0: usize = 0x60;
|
||||
@@ -49,25 +47,15 @@ const DIGIT_KEYS: [Key; 10] = [Key::Num0, Key::Num1, Key::Num2, Key::Num3, Key::
|
||||
/// Bit 24 of a key message's `lParam`: an extended key, such as the navigation keys beside the
|
||||
/// keypad (the keypad's own keys clear it).
|
||||
const EXTENDED_KEY: isize = 1 << 24;
|
||||
/// `VK_MENU`, `VK_LMENU` and `VK_RMENU`: Alt.
|
||||
const ALT_KEYS: [usize; 3] = [0x12, 0xA4, 0xA5];
|
||||
|
||||
thread_local! {
|
||||
/// The UI thread's sequence: [`msg_hook`] and [`raw_input_hook`] both run on it.
|
||||
static CODES: RefCell<AltCodes> = RefCell::new(AltCodes::default());
|
||||
}
|
||||
|
||||
/// Where an Alt + keypad code stands, from the keyboard messages of the thread's queue.
|
||||
/// The keypad digits typed with Alt held, from the keyboard messages of the thread's queue.
|
||||
#[derive(Default)]
|
||||
struct AltCodes {
|
||||
/// Keypad digits typed while Alt has been held.
|
||||
digits: usize,
|
||||
/// Alt came up after keypad digits: the next character message is the code's character.
|
||||
armed: bool,
|
||||
/// A high surrogate waiting for its low half.
|
||||
high: Option<u16>,
|
||||
/// Characters the codes typed, for the next frame.
|
||||
typed: String,
|
||||
/// The digits of the keypad presses and releases with Alt held since the last frame, which
|
||||
/// egui reports as Alt and a digit (or, with NumLock off, Alt and a navigation key): taken
|
||||
/// out of the frame.
|
||||
@@ -88,80 +76,45 @@ fn keypad_digit(wparam: usize, lparam: isize) -> Option<usize> {
|
||||
|
||||
impl AltCodes {
|
||||
/// Note a keyboard message `message` with `wparam` (the virtual-key code, or a UTF-16 unit)
|
||||
/// and `lparam` (its flags).
|
||||
/// and `lparam` (its flags). Windows sends a key pressed or released with Alt held as a system
|
||||
/// key.
|
||||
fn message(&mut self, message: u32, wparam: usize, lparam: isize) {
|
||||
let keypad = match message {
|
||||
WM_SYSKEYDOWN | WM_SYSKEYUP => keypad_digit(wparam, lparam),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(d) = keypad {
|
||||
// Windows sends a key pressed with Alt held as a system key.
|
||||
if message == WM_SYSKEYDOWN {
|
||||
self.digits += 1;
|
||||
self.armed = false;
|
||||
}
|
||||
if matches!(message, WM_SYSKEYDOWN | WM_SYSKEYUP)
|
||||
&& let Some(d) = keypad_digit(wparam, lparam)
|
||||
{
|
||||
self.keypad_events.push(d);
|
||||
return;
|
||||
}
|
||||
match message {
|
||||
WM_KEYDOWN | WM_SYSKEYDOWN if ALT_KEYS.contains(&wparam) => {}
|
||||
// Any other key ends the sequence and keeps its own meaning.
|
||||
WM_KEYDOWN | WM_SYSKEYDOWN => self.reset(),
|
||||
WM_KEYUP | WM_SYSKEYUP if ALT_KEYS.contains(&wparam) => {
|
||||
self.armed = self.digits > 0;
|
||||
self.digits = 0;
|
||||
}
|
||||
WM_CHAR | WM_SYSCHAR if self.armed => {
|
||||
let unit = (wparam & 0xffff) as u16;
|
||||
if (0xd800..0xdc00).contains(&unit) {
|
||||
self.high = Some(unit);
|
||||
return;
|
||||
}
|
||||
let units: Vec<u16> = self.high.take().into_iter().chain([unit]).collect();
|
||||
self.typed.extend(char::decode_utf16(units).filter_map(Result::ok).filter(|c| !c.is_control()));
|
||||
self.armed = false;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn reset(&mut self) {
|
||||
self.digits = 0;
|
||||
self.armed = false;
|
||||
self.high = None;
|
||||
}
|
||||
|
||||
/// Hand the frame `events` the characters typed since the last frame, as typed text, and take
|
||||
/// out the keypad digits typed with Alt held.
|
||||
/// Take out of the frame `events` the keypad digits typed with Alt held since the last frame.
|
||||
/// The character a code types comes from winit, as typed text.
|
||||
fn drain(&mut self, events: &mut Vec<Event>) {
|
||||
let mut keypad = std::mem::take(&mut self.keypad_events);
|
||||
if !keypad.is_empty() {
|
||||
events.retain(|e| {
|
||||
let Event::Key { key, modifiers, .. } = e else {
|
||||
return true;
|
||||
};
|
||||
if !modifiers.alt {
|
||||
return true;
|
||||
}
|
||||
// The first keypad key still to take out that egui reports as `key`.
|
||||
let stands_for = |d: &usize| DIGIT_KEYS.get(*d) == Some(key) || NUMLOCK_OFF_EGUI_KEYS.get(*d) == Some(key);
|
||||
match keypad.iter().position(stands_for) {
|
||||
Some(i) => {
|
||||
keypad.remove(i);
|
||||
false
|
||||
}
|
||||
None => true,
|
||||
}
|
||||
});
|
||||
}
|
||||
if !self.typed.is_empty() {
|
||||
events.push(Event::Text(std::mem::take(&mut self.typed)));
|
||||
if keypad.is_empty() {
|
||||
return;
|
||||
}
|
||||
events.retain(|e| {
|
||||
let Event::Key { key, modifiers, .. } = e else {
|
||||
return true;
|
||||
};
|
||||
if !modifiers.alt {
|
||||
return true;
|
||||
}
|
||||
// The first keypad key still to take out that egui reports as `key`.
|
||||
let stands_for = |d: &usize| DIGIT_KEYS.get(*d) == Some(key) || NUMLOCK_OFF_EGUI_KEYS.get(*d) == Some(key);
|
||||
match keypad.iter().position(stands_for) {
|
||||
Some(i) => {
|
||||
keypad.remove(i);
|
||||
false
|
||||
}
|
||||
None => true,
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// winit's message hook for the keyboard: notes Alt + keypad codes and the characters they type,
|
||||
/// and hands each message to `windows_symbol_chars`. It never consumes the message.
|
||||
/// winit's message hook for the keyboard: notes the keypad digits typed with Alt held, and hands
|
||||
/// each message to `windows_symbol_chars`. It never consumes the message.
|
||||
#[cfg(windows)]
|
||||
#[allow(unsafe_code)]
|
||||
pub fn msg_hook(msg: *const std::ffi::c_void) {
|
||||
@@ -182,7 +135,7 @@ pub fn msg_hook(msg: *const std::ffi::c_void) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Before egui reads the main window's frame: the characters Alt + keypad codes typed, as text.
|
||||
/// Before egui reads the main window's frame: the keypad digits typed with Alt held are taken out.
|
||||
pub fn raw_input_hook(raw: &mut egui::RawInput) {
|
||||
CODES.with(|c| {
|
||||
if let Ok(mut c) = c.try_borrow_mut() {
|
||||
@@ -196,6 +149,9 @@ mod tests {
|
||||
use super::*;
|
||||
|
||||
const ALT: usize = 0x12;
|
||||
const WM_KEYDOWN: u32 = 0x0100;
|
||||
const WM_KEYUP: u32 = 0x0101;
|
||||
const WM_CHAR: u32 = 0x0102;
|
||||
|
||||
/// Alt held, keypad digits `code`, Alt released, and the character Windows then posts.
|
||||
fn alt_code(c: &mut AltCodes, code: &str, posted: u16) {
|
||||
@@ -215,59 +171,53 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_alt_code_types_its_character_when_alt_comes_up() {
|
||||
fn an_alt_codes_keypad_digits_leave_the_frame_and_its_character_is_typed_once() {
|
||||
let mut c = AltCodes::default();
|
||||
alt_code(&mut c, "0176", 0xB0);
|
||||
alt_code(&mut c, "0151", 0x2014);
|
||||
let mut events = vec![key(Key::Num0, true, true), key(Key::Num0, true, false), key(Key::Num1, false, true)];
|
||||
// winit reports each code's character as typed text.
|
||||
let mut events = vec![
|
||||
key(Key::Num0, true, true),
|
||||
key(Key::Num0, true, false),
|
||||
key(Key::Num1, false, true),
|
||||
Event::Text("°".into()),
|
||||
Event::Text("—".into()),
|
||||
];
|
||||
c.drain(&mut events);
|
||||
// The keypad digits typed with Alt are gone (eight presses and eight releases, two here);
|
||||
// the digit typed without Alt stays, and the characters follow.
|
||||
assert_eq!(events, vec![key(Key::Num1, false, true), Event::Text("°—".into())]);
|
||||
// the digit typed without Alt stays, and each character stays once.
|
||||
assert_eq!(events, vec![key(Key::Num1, false, true), Event::Text("°".into()), Event::Text("—".into())]);
|
||||
let mut events = vec![key(Key::Num0, true, true)];
|
||||
c.drain(&mut events);
|
||||
assert_eq!(events.len(), 1, "counts don't carry over to a later frame");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_character_without_a_code_before_it_is_left_to_winit() {
|
||||
fn characters_are_left_to_winit() {
|
||||
let mut c = AltCodes::default();
|
||||
// A plain key press's character (winit types it), and Alt pressed and released alone.
|
||||
// A plain key press's character, Alt pressed and released alone, and a code's character.
|
||||
c.message(WM_KEYDOWN, 0x41, 0);
|
||||
c.message(WM_CHAR, usize::from(b'a'), 0);
|
||||
c.message(WM_SYSKEYDOWN, ALT, 0);
|
||||
c.message(WM_KEYUP, ALT, 0);
|
||||
c.message(WM_CHAR, usize::from(b'b'), 0);
|
||||
alt_code(&mut c, "0176", 0xB0);
|
||||
let mut events = vec![];
|
||||
c.drain(&mut events);
|
||||
assert!(events.is_empty(), "{events:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn another_key_while_alt_is_held_cancels_the_code() {
|
||||
fn alt_with_another_key_keeps_its_shortcut() {
|
||||
let mut c = AltCodes::default();
|
||||
c.message(WM_SYSKEYDOWN, ALT, 0);
|
||||
c.message(WM_SYSKEYDOWN, VK_NUMPAD0 + 1, 0);
|
||||
// Alt+F: a shortcut, not a code.
|
||||
c.message(WM_SYSKEYDOWN, 0x46, 0);
|
||||
c.message(WM_KEYUP, ALT, 0);
|
||||
c.message(WM_CHAR, 0x41, 0);
|
||||
let mut events = vec![];
|
||||
let mut events = vec![key(Key::Num1, true, true), key(Key::F, true, true)];
|
||||
c.drain(&mut events);
|
||||
assert!(!events.iter().any(|e| matches!(e, Event::Text(_))), "{events:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_code_above_the_basic_plane_arrives_as_two_halves() {
|
||||
let mut c = AltCodes::default();
|
||||
c.message(WM_SYSKEYDOWN, ALT, 0);
|
||||
c.message(WM_SYSKEYDOWN, VK_NUMPAD0 + 1, 0);
|
||||
c.message(WM_KEYUP, ALT, 0);
|
||||
c.message(WM_CHAR, 0xD83D, 0);
|
||||
c.message(WM_CHAR, 0xDE00, 0);
|
||||
let mut events = vec![];
|
||||
c.drain(&mut events);
|
||||
assert_eq!(events, vec![Event::Text("😀".into())]);
|
||||
assert_eq!(events, vec![key(Key::F, true, true)]);
|
||||
}
|
||||
|
||||
/// Alt held, keypad digits `code` with NumLock off (keypad Insert, End, …, flags without the
|
||||
@@ -284,7 +234,7 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn with_numlock_off_the_keypad_keys_type_the_code_and_leave_the_caret_alone() {
|
||||
fn with_numlock_off_the_keypad_keys_leave_the_caret_alone() {
|
||||
let mut c = AltCodes::default();
|
||||
alt_code_numlock_off(&mut c, "0176", 0xB0);
|
||||
// What egui reports for keypad 0, 1, 7 and 6 with NumLock off and Alt held, a press and a
|
||||
@@ -296,7 +246,7 @@ mod tests {
|
||||
}
|
||||
events.push(key(Key::Home, false, true));
|
||||
c.drain(&mut events);
|
||||
assert_eq!(events, vec![key(Key::Home, false, true), Event::Text("°".into())]);
|
||||
assert_eq!(events, vec![key(Key::Home, false, true)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -309,11 +259,11 @@ mod tests {
|
||||
let mut events =
|
||||
vec![key(Key::Num5, true, true), key(Key::ArrowDown, true, true), key(Key::PageDown, true, true), key(Key::ArrowLeft, true, true)];
|
||||
c.drain(&mut events);
|
||||
assert_eq!(events, vec![Event::Text("—ê".into())]);
|
||||
assert!(events.is_empty(), "{events:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_separate_navigation_keys_still_move_the_caret_and_cancel_the_code() {
|
||||
fn the_separate_navigation_keys_still_move_the_caret() {
|
||||
let mut c = AltCodes::default();
|
||||
c.message(WM_SYSKEYDOWN, ALT, 0);
|
||||
c.message(WM_SYSKEYDOWN, NUMLOCK_OFF_KEYS[1], 0);
|
||||
@@ -322,7 +272,6 @@ mod tests {
|
||||
c.message(WM_SYSKEYDOWN, NUMLOCK_OFF_KEYS[7], EXTENDED_KEY);
|
||||
c.message(WM_SYSKEYUP, NUMLOCK_OFF_KEYS[7], EXTENDED_KEY);
|
||||
c.message(WM_KEYUP, ALT, 0);
|
||||
c.message(WM_CHAR, 0x41, 0);
|
||||
let mut events = vec![key(Key::End, true, true), key(Key::End, true, false), key(Key::Home, true, true), key(Key::Home, true, false)];
|
||||
c.drain(&mut events);
|
||||
assert_eq!(events, vec![key(Key::Home, true, true), key(Key::Home, true, false)]);
|
||||
|
||||
@@ -22,18 +22,61 @@ use std::path::{Path, PathBuf};
|
||||
const X11_LIBS: &[&str] =
|
||||
&["libX11.so.6", "libX11-xcb.so.1", "libxcb.so.1", "libXcursor.so.1", "libXi.so.6", "libxkbcommon.so.0", "libxkbcommon-x11.so.0"];
|
||||
|
||||
/// Whether the saved `linuxDisplayServer` and the environment ask for XWayland: `x11` chosen, or
|
||||
/// any other choice (`automatic`, `x11WithPen`, none saved) with `pen` finding a pen and
|
||||
/// `VECTORCRAFT_NATIVE_WAYLAND` unset (or `0`); a Wayland session (winit picks Wayland whenever
|
||||
/// `WAYLAND_DISPLAY` or `WAYLAND_SOCKET` is set); and an X display to open. `pen` runs only after
|
||||
/// the other checks.
|
||||
pub fn wanted(pref: Option<&str>, var: impl Fn(&str) -> Option<OsString>, pen: impl FnOnce() -> bool) -> bool {
|
||||
/// What the pen check found: the name of the first pen, `None` when there is none, or why the
|
||||
/// device list could not be read.
|
||||
pub type PenProbe = Result<Option<String>, String>;
|
||||
|
||||
/// Where the window opens, and why, as [`choose`] decides it.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum Choice {
|
||||
/// Not a Wayland session: the window opens where winit opens it.
|
||||
NotWayland,
|
||||
/// XWayland, because Linux Display Server is X11 (XWayland).
|
||||
Chosen,
|
||||
/// XWayland, because the pen of this name is attached.
|
||||
Pen(String),
|
||||
/// Wayland: the session has no X display (`DISPLAY` is unset, as in the Flatpak on a Wayland
|
||||
/// session), so XWayland can't be used. `x11` is whether X11 (XWayland) was chosen.
|
||||
NoXDisplay { x11: bool },
|
||||
/// Wayland: `VECTORCRAFT_NATIVE_WAYLAND` keeps the window there.
|
||||
NativeWayland,
|
||||
/// Wayland: no pen is attached.
|
||||
NoPen,
|
||||
/// Wayland: the input devices could not be listed, for this reason.
|
||||
NoDeviceList(String),
|
||||
}
|
||||
|
||||
impl Choice {
|
||||
/// Whether the window opens through XWayland.
|
||||
pub fn xwayland(&self) -> bool {
|
||||
matches!(self, Self::Chosen | Self::Pen(_))
|
||||
}
|
||||
}
|
||||
|
||||
/// Where the saved `linuxDisplayServer` and the environment open the window: XWayland for `x11`
|
||||
/// chosen, or for any other choice (`automatic`, `x11WithPen`, none saved) with `pen` finding a pen
|
||||
/// and `VECTORCRAFT_NATIVE_WAYLAND` unset (or `0`), on a Wayland session (winit picks Wayland
|
||||
/// whenever `WAYLAND_DISPLAY` or `WAYLAND_SOCKET` is set) with an X display to open. `pen` runs
|
||||
/// only after the other checks.
|
||||
pub fn choose(pref: Option<&str>, var: impl Fn(&str) -> Option<OsString>, pen: impl FnOnce() -> PenProbe) -> Choice {
|
||||
let set = |name: &str| var(name).is_some_and(|v| !v.is_empty());
|
||||
let session = (set("WAYLAND_DISPLAY") || set("WAYLAND_SOCKET")) && set("DISPLAY");
|
||||
let native_wayland = var("VECTORCRAFT_NATIVE_WAYLAND").is_some_and(|v| !v.is_empty() && v != "0");
|
||||
match pref {
|
||||
Some("x11") => session,
|
||||
_ => session && !native_wayland && pen(),
|
||||
if !set("WAYLAND_DISPLAY") && !set("WAYLAND_SOCKET") {
|
||||
return Choice::NotWayland;
|
||||
}
|
||||
let x11 = pref == Some("x11");
|
||||
if !set("DISPLAY") {
|
||||
return Choice::NoXDisplay { x11 };
|
||||
}
|
||||
if x11 {
|
||||
return Choice::Chosen;
|
||||
}
|
||||
if var("VECTORCRAFT_NATIVE_WAYLAND").is_some_and(|v| !v.is_empty() && v != "0") {
|
||||
return Choice::NativeWayland;
|
||||
}
|
||||
match pen() {
|
||||
Ok(Some(name)) => Choice::Pen(name),
|
||||
Ok(None) => Choice::NoPen,
|
||||
Err(e) => Choice::NoDeviceList(e),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -44,20 +87,28 @@ const BTN_TOOL_PEN: u32 = 0x140;
|
||||
const ABS_X: u32 = 0x00;
|
||||
const ABS_Y: u32 = 0x01;
|
||||
|
||||
/// Is a pen attached? Reads `/proc/bus/input/devices`; a file that can't be read has no pen.
|
||||
pub fn pen_attached() -> bool {
|
||||
std::fs::read_to_string("/proc/bus/input/devices").is_ok_and(|devices| has_pen(&devices))
|
||||
/// The pen attached, from `/proc/bus/input/devices`, or why that file could not be read.
|
||||
pub fn pen_attached() -> PenProbe {
|
||||
std::fs::read_to_string("/proc/bus/input/devices").map(|devices| find_pen(&devices)).map_err(|e| format!("/proc/bus/input/devices: {e}"))
|
||||
}
|
||||
|
||||
/// Is a pen among the input devices `/proc/bus/input/devices` lists? A pen is a device whose
|
||||
/// Is a pen among the input devices `/proc/bus/input/devices` lists?
|
||||
#[cfg(test)]
|
||||
fn has_pen(devices: &str) -> bool {
|
||||
find_pen(devices).is_some()
|
||||
}
|
||||
|
||||
/// The name of the first pen among the input devices `/proc/bus/input/devices` lists (its
|
||||
/// `N: Name=` line without the quotes, empty when it has none). A pen is a device whose
|
||||
/// `B: KEY=` bitmap has `BTN_TOOL_PEN` and whose `B: ABS=` bitmap has `ABS_X` and `ABS_Y`, as
|
||||
/// libinput asks of a tablet tool. A virtual keyboard made with uinput can claim every key code,
|
||||
/// `BTN_TOOL_PEN` included, but has no absolute axes.
|
||||
fn has_pen(devices: &str) -> bool {
|
||||
devices.split("\n\n").any(|device| {
|
||||
let bitmap = |name: &str| device.lines().find_map(|l| l.strip_prefix(name));
|
||||
bitmap("B: KEY=").is_some_and(|keys| bit_set(keys, BTN_TOOL_PEN))
|
||||
&& bitmap("B: ABS=").is_some_and(|axes| bit_set(axes, ABS_X) && bit_set(axes, ABS_Y))
|
||||
fn find_pen(devices: &str) -> Option<String> {
|
||||
devices.split("\n\n").find_map(|device| {
|
||||
let field = |name: &str| device.lines().find_map(|l| l.strip_prefix(name));
|
||||
let pen = field("B: KEY=").is_some_and(|keys| bit_set(keys, BTN_TOOL_PEN))
|
||||
&& field("B: ABS=").is_some_and(|axes| bit_set(axes, ABS_X) && bit_set(axes, ABS_Y));
|
||||
pen.then(|| field("N: Name=").map_or_else(String::new, |n| n.trim().trim_matches('"').to_string()))
|
||||
})
|
||||
}
|
||||
|
||||
@@ -147,6 +198,11 @@ mod tests {
|
||||
panic!("the pen check ran")
|
||||
}
|
||||
|
||||
/// [`choose`] as a yes or no, with a pen check that finds a pen or none.
|
||||
fn wanted(pref: Option<&str>, var: impl Fn(&str) -> Option<OsString>, pen: impl FnOnce() -> bool) -> bool {
|
||||
choose(pref, var, || Ok(pen().then(|| "Pen".to_string()))).xwayland()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn xwayland_only_when_chosen_on_wayland_with_an_x_display() {
|
||||
let wayland = env(&[("WAYLAND_DISPLAY", "wayland-0"), ("DISPLAY", ":0")]);
|
||||
@@ -183,6 +239,40 @@ mod tests {
|
||||
assert!(wanted(Some("x11"), &native, no_probe));
|
||||
}
|
||||
|
||||
/// #5622: the choice names why the window stays on Wayland, where the pen does not reach it,
|
||||
/// so that the log tells a missing X display (the Flatpak on a Wayland session) from a pen
|
||||
/// that is not listed or a device list that can't be read.
|
||||
#[test]
|
||||
fn the_choice_says_why_the_window_stays_on_wayland() {
|
||||
let wayland = env(&[("WAYLAND_DISPLAY", "wayland-0"), ("DISPLAY", ":0")]);
|
||||
let no_x = env(&[("WAYLAND_DISPLAY", "wayland-0")]);
|
||||
let native = env(&[("WAYLAND_DISPLAY", "wayland-0"), ("DISPLAY", ":0"), ("VECTORCRAFT_NATIVE_WAYLAND", "1")]);
|
||||
let pen = || Ok(Some("ELAN9008:00 04F3:2C82 Stylus".to_string()));
|
||||
let never = || -> PenProbe { panic!("the pen check ran") };
|
||||
assert_eq!(choose(None, env(&[("DISPLAY", ":0")]), never), Choice::NotWayland);
|
||||
assert_eq!(choose(None, &no_x, never), Choice::NoXDisplay { x11: false });
|
||||
assert_eq!(choose(Some("x11"), &no_x, never), Choice::NoXDisplay { x11: true });
|
||||
assert_eq!(choose(Some("x11"), &wayland, never), Choice::Chosen);
|
||||
assert_eq!(choose(Some("automatic"), &native, never), Choice::NativeWayland);
|
||||
assert_eq!(choose(Some("automatic"), &wayland, pen), Choice::Pen("ELAN9008:00 04F3:2C82 Stylus".to_string()));
|
||||
assert_eq!(choose(Some("x11WithPen"), &wayland, || Ok(None)), Choice::NoPen);
|
||||
let unreadable = choose(None, &wayland, || Err("/proc/bus/input/devices: Permission denied".to_string()));
|
||||
assert_eq!(unreadable, Choice::NoDeviceList("/proc/bus/input/devices: Permission denied".to_string()));
|
||||
for stays in [Choice::NotWayland, Choice::NoXDisplay { x11: true }, Choice::NativeWayland, Choice::NoPen, unreadable] {
|
||||
assert!(!stays.xwayland(), "{stays:?}");
|
||||
}
|
||||
assert!(Choice::Chosen.xwayland() && Choice::Pen(String::new()).xwayland());
|
||||
}
|
||||
|
||||
/// The pen check names the pen it found, for the log.
|
||||
#[test]
|
||||
fn the_pen_check_names_the_pen() {
|
||||
assert_eq!(find_pen(WITH_PEN).as_deref(), Some("Wacom Intuos Pro M Pen"));
|
||||
let without = WITH_PEN.split("\n\n").take(2).collect::<Vec<_>>().join("\n\n");
|
||||
assert_eq!(find_pen(&without), None);
|
||||
assert_eq!(find_pen("B: KEY=1c03 0 0 0 0 0\nB: ABS=3\n").as_deref(), Some(""), "a pen without a name line");
|
||||
}
|
||||
|
||||
/// `/proc/bus/input/devices` of a laptop with a Wacom Intuos Pro attached (64-bit longs: the
|
||||
/// pen's `KEY=1c03 0 0 0 0 0` has bit 0x140, `BTN_TOOL_PEN`), from PhotoCraft's tests.
|
||||
const WITH_PEN: &str = "I: Bus=0011 Vendor=0001 Product=0001 Version=ab83\n\
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M2 4.8L18.7 1.4L22.6 21.6L4.8 18.2Z"/>
|
||||
<rect x="0.8" y="3.6" width="2.4" height="2.4" fill="currentColor"/>
|
||||
<rect x="17.5" y="0.2" width="2.4" height="2.4" fill="currentColor"/>
|
||||
|
||||
|
Before Width: | Height: | Size: 525 B After Width: | Height: | Size: 527 B |
@@ -19,8 +19,11 @@ craft-affinity = { workspace = true }
|
||||
[dev-dependencies]
|
||||
proptest = { workspace = true }
|
||||
# The tests build containers and decode previews.
|
||||
crc32fast = { workspace = true }
|
||||
craft-image-codecs = { workspace = true }
|
||||
# tests/it's `import_limits`, `outline_limits` and `text` modules need `synth`, also when this crate
|
||||
# is tested without vectorcraft-engine (`cargo xtask ci shard`).
|
||||
vectorcraft-affinity = { path = ".", features = ["synth"] }
|
||||
|
||||
# The files of other crates that this crate's tests compile or read, for CI's test selection.
|
||||
[package.metadata.craft]
|
||||
reads = ["xtask/affinity-corpus.sha256", "xtask/src/sha256.rs"]
|
||||
|
||||
@@ -41,6 +41,70 @@ fn source(bytes: &[u8]) -> Vec<u8> {
|
||||
block.bytes(block.root, b"Data").unwrap().to_vec()
|
||||
}
|
||||
|
||||
/// The fixture's one tiled bitmap read straight from its archive entries, interleaved: RGBA8 for
|
||||
/// RGBA layers (16-bit samples scaled to 8 bits with rounding) and C, M, Y, K, alpha for CMYK.
|
||||
/// Each channel is a grid of 256-byte × 256-row tiles in row-major order; state 2 is a tile of
|
||||
/// 0xFF, state 4 a stored tile (the next `Idx<c>` entry), and any other state a tile of zeros.
|
||||
fn tiled_pixels(bytes: &[u8]) -> (u32, u32, Vec<u8>) {
|
||||
const TILE: usize = 256;
|
||||
let mut archive = Archive::open(bytes, Limits::default()).unwrap();
|
||||
let doc = stream::parse(&archive.read("doc.dat").unwrap()).unwrap();
|
||||
// The bitmap the image layer (`ImgN`) holds as `Bitm`; the document's other bitmaps are masks.
|
||||
let bitmaps: Vec<usize> = (0..doc.objects.len())
|
||||
.filter(|&o| doc.is(o, b"ImgN"))
|
||||
.filter_map(|o| doc.obj(o, b"Bitm"))
|
||||
.filter(|&b| doc.is(b, b"DyBm") && doc.field(b, b"Sta1").is_some())
|
||||
.collect();
|
||||
assert_eq!(bitmaps.len(), 1, "one tiled image bitmap");
|
||||
let bitmap = bitmaps[0];
|
||||
let width = usize::try_from(doc.int(bitmap, b"BmpW").unwrap()).unwrap();
|
||||
let height = usize::try_from(doc.int(bitmap, b"BmpH").unwrap()).unwrap();
|
||||
let (channels, bps) = match doc.enumeration(bitmap, b"Frmt").unwrap().0 {
|
||||
0 => (4, 1),
|
||||
1 => (4, 2),
|
||||
4 => (5, 1),
|
||||
other => panic!("format {other}"),
|
||||
};
|
||||
let row = width * bps;
|
||||
let across = row.div_ceil(TILE);
|
||||
let mut planes = Vec::new();
|
||||
for c in 1..=channels {
|
||||
let digit = b'0' + c as u8;
|
||||
let Some(stream::Value::Array(states)) = doc.field(bitmap, &[b'S', b't', b'a', digit]) else { panic!("states of channel {c}") };
|
||||
let mut stored = doc.objs(bitmap, &[b'I', b'd', b'x', digit]).into_iter();
|
||||
let mut plane = vec![0u8; row * height];
|
||||
for (t, state) in states.iter().enumerate().take(across * height.div_ceil(TILE)) {
|
||||
let tile: Vec<u8> = match state {
|
||||
stream::Value::UInt(2) => vec![0xFF; TILE * TILE],
|
||||
stream::Value::UInt(4) => {
|
||||
let name = doc.entry(stored.next().unwrap(), b"Data").unwrap().to_string();
|
||||
let data = archive.read(&name).unwrap();
|
||||
assert_eq!(data.len(), TILE * TILE, "{name}");
|
||||
data
|
||||
}
|
||||
_ => continue,
|
||||
};
|
||||
let (ox, oy) = ((t % across) * TILE, (t / across) * TILE);
|
||||
for y in oy..(oy + TILE).min(height) {
|
||||
for x in ox..(ox + TILE).min(row) {
|
||||
plane[y * row + x] = tile[(y - oy) * TILE + x - ox];
|
||||
}
|
||||
}
|
||||
}
|
||||
planes.push(plane);
|
||||
}
|
||||
let sample = |c: usize, i: usize| -> u8 {
|
||||
if bps == 1 {
|
||||
planes[c][i]
|
||||
} else {
|
||||
let v = u32::from(u16::from_le_bytes([planes[c][2 * i], planes[c][2 * i + 1]]));
|
||||
u8::try_from((v * 255 + 32767) / 65535).unwrap()
|
||||
}
|
||||
};
|
||||
let pixels = (0..width * height).flat_map(|i| (0..channels).map(move |c| (c, i))).map(|(c, i)| sample(c, i)).collect();
|
||||
(u32::try_from(width).unwrap(), u32::try_from(height).unwrap(), pixels)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn source_backed_tiles_retain_the_embedded_jpeg_pixels() {
|
||||
let Some((bytes, doc, images)) = read_fixture("patchy-embedded-jpeg.af") else { return };
|
||||
@@ -68,8 +132,8 @@ fn lazy_placed_images_keep_the_original_encoded_bytes() {
|
||||
|
||||
#[test]
|
||||
fn eight_and_sixteen_bit_channels_retain_the_same_pixel_pattern() {
|
||||
let Some((_, doc8, images8)) = read_fixture("patchy-rgba8.af") else { return };
|
||||
let (_, doc16, images16) = read_fixture("patchy-rgba16.af").unwrap();
|
||||
let Some((bytes8, doc8, images8)) = read_fixture("patchy-rgba8.af") else { return };
|
||||
let (bytes16, doc16, images16) = read_fixture("patchy-rgba16.af").unwrap();
|
||||
assert!(doc8.warnings.is_empty());
|
||||
assert!(doc16.warnings.is_empty());
|
||||
assert_eq!(images8.len(), 1);
|
||||
@@ -80,13 +144,13 @@ fn eight_and_sixteen_bit_channels_retain_the_same_pixel_pattern() {
|
||||
assert_eq!(&pixels[..4], &[0, 0, 0, 128]);
|
||||
assert!(pixels.as_chunks::<4>().0.iter().any(|p| p[3] < 255));
|
||||
assert!(pixels.as_chunks::<4>().0.iter().any(|p| p[0] != p[1]));
|
||||
// Frozen pixel-retention baseline, including every alpha sample. It is not a render oracle.
|
||||
assert_eq!(crc32fast::hash(pixels), 0xc8ee4dc1);
|
||||
assert_eq!(tiled_pixels(&bytes8), (64, 48, pixels.clone()));
|
||||
assert_eq!(tiled_pixels(&bytes16), (64, 48, pixels.clone()), "16-bit samples scaled to 8 bits");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rotated_scaled_pixels_keep_the_full_affine_transform() {
|
||||
let Some((_, doc, images)) = read_fixture("patchy-transform.af") else { return };
|
||||
let Some((bytes, doc, images)) = read_fixture("patchy-transform.af") else { return };
|
||||
assert!(doc.warnings.is_empty());
|
||||
assert_eq!(images.len(), 1);
|
||||
assert_eq!((images[0].width, images[0].height), (80, 60));
|
||||
@@ -97,18 +161,19 @@ fn rotated_scaled_pixels_keep_the_full_affine_transform() {
|
||||
let Pixels::Rgba8(pixels) = &images[0].pixels else { panic!() };
|
||||
assert_eq!(pixels.len(), 80 * 60 * 4);
|
||||
assert!(pixels.as_chunks::<4>().0.iter().all(|p| p[3] == 255));
|
||||
assert_eq!(crc32fast::hash(pixels), 0x3720a442);
|
||||
assert_eq!(tiled_pixels(&bytes), (80, 60, pixels.clone()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cmyk_pixels_stay_cmyk_and_lab_losses_are_reported() {
|
||||
// CMYK layers keep their inks for the importer to convert through a colour profile.
|
||||
let Some((_, cmyk, images)) = read_fixture("patchy-cmyk.af") else { return };
|
||||
let Some((bytes, cmyk, images)) = read_fixture("patchy-cmyk.af") else { return };
|
||||
assert_eq!(images.len(), 1);
|
||||
assert_eq!((images[0].width, images[0].height), (64, 48));
|
||||
let Pixels::Cmyka8(pixels) = &images[0].pixels else { panic!() };
|
||||
assert_eq!(pixels.len(), 64 * 48 * 5);
|
||||
assert_eq!(crc32fast::hash(pixels), 0x56b1f659);
|
||||
assert_eq!(tiled_pixels(&bytes), (64, 48, pixels.clone()));
|
||||
assert!(pixels.as_chunks::<5>().0.iter().any(|p| p[0] != p[3]), "inks differ between channels");
|
||||
assert!(cmyk.warnings.is_empty(), "{:?}", cmyk.warnings);
|
||||
assert_eq!(cmyk.cmyk_profile, None, "this file embeds no profile");
|
||||
let (_, lab, images) = read_fixture("patchy-lab.af").unwrap();
|
||||
|
||||
@@ -1,33 +1,33 @@
|
||||
affinity3-mexican-guy.af dpi=300;spreads=1;model_crc32=32b7cf3f;counts={"depth": 8, "fills": 169, "gradients": 0, "groups": 23, "nodes": 283, "opacity": 1, "segments": 1491, "shapes": 260, "strokes": 114, "subpaths": 264};boards=[];fonts={};warnings=["blur effects (left out) (156×)"]
|
||||
affinity3-mexican-man.af dpi=300;spreads=1;model_crc32=c10daaea;counts={"depth": 7, "fills": 277, "gradients": 2, "groups": 29, "nodes": 903, "segments": 3225, "shapes": 874, "strokes": 540, "subpaths": 881};boards=[];fonts={};warnings=["blur effects (left out) (244×)"]
|
||||
affinity3-mexican-woman.af dpi=300;spreads=1;model_crc32=3bc13374;counts={"depth": 9, "fills": 527, "gradients": 0, "groups": 28, "nodes": 595, "segments": 3562, "shapes": 567, "strokes": 60, "subpaths": 570};boards=[];fonts={};warnings=["blur effects (left out) (278×)"]
|
||||
affinity3-playing-cards.af dpi=300;spreads=1;model_crc32=bc0c838d;counts={"depth": 5, "fills": 363, "gradients": 0, "groups": 758, "nodes": 1350, "segments": 4864, "shapes": 592, "strokes": 17, "subpaths": 656};boards=[];fonts={};warnings=["blur effects (left out) (309×)", "brush strokes (imported as plain strokes)"]
|
||||
patchy-adjust-curves.af dpi=72;spreads=1;model_crc32=36ab962f;counts={"depth": 1, "images": 1, "nodes": 2, "unsupported": 1};boards=[];fonts={};warnings=["adjustment layers"]
|
||||
patchy-adjust-hsl.af dpi=72;spreads=1;model_crc32=e2eac05e;counts={"depth": 1, "images": 1, "nodes": 2, "unsupported": 1};boards=[];fonts={};warnings=["adjustment layers"]
|
||||
patchy-artboards.af dpi=72;spreads=1;model_crc32=0037a28e;counts={"artboards": 2, "depth": 2, "fills": 2, "gradients": 0, "nodes": 4, "segments": 7, "shapes": 2, "strokes": 0, "subpaths": 2};boards=["board-a:0.0000,0.0000,80.0000,60.0000", "board-b:100.0000,10.0000,160.0000,70.0000"];fonts={};warnings=[]
|
||||
patchy-blend-affinity.af dpi=72;spreads=1;model_crc32=8497c917;counts={"depth": 2, "fills": 8, "gradients": 0, "images": 1, "layers": 1, "nodes": 10, "segments": 24, "shapes": 8, "strokes": 0, "subpaths": 8};boards=[];fonts={};warnings=["an unknown blend mode (imported as Normal) (2×)"]
|
||||
patchy-cmyk.af dpi=72;spreads=1;model_crc32=56754ce9;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[]
|
||||
patchy-dpi300.af dpi=300;spreads=1;model_crc32=2561f9d3;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[]
|
||||
patchy-embedded-jpeg.af dpi=72;spreads=1;model_crc32=ab4b6fbf;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[]
|
||||
patchy-fx-blur.af dpi=72;spreads=1;model_crc32=29b5083b;counts={"depth": 1, "images": 2, "nodes": 2};boards=[];fonts={};warnings=["blur effects (left out) (2×)"]
|
||||
patchy-fx-gradient.af dpi=72;spreads=1;model_crc32=96cd10be;counts={"depth": 1, "images": 3, "nodes": 3};boards=[];fonts={};warnings=[]
|
||||
patchy-fx.af dpi=72;spreads=1;model_crc32=7c8d4d20;counts={"depth": 1, "images": 5, "nodes": 5};boards=[];fonts={};warnings=[]
|
||||
patchy-group.af dpi=72;spreads=1;model_crc32=dc37ab6c;counts={"depth": 2, "images": 3, "layers": 1, "nodes": 4};boards=[];fonts={};warnings=[]
|
||||
patchy-incremental-chain.af dpi=72;spreads=1;model_crc32=38c9c5f4;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[]
|
||||
patchy-lab.af dpi=72;spreads=1;model_crc32=df3a4e40;counts={"depth": 1, "nodes": 1, "unsupported": 1};boards=[];fonts={};warnings=["pixel layers in grey, Lab or 32-bit formats"]
|
||||
patchy-lazy-placed.af dpi=72;spreads=1;model_crc32=8776a8a0;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[]
|
||||
patchy-live-filter.af dpi=72;spreads=1;model_crc32=12235fe9;counts={"depth": 2, "fills": 2, "gradients": 0, "nodes": 4, "segments": 6, "shapes": 2, "strokes": 0, "subpaths": 2, "unsupported": 2};boards=[];fonts={};warnings=["adjustment layers", "unknown layers"]
|
||||
patchy-rgba16.af dpi=72;spreads=1;model_crc32=688b2475;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[]
|
||||
patchy-rgba8.af dpi=72;spreads=1;model_crc32=688b2475;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[]
|
||||
patchy-shapes-2.af dpi=72;spreads=1;model_crc32=6f174318;counts={"depth": 1, "fills": 12, "gradients": 0, "nodes": 12, "segments": 168, "shapes": 12, "strokes": 0, "subpaths": 13};boards=[];fonts={};warnings=[]
|
||||
patchy-shapes.af dpi=72;spreads=1;model_crc32=c1790e97;counts={"depth": 1, "fills": 4, "gradients": 0, "nodes": 4, "segments": 28, "shapes": 4, "strokes": 0, "subpaths": 4};boards=[];fonts={};warnings=[]
|
||||
patchy-text-artistic.af dpi=72;spreads=1;model_crc32=1d33192c;counts={"depth": 1, "nodes": 1, "text_chars": 5, "text_runs": 1, "texts": 1};boards=[];fonts={"Arial:ArialMT:400:false"};warnings=[]
|
||||
patchy-text-caps.af dpi=72;spreads=1;model_crc32=24e52518;counts={"depth": 1, "nodes": 2, "text_chars": 21, "text_runs": 2, "texts": 2};boards=[];fonts={"Arial:ArialNarrow:400:false"};warnings=["font width variants (exact face depends on the installed PostScript font) (2×)"]
|
||||
patchy-text-frame.af dpi=72;spreads=1;model_crc32=3bff8ef9;counts={"depth": 1, "nodes": 1, "text_chars": 11, "text_runs": 1, "texts": 1};boards=[];fonts={"Arial:ArialMT:400:false"};warnings=[]
|
||||
patchy-text-indent.af dpi=72;spreads=1;model_crc32=dc36dfc5;counts={"depth": 1, "nodes": 2, "text_chars": 104, "text_runs": 2, "texts": 2};boards=[];fonts={"Arial:ArialNarrow:400:false"};warnings=["font width variants (exact face depends on the installed PostScript font) (2×)"]
|
||||
patchy-text-para-spacing.af dpi=72;spreads=1;model_crc32=6408f39b;counts={"depth": 1, "nodes": 1, "text_chars": 13, "text_runs": 1, "texts": 1};boards=[];fonts={"Arial:ArialNarrow:400:false"};warnings=["font width variants (exact face depends on the installed PostScript font)"]
|
||||
patchy-text-rotated.af dpi=72;spreads=1;model_crc32=3d1de559;counts={"depth": 1, "nodes": 1, "text_chars": 7, "text_runs": 1, "texts": 1};boards=[];fonts={"Arial:ArialNarrow:400:false"};warnings=["font width variants (exact face depends on the installed PostScript font)"]
|
||||
patchy-text-runs.af dpi=72;spreads=1;model_crc32=7820b881;counts={"depth": 1, "nodes": 1, "text_chars": 7, "text_runs": 5, "texts": 1};boards=[];fonts={"Arial:ArialNarrow:400:false", "Courier New:CourierNewPSMT:400:false", "Segoe UI Emoji:SegoeUIEmoji:400:false", "Times New Roman:TimesNewRomanPSMT:400:false"};warnings=["font width variants (exact face depends on the installed PostScript font)", "text uses a stored fallback font (imported with that font)"]
|
||||
patchy-transform.af dpi=72;spreads=1;model_crc32=8d56df84;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[]
|
||||
patchy-vector-mask.af dpi=72;spreads=1;model_crc32=80ca946a;counts={"depth": 1, "fills": 2, "gradients": 0, "nodes": 2, "segments": 7, "shapes": 2, "strokes": 0, "subpaths": 2, "vector_masks": 1};boards=[];fonts={};warnings=["unknown layers attached to other layers (imported without them)"]
|
||||
patchy-vector.af dpi=72;spreads=1;model_crc32=3b16c7ed;counts={"depth": 1, "fills": 3, "gradients": 0, "nodes": 4, "segments": 17, "shapes": 4, "strokes": 2, "subpaths": 5};boards=[];fonts={};warnings=[]
|
||||
affinity3-mexican-guy.af dpi=300;spreads=1;counts={"depth": 8, "fills": 169, "gradients": 0, "groups": 23, "nodes": 283, "opacity": 1, "segments": 1491, "shapes": 260, "strokes": 114, "subpaths": 264};boards=[];fonts={};warnings=["blur effects (left out) (156×)"]
|
||||
affinity3-mexican-man.af dpi=300;spreads=1;counts={"depth": 7, "fills": 277, "gradients": 2, "groups": 29, "nodes": 903, "segments": 3225, "shapes": 874, "strokes": 540, "subpaths": 881};boards=[];fonts={};warnings=["blur effects (left out) (244×)"]
|
||||
affinity3-mexican-woman.af dpi=300;spreads=1;counts={"depth": 9, "fills": 527, "gradients": 0, "groups": 28, "nodes": 595, "segments": 3562, "shapes": 567, "strokes": 60, "subpaths": 570};boards=[];fonts={};warnings=["blur effects (left out) (278×)"]
|
||||
affinity3-playing-cards.af dpi=300;spreads=1;counts={"depth": 5, "fills": 363, "gradients": 0, "groups": 758, "nodes": 1350, "segments": 4864, "shapes": 592, "strokes": 17, "subpaths": 656};boards=[];fonts={};warnings=["blur effects (left out) (309×)", "brush strokes (imported as plain strokes)"]
|
||||
patchy-adjust-curves.af dpi=72;spreads=1;counts={"depth": 1, "images": 1, "nodes": 2, "unsupported": 1};boards=[];fonts={};warnings=["adjustment layers"]
|
||||
patchy-adjust-hsl.af dpi=72;spreads=1;counts={"depth": 1, "images": 1, "nodes": 2, "unsupported": 1};boards=[];fonts={};warnings=["adjustment layers"]
|
||||
patchy-artboards.af dpi=72;spreads=1;counts={"artboards": 2, "depth": 2, "fills": 2, "gradients": 0, "nodes": 4, "segments": 7, "shapes": 2, "strokes": 0, "subpaths": 2};boards=["board-a:0.0000,0.0000,80.0000,60.0000", "board-b:100.0000,10.0000,160.0000,70.0000"];fonts={};warnings=[]
|
||||
patchy-blend-affinity.af dpi=72;spreads=1;counts={"depth": 2, "fills": 8, "gradients": 0, "images": 1, "layers": 1, "nodes": 10, "segments": 24, "shapes": 8, "strokes": 0, "subpaths": 8};boards=[];fonts={};warnings=["an unknown blend mode (imported as Normal) (2×)"]
|
||||
patchy-cmyk.af dpi=72;spreads=1;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[]
|
||||
patchy-dpi300.af dpi=300;spreads=1;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[]
|
||||
patchy-embedded-jpeg.af dpi=72;spreads=1;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[]
|
||||
patchy-fx-blur.af dpi=72;spreads=1;counts={"depth": 1, "images": 2, "nodes": 2};boards=[];fonts={};warnings=["blur effects (left out) (2×)"]
|
||||
patchy-fx-gradient.af dpi=72;spreads=1;counts={"depth": 1, "images": 3, "nodes": 3};boards=[];fonts={};warnings=[]
|
||||
patchy-fx.af dpi=72;spreads=1;counts={"depth": 1, "images": 5, "nodes": 5};boards=[];fonts={};warnings=[]
|
||||
patchy-group.af dpi=72;spreads=1;counts={"depth": 2, "images": 3, "layers": 1, "nodes": 4};boards=[];fonts={};warnings=[]
|
||||
patchy-incremental-chain.af dpi=72;spreads=1;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[]
|
||||
patchy-lab.af dpi=72;spreads=1;counts={"depth": 1, "nodes": 1, "unsupported": 1};boards=[];fonts={};warnings=["pixel layers in grey, Lab or 32-bit formats"]
|
||||
patchy-lazy-placed.af dpi=72;spreads=1;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[]
|
||||
patchy-live-filter.af dpi=72;spreads=1;counts={"depth": 2, "fills": 2, "gradients": 0, "nodes": 4, "segments": 6, "shapes": 2, "strokes": 0, "subpaths": 2, "unsupported": 2};boards=[];fonts={};warnings=["adjustment layers", "unknown layers"]
|
||||
patchy-rgba16.af dpi=72;spreads=1;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[]
|
||||
patchy-rgba8.af dpi=72;spreads=1;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[]
|
||||
patchy-shapes-2.af dpi=72;spreads=1;counts={"depth": 1, "fills": 12, "gradients": 0, "nodes": 12, "segments": 168, "shapes": 12, "strokes": 0, "subpaths": 13};boards=[];fonts={};warnings=[]
|
||||
patchy-shapes.af dpi=72;spreads=1;counts={"depth": 1, "fills": 4, "gradients": 0, "nodes": 4, "segments": 28, "shapes": 4, "strokes": 0, "subpaths": 4};boards=[];fonts={};warnings=[]
|
||||
patchy-text-artistic.af dpi=72;spreads=1;counts={"depth": 1, "nodes": 1, "text_chars": 5, "text_runs": 1, "texts": 1};boards=[];fonts={"Arial:ArialMT:400:false"};warnings=[]
|
||||
patchy-text-caps.af dpi=72;spreads=1;counts={"depth": 1, "nodes": 2, "text_chars": 21, "text_runs": 2, "texts": 2};boards=[];fonts={"Arial:ArialNarrow:400:false"};warnings=["font width variants (exact face depends on the installed PostScript font) (2×)"]
|
||||
patchy-text-frame.af dpi=72;spreads=1;counts={"depth": 1, "nodes": 1, "text_chars": 11, "text_runs": 1, "texts": 1};boards=[];fonts={"Arial:ArialMT:400:false"};warnings=[]
|
||||
patchy-text-indent.af dpi=72;spreads=1;counts={"depth": 1, "nodes": 2, "text_chars": 104, "text_runs": 2, "texts": 2};boards=[];fonts={"Arial:ArialNarrow:400:false"};warnings=["font width variants (exact face depends on the installed PostScript font) (2×)"]
|
||||
patchy-text-para-spacing.af dpi=72;spreads=1;counts={"depth": 1, "nodes": 1, "text_chars": 13, "text_runs": 1, "texts": 1};boards=[];fonts={"Arial:ArialNarrow:400:false"};warnings=["font width variants (exact face depends on the installed PostScript font)"]
|
||||
patchy-text-rotated.af dpi=72;spreads=1;counts={"depth": 1, "nodes": 1, "text_chars": 7, "text_runs": 1, "texts": 1};boards=[];fonts={"Arial:ArialNarrow:400:false"};warnings=["font width variants (exact face depends on the installed PostScript font)"]
|
||||
patchy-text-runs.af dpi=72;spreads=1;counts={"depth": 1, "nodes": 1, "text_chars": 7, "text_runs": 5, "texts": 1};boards=[];fonts={"Arial:ArialNarrow:400:false", "Courier New:CourierNewPSMT:400:false", "Segoe UI Emoji:SegoeUIEmoji:400:false", "Times New Roman:TimesNewRomanPSMT:400:false"};warnings=["font width variants (exact face depends on the installed PostScript font)", "text uses a stored fallback font (imported with that font)"]
|
||||
patchy-transform.af dpi=72;spreads=1;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[]
|
||||
patchy-vector-mask.af dpi=72;spreads=1;counts={"depth": 1, "fills": 2, "gradients": 0, "nodes": 2, "segments": 7, "shapes": 2, "strokes": 0, "subpaths": 2, "vector_masks": 1};boards=[];fonts={};warnings=["unknown layers attached to other layers (imported without them)"]
|
||||
patchy-vector.af dpi=72;spreads=1;counts={"depth": 1, "fills": 3, "gradients": 0, "nodes": 4, "segments": 17, "shapes": 4, "strokes": 2, "subpaths": 5};boards=[];fonts={};warnings=[]
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
//! Structural regression signatures, measured from the pinned files through our own reader.
|
||||
//! These freeze feature retention; they are not independent visual or compatibility oracles.
|
||||
//! The model CRC covers every decoded field via its Debug representation (including paths,
|
||||
//! paint, masks, image pixels and text runs). A deliberate reader/Debug change needs review;
|
||||
//! input authenticity is independently checked with SHA256 by the corpus gate.
|
||||
//! They count retained features; they are not independent visual or compatibility oracles.
|
||||
//! Pixels are checked against the stored tiles in `raster.rs`. Input authenticity is checked
|
||||
//! with SHA256 by the corpus gate.
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use vectorcraft_affinity::model::{Document, Kind, Node};
|
||||
use vectorcraft_affinity::paint::Paint;
|
||||
@@ -58,11 +57,5 @@ pub fn signature(doc: &Document) -> String {
|
||||
for spread in &doc.spreads {
|
||||
visit(&spread.nodes, &mut counts, &mut fonts, &mut boards, 1);
|
||||
}
|
||||
let model_crc32 = crc32fast::hash(format!("{:?}", doc.spreads).as_bytes());
|
||||
format!(
|
||||
"dpi={};spreads={};model_crc32={model_crc32:08x};counts={counts:?};boards={boards:?};fonts={fonts:?};warnings={:?}",
|
||||
doc.dpi,
|
||||
doc.spreads.len(),
|
||||
doc.warnings
|
||||
)
|
||||
format!("dpi={};spreads={};counts={counts:?};boards={boards:?};fonts={fonts:?};warnings={:?}", doc.dpi, doc.spreads.len(), doc.warnings)
|
||||
}
|
||||
|
||||
@@ -894,7 +894,7 @@ fn trimmed_bristle_strands_read_pressure_where_they_begin() {
|
||||
}
|
||||
let (_, neutral_width) = start(neutral);
|
||||
let expected = 0.5 + x / 80.0;
|
||||
assert!(width / neutral_width > expected - 0.08, "strand at {x}: {width} vs {neutral_width}, expected ratio {expected}");
|
||||
assert!((width / neutral_width - expected).abs() < 0.02, "strand at {x}: {width} vs {neutral_width}, expected ratio {expected}");
|
||||
checked = true;
|
||||
}
|
||||
assert!(checked, "at least one strand begins past the pressure ramp's first eighth");
|
||||
@@ -1967,7 +1967,8 @@ fn pressure_varies_angle_and_roundness() {
|
||||
let b = Brush { name: "r".into(), kind: BrushKind::Calligraphic(vertical.clone()) };
|
||||
bounds(&stroke_pieces(&Document::new(1.0, 1.0), &b, &line(0.0, 0.0, 0.0, 100.0), &pressed(vec![(0.0, p), (1.0, p)]))).width()
|
||||
};
|
||||
assert!(near(wide(0.0), 0.1, 0.05), "{}", wide(0.0));
|
||||
// Roundness 1% of the 10 pt size.
|
||||
assert!(near(wide(0.0), 0.1, 1e-6), "{}", wide(0.0));
|
||||
assert!(near(wide(1.0), 10.0, 0.05), "{}", wide(1.0));
|
||||
// The angle turns on past 180°: 170 + 40 is 210°, the nib at 30° (not stopped at 180°).
|
||||
let turned = Calligraphic { angle: 170.0, roundness: 10.0, variation: [40.0, 0.0, 0.0], ..c([Pressure, Fixed, Fixed]) };
|
||||
@@ -2219,7 +2220,10 @@ fn brushes_without_modes_vary_randomly_as_before() {
|
||||
serde_json::to_value(Variation::ALL).unwrap(),
|
||||
serde_json::json!(["fixed", "random", "pressure", "tilt", "bearing", "rotation", "stylusWheel"])
|
||||
);
|
||||
assert!(Variation::ALL.iter().all(|v| Variation::parse(v.id()) == Some(*v) && serde_json::to_value(v).unwrap() == v.id()));
|
||||
let ids: Vec<&str> = Variation::ALL.iter().map(|v| v.id()).collect();
|
||||
assert_eq!(serde_json::to_value(Variation::ALL).unwrap(), serde_json::json!(ids), "saved names are the ids");
|
||||
assert_eq!(Variation::parse("stylusWheel"), Some(Variation::StylusWheel));
|
||||
assert_eq!(Variation::parse("wheel"), None);
|
||||
assert!(!Variation::offered(false).contains(&Variation::StylusWheel) && Variation::offered(true).contains(&Variation::StylusWheel));
|
||||
}
|
||||
|
||||
@@ -2227,6 +2231,7 @@ fn brushes_without_modes_vary_randomly_as_before() {
|
||||
#[test]
|
||||
fn junk_pressure_brushes_draw_finite_art() {
|
||||
let bp = preview_path(120.0, 24.0);
|
||||
let mut drawn = 0;
|
||||
for (size, var) in [(1e308, 1e308), (-1e308, 1e308), (0.0, -1e308), (f64::MAX, f64::MAX)] {
|
||||
for profile in [vec![], vec![(0.0, 2.0), (0.0, -1.0), (5.0, 0.5)], vec![(1.0, 1.0), (0.0, 0.0)]] {
|
||||
let out = stroke_pieces(&Document::new(1.0, 1.0), &pressure_calli(size, var), &bp, &pressed(profile));
|
||||
@@ -2235,8 +2240,10 @@ fn junk_pressure_brushes_draw_finite_art() {
|
||||
all_points(n, &mut pts);
|
||||
}
|
||||
assert!(pts.iter().all(|p| p.x.is_finite() && p.y.is_finite()), "{size} {var}");
|
||||
drawn += usize::from(!pts.is_empty());
|
||||
}
|
||||
}
|
||||
assert_eq!(drawn, 12, "brushes that draw");
|
||||
}
|
||||
|
||||
/// A scatter brush of 10 × 4 pt rectangles whose size goes from `lo` % to `hi` % as `mode` says.
|
||||
|
||||
@@ -131,7 +131,7 @@ fn pens_pick_colors_and_widths() {
|
||||
let i = plot("IN;SP1;PW1;PD0,0,10,0;PU;PW2,2;SP2;PD0,10,10,10;PU;SP1;PD0,20,10,20;PU;IN;SP1;PD0,30,10,30;");
|
||||
let widths: Vec<f64> = leaves(&i.document).iter().map(|n| stroke(n).width).collect();
|
||||
let want = [MM, 2.0 * MM, MM, 0.35 * MM];
|
||||
assert!(widths.iter().zip(want).all(|(a, b)| (a - b).abs() < 1e-9), "{widths:?}");
|
||||
assert!(widths.len() == want.len() && widths.iter().zip(want).all(|(a, b)| (a - b).abs() < 1e-9), "{widths:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
+98
-7
@@ -1448,7 +1448,8 @@ fn crop_keeps_an_instance_whose_art_reaches_the_region() {
|
||||
let art = path(&mut d, shapes::rectangle(Rect::new(100.0, 50.0, 140.0, 90.0)), Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0);
|
||||
d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Far".into(), art: Arc::new(art) });
|
||||
let o = DxfOptions { crop: true, ..opts(&d) };
|
||||
assert!(!kinds(&export(&d, &o).unwrap()).is_empty());
|
||||
// The red fill: its outline and its hatch.
|
||||
assert_eq!(kinds(&export(&d, &o).unwrap()), ["LWPOLYLINE", "HATCH"]);
|
||||
}
|
||||
|
||||
/// An instance stained blue by its fill writes its symbol's red art in blue, as the canvas draws it.
|
||||
@@ -1543,13 +1544,103 @@ fn export_bytes_match_shared_writer_goldens() {
|
||||
let out = export(&doc, &DxfOptions { version, ..opts(&doc) }).unwrap();
|
||||
let got = std::str::from_utf8(&out.bytes).expect("UTF-8 DXF");
|
||||
let path = dir.join(name);
|
||||
if std::env::var_os("WRITE_DXF_GOLDENS").is_some() {
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
std::fs::write(&path, got).unwrap();
|
||||
continue;
|
||||
}
|
||||
let expected = std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("read {}: {e}", path.display()));
|
||||
assert_eq!(got, expected, "DXF bytes changed versus {}", path.display());
|
||||
assert_holds_shapes_doc(&expected, version);
|
||||
if got != expected {
|
||||
// Written for review only; a golden file changes by hand after its drawing checks pass.
|
||||
let actual = std::env::temp_dir().join(format!("{name}.actual"));
|
||||
let saved = std::fs::write(&actual, got).map_or_else(|e| format!("not saved: {e}"), |()| format!("saved to {}", actual.display()));
|
||||
panic!("DXF bytes changed versus {} (output {saved})", path.display());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Checks that a golden file holds [`shapes_doc`] as the DXF Reference describes it, in a 200 × 100 pt
|
||||
/// region with y up: the red fill and the black 1 pt stroke of the rectangle (10, 40)–(110, 90), and
|
||||
/// the blue 2 pt circle of radius 30 around (150, 50). ACI colors 1, 5 and 7 are red, blue and
|
||||
/// black/white; code 420 holds 0xRRGGBB; code 370 is lineweight in hundredths of a millimeter
|
||||
/// (1 pt = 0.3528 mm gives 35, 2 pt gives 70); a POLYLINE vertex's bulge is tan(arc angle / 4).
|
||||
fn assert_holds_shapes_doc(golden: &str, version: DxfVersion) {
|
||||
let ents = section(&pairs(golden.as_bytes()), "ENTITIES");
|
||||
let colored = |aci: &str| -> Vec<&Pairs> { ents.iter().filter(|e| get(e, 62) == Some(aci)).collect() };
|
||||
// Every drawn point of the entities in one color; (0, 0) is the elevation point of POLYLINE
|
||||
// and HATCH headers, which no shape of the drawing reaches.
|
||||
let points = |aci: &str| -> Vec<(f64, f64)> {
|
||||
colored(aci).iter().flat_map(|e| all(e, 10).into_iter().zip(all(e, 20))).filter(|p| *p != (0.0, 0.0)).collect()
|
||||
};
|
||||
let bbox = |pts: &[(f64, f64)]| {
|
||||
pts.iter().fold((f64::MAX, f64::MAX, f64::MIN, f64::MIN), |b, p| (b.0.min(p.0), b.1.min(p.1), b.2.max(p.0), b.3.max(p.1)))
|
||||
};
|
||||
for aci in ["1", "7"] {
|
||||
let pts = points(aci);
|
||||
assert_eq!(pts.len() % 4, 0, "{version:?} ACI {aci}: rectangle corners {pts:?}");
|
||||
assert_eq!(bbox(&pts), (10.0, 40.0, 110.0, 90.0), "{version:?} ACI {aci}");
|
||||
// Each run of four points is one outline of the rectangle: all four corners, each joined to
|
||||
// the next (and the last to the first) by a horizontal or vertical edge.
|
||||
let corners = [(10.0, 40.0), (110.0, 40.0), (110.0, 90.0), (10.0, 90.0)];
|
||||
for quad in pts.chunks(4) {
|
||||
assert!(corners.iter().all(|c| quad.contains(c)), "{version:?} ACI {aci}: corners {quad:?}");
|
||||
for (i, a) in quad.iter().enumerate() {
|
||||
let b = quad[(i + 1) % 4];
|
||||
assert!((a.0 == b.0) != (a.1 == b.1), "{version:?} ACI {aci}: edge {a:?} to {b:?} in {quad:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
let circle = colored("5");
|
||||
assert!(!circle.is_empty(), "{version:?}: the blue circle");
|
||||
if let Some(c) = circle.iter().find(|e| kind(e) == "CIRCLE") {
|
||||
assert_eq!((all(c, 10), all(c, 20), all(c, 40)), (vec![150.0], vec![50.0], vec![30.0]), "{version:?}");
|
||||
} else {
|
||||
let pts = points("5");
|
||||
assert!(pts.len() >= 2, "{version:?}: circle vertices {pts:?}");
|
||||
for (x, y) in &pts {
|
||||
assert!(((x - 150.0).hypot(y - 50.0) - 30.0).abs() < 1e-4, "{version:?}: vertex ({x}, {y}) off the circle");
|
||||
}
|
||||
let turn: f64 = circle.iter().flat_map(|e| all(e, 42)).map(|b| 4.0 * b.atan()).sum();
|
||||
assert!((turn.abs() - std::f64::consts::TAU).abs() < 1e-4, "{version:?}: bulges sweep {turn} rad");
|
||||
// Each segment, the closing one included, is an arc of the circle: the point halfway along it,
|
||||
// which lies bulge × chord / 2 to the right of the chord's middle, is on the circle too.
|
||||
let mut verts: Vec<((f64, f64), f64)> = Vec::new();
|
||||
for e in &circle {
|
||||
let mut x = None;
|
||||
for (c, v) in e.iter() {
|
||||
let n = || v.trim().parse::<f64>().expect("a number");
|
||||
match c {
|
||||
10 => x = Some(n()),
|
||||
20 => {
|
||||
let p = (x.take().unwrap_or(f64::NAN), n());
|
||||
if p != (0.0, 0.0) {
|
||||
verts.push((p, 0.0));
|
||||
}
|
||||
}
|
||||
42 => {
|
||||
if let Some(last) = verts.last_mut() {
|
||||
last.1 = n();
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
for (i, &((px, py), b)) in verts.iter().enumerate() {
|
||||
let (qx, qy) = verts[(i + 1) % verts.len()].0;
|
||||
let (mx, my) = (px + (qx - px) / 2.0 + b * (qy - py) / 2.0, py + (qy - py) / 2.0 - b * (qx - px) / 2.0);
|
||||
assert!(
|
||||
((mx - 150.0).hypot(my - 50.0) - 30.0).abs() < 1e-4,
|
||||
"{version:?}: segment ({px}, {py}) to ({qx}, {qy}) with bulge {b} leaves the circle at ({mx}, {my})"
|
||||
);
|
||||
}
|
||||
}
|
||||
if version >= DxfVersion::R2000 {
|
||||
let code = |aci: &str, c: i32| -> Vec<String> { colored(aci).iter().filter_map(|e| get(e, c)).map(str::to_string).collect() };
|
||||
assert!(code("1", 420).iter().all(|v| v == "16711680") && !code("1", 420).is_empty(), "{version:?}: red true color");
|
||||
assert_eq!(code("7", 420), ["0"], "{version:?}: black true color");
|
||||
assert_eq!(code("5", 420), ["255"], "{version:?}: blue true color");
|
||||
assert_eq!(code("7", 370), ["35"], "{version:?}: 1 pt stroke");
|
||||
assert_eq!(code("5", 370), ["70"], "{version:?}: 2 pt stroke");
|
||||
} else {
|
||||
let stroke = colored("7");
|
||||
assert_eq!((all(stroke[0], 40), all(stroke[0], 41)), (vec![1.0], vec![1.0]), "{version:?}: 1 pt polyline width");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -313,8 +313,10 @@ mod tests {
|
||||
assert_eq!(BlendMode::parse("ColorBurn"), Some(BlendMode::ColorBurn));
|
||||
assert_eq!(BlendMode::parse("soft_light"), Some(BlendMode::SoftLight));
|
||||
assert_eq!(BlendMode::parse("nope"), None);
|
||||
for m in BlendMode::ALL {
|
||||
assert_eq!(BlendMode::parse(m.label()), Some(m));
|
||||
}
|
||||
assert_eq!(BlendMode::parse(""), None);
|
||||
// A label that starts another one names its own mode.
|
||||
assert_eq!(BlendMode::parse("Color"), Some(BlendMode::Color));
|
||||
assert_eq!(BlendMode::parse("Color Dodge"), Some(BlendMode::ColorDodge));
|
||||
assert_eq!(BlendMode::parse("HARD-LIGHT"), Some(BlendMode::HardLight));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,11 +15,14 @@ fn de(a: [f32; 3], b: [f32; 3]) -> f32 {
|
||||
|
||||
#[test]
|
||||
fn intents_parse_and_name() {
|
||||
for i in Intent::ALL {
|
||||
assert_eq!(Intent::parse(i.id()), Some(i));
|
||||
assert_eq!(Intent::parse(i.label()), Some(i));
|
||||
}
|
||||
// The id settings save and the label the menu shows both read back, in any case and spacing.
|
||||
assert_eq!(Intent::RelativeColorimetric.id(), "relative");
|
||||
assert_eq!(Intent::parse("relative"), Some(Intent::RelativeColorimetric));
|
||||
assert_eq!(Intent::parse("Relative Colorimetric"), Some(Intent::RelativeColorimetric));
|
||||
assert_eq!(Intent::parse("absolute_colorimetric"), Some(Intent::AbsoluteColorimetric));
|
||||
assert_eq!(Intent::parse("PERCEPTUAL"), Some(Intent::Perceptual));
|
||||
assert_eq!(Intent::parse("bogus"), None);
|
||||
assert_eq!(Intent::parse(""), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -322,21 +325,29 @@ fn bad_icc_rejected() {
|
||||
assert!(matches!(register_icc(b"not a profile", None), Err(CmsError::BadProfile(_))));
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
/// A profile file is read and registered as its bytes are: a missing file is an I/O error naming
|
||||
/// the path, a file that is not a profile is refused as one, and a file holding a built-in
|
||||
/// profile is refused for its name.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn loads_system_cmyk_icc() {
|
||||
let path = std::path::Path::new("/System/Library/ColorSync/Profiles/Generic CMYK Profile.icc");
|
||||
if !path.exists() {
|
||||
return;
|
||||
fn loads_icc_files_and_refuses_bad_ones() {
|
||||
let dir = std::env::temp_dir().join(format!("vectorcraft-color-icc-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let missing = dir.join("missing.icc");
|
||||
match load_icc_file(&missing) {
|
||||
Err(CmsError::Io(e)) => assert!(e.contains("missing.icc"), "{e}"),
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
let info = load_icc_file(path).unwrap();
|
||||
assert_eq!(info.kind, ProfileKind::Cmyk);
|
||||
assert!(profiles().iter().any(|p| p.name == info.name && !p.builtin));
|
||||
let c = Cms::new(&ColorSettings { cmyk: info.name.clone(), ..Default::default() }).unwrap();
|
||||
let rgb = [0.7, 0.5, 0.4];
|
||||
let back = c.cmyk_to_srgb(c.srgb_to_cmyk(rgb, Intent::RelativeColorimetric), false);
|
||||
assert!(de(rgb, back) < 5.0, "{back:?}");
|
||||
assert_eq!(c.cmyk_to_srgb([0.0; 4], false).map(|v| (v * 255.0).round() as u8), [255, 255, 255]);
|
||||
let junk = dir.join("junk.icc");
|
||||
std::fs::write(&junk, b"not a profile").unwrap();
|
||||
assert!(matches!(load_icc_file(&junk), Err(CmsError::BadProfile(_))));
|
||||
let builtin = dir.join("generic.icc");
|
||||
std::fs::write(&builtin, &*icc_bytes(GENERIC_CMYK).unwrap()).unwrap();
|
||||
match load_icc_file(&builtin) {
|
||||
Err(CmsError::Unsupported(e)) => assert!(e.contains("built-in"), "{e}"),
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
/// With black-point compensation, sRGB black separates to the press's black point and that black
|
||||
@@ -568,10 +579,10 @@ fn a_document_gets_the_same_context_for_the_same_profiles() {
|
||||
/// settings saved before the policies existed read with the default policy.
|
||||
#[test]
|
||||
fn policies_parse_and_default_in_saved_settings() {
|
||||
for p in Policy::CMYK {
|
||||
assert_eq!(Policy::parse(p.id()), Some(p));
|
||||
}
|
||||
assert_eq!(Policy::parse("preserveNumbers"), Some(Policy::PreserveNumbers));
|
||||
assert_eq!(Policy::parse("convert"), Some(Policy::Convert));
|
||||
assert_eq!(Policy::parse("bogus"), None);
|
||||
assert_eq!(Policy::parse("Preserve Numbers"), None, "only ids parse");
|
||||
assert!(!Policy::RGB.contains(&Policy::PreserveNumbers));
|
||||
let old: ColorSettings =
|
||||
serde_json::from_str(r#"{"rgb": "sRGB IEC61966-2.1", "cmyk": "Device CMYK (uncalibrated)", "intent": "perceptual", "bpc": false}"#).unwrap();
|
||||
|
||||
@@ -395,5 +395,5 @@ fn cmyk_to_cmyk_compensates_the_black_point() {
|
||||
assert_ne!(convert(true), convert(false));
|
||||
// White is untouched.
|
||||
let white = generic.to_same_model_of(&device, &[0.0; 4], rel, true).unwrap();
|
||||
assert!(white.iter().all(|v| *v < 0.01), "{white:?}");
|
||||
assert!(white.len() == 4 && white.iter().all(|v| *v < 0.01), "{white:?}");
|
||||
}
|
||||
|
||||
@@ -108,6 +108,7 @@ fn the_fit_predicts_patches_it_left_out() {
|
||||
let corner = |p: &measured::Patch| p.cmyk.iter().all(|v| *v == 0.0 || *v == 1.0);
|
||||
let first = |p: &measured::Patch| patches.iter().position(|q| q.cmyk == p.cmyk).unwrap_or(0);
|
||||
let (kept, left): (Vec<&measured::Patch>, Vec<_>) = patches.iter().partition(|p| first(p) % 4 != 3 || corner(p));
|
||||
assert!(!left.is_empty(), "{}: nothing left out", c.reference);
|
||||
assert!(left.iter().all(|l| kept.iter().all(|k| k.cmyk != l.cmyk)), "{}", c.reference);
|
||||
let kept: Vec<measured::Patch> = kept.into_iter().copied().collect();
|
||||
let left: Vec<measured::Patch> = left.into_iter().copied().collect();
|
||||
|
||||
@@ -685,7 +685,9 @@ mod tests {
|
||||
let mid = f.split_line(0, 0, 0.5).unwrap();
|
||||
assert_eq!((mid, &f.lines[0]), (3, &vec![0, 3, 1, 2]));
|
||||
let p = f.points[3];
|
||||
assert!(p.at.y.abs() < 1e-9 && p.at.x > 0.0 && p.at.x < 100.0 && (p.opacity - 0.75).abs() < 1e-6, "on the curve, half way: {p:?}");
|
||||
// The Catmull-Rom segment from (0, 0) to (100, 0), with (200, 0) after it, is at x = 43.75
|
||||
// half way, not at the straight line's 50.
|
||||
assert!(p.at.y.abs() < 1e-9 && (p.at.x - 43.75).abs() < 1e-9 && (p.opacity - 0.75).abs() < 1e-6, "on the curve, half way: {p:?}");
|
||||
assert!(f.remove_point(1));
|
||||
assert_eq!(f.lines, vec![vec![0, 2, 1]]);
|
||||
assert!(f.add_line(vec![0, 9]).is_err() && f.add_line(vec![0]).is_err());
|
||||
|
||||
@@ -464,9 +464,10 @@ impl Gradient {
|
||||
self.repeats.clamp(1, MAX_REPEATS)
|
||||
}
|
||||
/// Does it paint something other than its end colors past the ends of its stops, or run its
|
||||
/// stops more than once: a linear, radial, conic or diamond gradient that repeats or reflects?
|
||||
/// stops more than once: a linear, radial, conic or diamond gradient with stops that repeats or
|
||||
/// reflects? One without stops paints as one that pads.
|
||||
pub fn is_spread(&self) -> bool {
|
||||
!self.spread.is_pad() && self.kind != GradientKind::Freeform
|
||||
!self.spread.is_pad() && self.kind != GradientKind::Freeform && !self.stops.is_empty()
|
||||
}
|
||||
/// The spread and count as the gradient paints them: Pad and 1 for one that pads (whatever
|
||||
/// count it keeps) and for a freeform one, else its spread and [`Self::repeat_count`]. Equal
|
||||
|
||||
@@ -36,6 +36,10 @@ fn spread_maps_the_parameter_to_a_place_along_the_stops() {
|
||||
let free = spread(GradientKind::Freeform, GradientSpread::Repeat, 3);
|
||||
assert_eq!(free.spread_param(0.7), 0.7);
|
||||
assert!(!free.is_spread() && !pad.is_spread() && repeat.is_spread());
|
||||
// Without stops it paints as one that pads.
|
||||
let empty = Gradient { stops: vec![], ..repeat.clone() };
|
||||
assert!(!empty.is_spread());
|
||||
assert_eq!(empty.painted_spread(), (GradientSpread::Pad, 1));
|
||||
assert!(repeat.spread_param(f64::NAN).is_nan());
|
||||
// A count out of range (set in code) counts as the nearest one in range.
|
||||
assert_eq!(spread(GradientKind::Linear, GradientSpread::Repeat, 0).repeat_count(), 1);
|
||||
|
||||
@@ -184,6 +184,7 @@ fn reverse_mirrors_midpoints() {
|
||||
r.reverse();
|
||||
let mids: Vec<f32> = r.stops.iter().map(|s| s.midpoint).collect();
|
||||
let want: Vec<f32> = g.stops.iter().rev().skip(1).map(|s| 1.0 - s.midpoint).chain([0.5]).collect();
|
||||
assert_eq!(mids.len(), g.stops.len(), "reversing keeps every stop");
|
||||
assert!(mids.iter().zip(&want).all(|(a, b)| (a - b).abs() < 1e-6), "{mids:?} {want:?}");
|
||||
for i in 0..=20 {
|
||||
let t = i as f32 / 20.0;
|
||||
@@ -291,6 +292,7 @@ fn remove_keeps_two() {
|
||||
fn move_reorders_and_tracks_index() {
|
||||
let g = g3();
|
||||
let (v, i) = move_stop(&g.stops, 0, 0.8);
|
||||
assert_eq!(v.len(), g.stops.len(), "moving keeps every stop");
|
||||
assert_eq!(i, 1);
|
||||
assert_eq!(v[1].color.to_hex(), "#ffffff");
|
||||
assert!(v.windows(2).all(|w| w[0].offset <= w[1].offset));
|
||||
@@ -1176,7 +1178,8 @@ fn a_conic_with_no_extent_or_bad_numbers_still_sweeps() {
|
||||
assert!(t(90.0, 50.0).abs() < 1e-12, "{g:?}");
|
||||
assert!((t(50.0, 90.0) - 0.25).abs() < 1e-12, "{g:?}");
|
||||
let wedges = g.conic_wedges(Rect::new(0.0, 0.0, 100.0, 100.0), 4, false);
|
||||
assert!(wedges.iter().flat_map(|(pts, _)| pts).all(|p| p.is_finite()), "{g:?}");
|
||||
assert_eq!(wedges.len(), 4, "{g:?}");
|
||||
assert!(wedges.iter().all(|(pts, _)| pts.len() >= 3 && pts.iter().all(|p| p.is_finite())), "{g:?}: {wedges:?}");
|
||||
}
|
||||
// A flat extent keeps the vector's direction and the sign of its aspect.
|
||||
let down = GradientGeom { end: Point::new(50.0, 80.0), ..conic_at(c, 30.0, 0.0) };
|
||||
@@ -1379,7 +1382,7 @@ fn diamond_pixels_follow_the_squares() {
|
||||
g.geom = Some(diamond_at(Point::new(2.5, 2.5), 2.5, 1.0));
|
||||
let px: Vec<[u8; 4]> = g.pixels(b, b, 5, 5, false, &Color::to_rgb).collect();
|
||||
// White at the center, black in the corners, and the same on each side of it.
|
||||
assert!(px[2 * 5 + 2][0] > 200 && px[0][0] < 10 && px[24][0] < 10, "{px:?}");
|
||||
assert_eq!((px[2 * 5 + 2], px[0], px[24]), ([255, 255, 255, 255], [0, 0, 0, 255], [0, 0, 0, 255]), "{px:?}");
|
||||
assert_eq!(px[2 * 5 + 1], px[2 * 5 + 3]);
|
||||
assert_eq!(px[5 + 2], px[3 * 5 + 2]);
|
||||
assert_eq!(px[2 * 5 + 1], px[5 + 2]);
|
||||
|
||||
@@ -177,20 +177,23 @@ mod tests {
|
||||
fn harmonies_keep_the_base_model() {
|
||||
let base = Color::cmyk(0.0, 1.0, 1.0, 0.0);
|
||||
for h in Harmony::ALL {
|
||||
assert!(apply(h, base).iter().all(|c| matches!(c, Color::Cmyk { .. })), "{}", label(h));
|
||||
let colors = apply(h, base);
|
||||
assert!(colors.len() >= 2 && colors.iter().all(|c| matches!(c, Color::Cmyk { .. })), "{}: {colors:?}", label(h));
|
||||
}
|
||||
let Color::Cmyk { c, m, y, .. } = apply(Harmony::Complementary, base)[1] else { panic!("a CMYK complement") };
|
||||
assert!(c > m && c > y, "the complement of red is a cyan: {c} {m} {y}");
|
||||
let g = Guide::new(Color::gray(0.4), Harmony::Triad, &GuideOptions::default());
|
||||
assert!(g.grid.iter().flatten().all(|c| matches!(c, Color::Gray { .. })));
|
||||
let cells: Vec<&Color> = g.grid.iter().flatten().collect();
|
||||
assert!(!cells.is_empty() && cells.iter().all(|c| matches!(c, Color::Gray { .. })), "{cells:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rules_parse_by_id_and_label() {
|
||||
for h in Harmony::ALL {
|
||||
assert_eq!(parse(h.id()), Some(h));
|
||||
assert_eq!(parse(label(h)), Some(h));
|
||||
}
|
||||
// A label reads back as its rule, its spaces and case ignored, and so does an id.
|
||||
assert_eq!(parse("Split Complementary"), Some(Harmony::SplitComplementary));
|
||||
assert_eq!(parse("high contrast 3"), Some(Harmony::HighContrast3));
|
||||
assert_eq!(parse("tetrad2"), Some(Harmony::Tetrad2));
|
||||
assert_eq!(parse(""), None);
|
||||
assert_eq!(Harmony::SplitComplementary.id(), "splitComplementary");
|
||||
assert_eq!(Harmony::HighContrast3.id(), "highContrast3");
|
||||
assert_eq!(parse("square"), None);
|
||||
|
||||
@@ -825,16 +825,4 @@ mod tests {
|
||||
let [l, ..] = to_oklab(&stop("Violet Edge", 4));
|
||||
assert!(l < 0.5 && to_oklab(&stop("Prism Veil", 2))[0] > 0.95, "{l}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_other_libraries_keep_classic_mixing_and_centered_midpoints() {
|
||||
for b in builtins().filter(|b| !["organic-fades", "holographic"].contains(&b.id)) {
|
||||
for s in builtin_library(b.id).unwrap().iter() {
|
||||
if let Paint::Gradient(g) = &s.paint {
|
||||
assert_eq!(g.gradient.method, GradientMethod::Classic, "{}", s.name);
|
||||
assert!(g.gradient.stops.iter().all(|st| st.midpoint == 0.5), "{}", s.name);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -796,12 +796,12 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn methods_parse_by_id_and_label() {
|
||||
for m in Method::ALL {
|
||||
assert_eq!(Method::parse(m.id()), Some(m));
|
||||
assert_eq!(Method::parse(m.label()), Some(m));
|
||||
}
|
||||
assert_eq!(Method::parse("preserveTints"), Some(Method::PreserveTints));
|
||||
assert_eq!(Method::parse("Hue Shift"), Some(Method::HueShift));
|
||||
assert_eq!(Method::parse("Tints and Shades"), Some(Method::TintsShades));
|
||||
assert_eq!(Method::parse("tints & shades"), Some(Method::TintsShades));
|
||||
assert_eq!(Method::parse("nope"), None);
|
||||
assert_eq!(Method::parse(""), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -186,13 +186,20 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn default_swatches_parse() {
|
||||
// `solid`/`grad` fall back to black or white on a bad literal instead of panicking; make sure
|
||||
// none falls back.
|
||||
let src = include_str!("swatch.rs");
|
||||
let hexes: Vec<&str> = src.split('"').filter(|t| t.starts_with('#') && t.len() == 7).collect();
|
||||
assert!(hexes.len() > 30);
|
||||
for h in hexes {
|
||||
assert!(Color::from_hex(h).is_some(), "{h}");
|
||||
}
|
||||
// `solid` and `grad` fall back to black or white on a bad hex literal. A fallback gives a
|
||||
// solid the color of Black or White, and a gradient a stop that differs from the swatch
|
||||
// its hex literal names.
|
||||
let (s, g) = default_swatches(Model::Rgb);
|
||||
let solids: Vec<Color> = s.iter().chain(g.iter().flat_map(|g| &g.swatches)).filter_map(|w| w.paint.color()).collect();
|
||||
assert!(solids.len() > 40, "{}", solids.len());
|
||||
let repeated: Vec<&Color> = solids.iter().enumerate().filter(|(i, c)| solids[..*i].contains(c)).map(|(_, c)| c).collect();
|
||||
assert_eq!(repeated, Vec::<&Color>::new(), "colors of more than one default swatch");
|
||||
let color = |name: &str| s.iter().find(|w| w.name == name).and_then(|w| w.paint.color());
|
||||
let stops = |name: &str| match s.iter().find(|w| w.name == name).map(|w| &w.paint) {
|
||||
Some(Paint::Gradient(gp)) => gp.gradient.stops.iter().map(|st| Some(st.color)).collect::<Vec<_>>(),
|
||||
other => panic!("{name}: {other:?}"),
|
||||
};
|
||||
assert_eq!(stops("Sunset"), [color("Amber"), color("Rose")]);
|
||||
assert_eq!(stops("Ocean"), [color("Cyan"), color("Blue")]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -208,10 +208,11 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn category_ids_parse_back() {
|
||||
for c in Category::ALL {
|
||||
assert_eq!(Category::parse(c.id()), Some(c));
|
||||
}
|
||||
// Commands and saved settings name a category by its id, exactly.
|
||||
assert_eq!(Category::parse("largeText"), Some(Category::LargeText));
|
||||
assert_eq!(Category::parse("graphics"), Some(Category::Graphics));
|
||||
assert_eq!(Category::parse("NormalText"), None);
|
||||
assert_eq!(Category::parse("Large Text"), None, "a label is not an id");
|
||||
}
|
||||
|
||||
fn hue(srgb: [f32; 3]) -> f64 {
|
||||
|
||||
+17
-3
@@ -2784,10 +2784,13 @@ mod tests {
|
||||
Paint::Gradient(Box::new(GradientPaint::new(Gradient { stops, ..Gradient::default() })))
|
||||
};
|
||||
let Paint::Gradient(m) = lerp_paint(&spot_gradient(0.2), &spot_gradient(1.0), 0.5) else { panic!() };
|
||||
assert_eq!(m.gradient.stops.len(), 2);
|
||||
assert!(m.gradient.stops.iter().all(|s| s.swatch.as_deref() == Some("Spot") && (s.tint - 0.6).abs() < 1e-6), "{:?}", m.gradient.stops);
|
||||
let Paint::Gradient(m) = lerp_paint(&tinted(0.2), &spot_gradient(1.0), 0.5) else { panic!() };
|
||||
assert_eq!(m.gradient.stops.len(), 2);
|
||||
assert!(m.gradient.stops.iter().all(|s| s.swatch.as_deref() == Some("Spot") && (s.tint - 0.6).abs() < 1e-6), "{:?}", m.gradient.stops);
|
||||
let Paint::Gradient(m) = lerp_paint(&Paint::solid(Color::BLACK), &spot_gradient(1.0), 0.5) else { panic!() };
|
||||
assert_eq!(m.gradient.stops.len(), 2);
|
||||
assert!(m.gradient.stops.iter().all(|s| s.swatch.is_none()), "{:?}", m.gradient.stops);
|
||||
}
|
||||
|
||||
@@ -2840,6 +2843,7 @@ mod tests {
|
||||
let a = gradient_paint(vec![spot_stop(0.0, 0.2, Some(p)), spot_stop(1.0, 0.2, Some(p))]);
|
||||
let b = gradient_paint(vec![spot_stop(0.0, 1.0, Some(q)), spot_stop(1.0, 1.0, Some(q))]);
|
||||
let Paint::Gradient(m) = lerp_paint(&a, &b, 0.25) else { panic!() };
|
||||
assert_eq!(m.gradient.stops.len(), 2);
|
||||
for s in &m.gradient.stops {
|
||||
assert_eq!(s.swatch.as_deref(), Some("Spot"));
|
||||
assert!((s.tint - 0.4).abs() < 1e-6, "{}", s.tint);
|
||||
@@ -2848,6 +2852,7 @@ mod tests {
|
||||
// Without plates on either side the steps print the spot ink alone, as before.
|
||||
let bare = |tint| gradient_paint(vec![spot_stop(0.0, tint, None), spot_stop(1.0, tint, None)]);
|
||||
let Paint::Gradient(m) = lerp_paint(&bare(0.2), &bare(1.0), 0.5) else { panic!() };
|
||||
assert_eq!(m.gradient.stops.len(), 2);
|
||||
assert!(m.gradient.stops.iter().all(|s| s.plates.is_none()), "{:?}", m.gradient.stops);
|
||||
}
|
||||
|
||||
@@ -2882,10 +2887,12 @@ mod tests {
|
||||
let with = gradient_paint(vec![spot_stop(0.0, 1.0, Some(p)), spot_stop(1.0, 1.0, Some(p))]);
|
||||
let without = gradient_paint(vec![spot_stop(0.0, 1.0, None), spot_stop(1.0, 1.0, None)]);
|
||||
let Paint::Gradient(m) = lerp_paint(&without, &with, 0.25) else { panic!() };
|
||||
assert_eq!(m.gradient.stops.len(), 2);
|
||||
assert!(m.gradient.stops.iter().all(|s| s.swatch.as_deref() == Some("Spot")), "{:?}", m.gradient.stops);
|
||||
m.gradient.stops.iter().for_each(|s| assert_plates(s.plates, [0.1, 0.2, 0.0, 0.05]));
|
||||
// The ends keep their own plates.
|
||||
let Paint::Gradient(m) = lerp_paint(&without, &with, 0.0) else { panic!() };
|
||||
assert_eq!(m.gradient.stops.len(), 2);
|
||||
assert!(m.gradient.stops.iter().all(|s| s.plates.is_none()), "{:?}", m.gradient.stops);
|
||||
|
||||
// Another swatch, or an unlinked stop: process steps with no plates, as before.
|
||||
@@ -2897,6 +2904,7 @@ mod tests {
|
||||
let plain = gradient_paint(vec![plain.clone(), GradientStop { offset: 1.0, ..plain }]);
|
||||
for b in [&other, &plain] {
|
||||
let Paint::Gradient(m) = lerp_paint(&with, b, 0.5) else { panic!() };
|
||||
assert_eq!(m.gradient.stops.len(), 2);
|
||||
assert!(m.gradient.stops.iter().all(|s| s.swatch.is_none() && s.plates.is_none()), "{:?}", m.gradient.stops);
|
||||
}
|
||||
}
|
||||
@@ -2906,11 +2914,14 @@ mod tests {
|
||||
let p = [0.4, 0.8, 0.0, 0.2];
|
||||
let gradient = gradient_paint(vec![spot_stop(0.0, 1.0, Some(p)), spot_stop(1.0, 1.0, Some(p))]);
|
||||
let Paint::Gradient(g) = &gradient else { panic!() };
|
||||
assert!(solid_gradient(Color::BLACK, Some("Spot"), 0.2, &g.gradient).stops.iter().all(|s| s.plates.is_none()));
|
||||
let linked = solid_gradient(Color::BLACK, Some("Spot"), 0.2, &g.gradient);
|
||||
assert_eq!(linked.stops.len(), 2);
|
||||
assert!(linked.stops.iter().all(|s| s.plates.is_none() && s.swatch.as_deref() == Some("Spot") && s.tint == 0.2), "{:?}", linked.stops);
|
||||
let solid = Paint::Solid { color: Color::cmyk(1.0, 0.7, 0.0, 0.4).tinted(0.2), swatch: Some("Spot".into()), tint: 0.2 };
|
||||
// The solid's end has no plates: they grow from none toward the gradient's, both ways round.
|
||||
for (a, b, t) in [(&solid, &gradient, 0.25), (&gradient, &solid, 0.75)] {
|
||||
let Paint::Gradient(m) = lerp_paint(a, b, t) else { panic!() };
|
||||
assert_eq!(m.gradient.stops.len(), 2);
|
||||
for s in &m.gradient.stops {
|
||||
assert_eq!(s.swatch.as_deref(), Some("Spot"));
|
||||
assert!((s.tint - 0.4).abs() < 1e-6, "{}", s.tint);
|
||||
@@ -2919,6 +2930,7 @@ mod tests {
|
||||
}
|
||||
// A process solid unlinks the steps, and they take no plates.
|
||||
let Paint::Gradient(m) = lerp_paint(&Paint::solid(Color::BLACK), &gradient, 0.5) else { panic!() };
|
||||
assert_eq!(m.gradient.stops.len(), 2);
|
||||
assert!(m.gradient.stops.iter().all(|s| s.swatch.is_none() && s.plates.is_none()), "{:?}", m.gradient.stops);
|
||||
}
|
||||
|
||||
@@ -3401,7 +3413,8 @@ mod tests {
|
||||
#[test]
|
||||
fn odd_dash_blends_to_solid_with_closed_gaps() {
|
||||
let d = lerp_dash(Some(&Dash { pattern: vec![2.0, 3.0, 4.0], ..Default::default() }), None, 1.0).unwrap();
|
||||
assert!(d.pattern.iter().skip(1).step_by(2).all(|g| *g == 0.0), "{:?}", d.pattern);
|
||||
// Doubled to dash, gap, dash, gap, dash, gap; each dash takes the gap after it.
|
||||
assert_eq!(d.pattern, [5.0, 0.0, 6.0, 0.0, 7.0, 0.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -3412,7 +3425,8 @@ mod tests {
|
||||
let mid = lerp_node(&a, &b, 0.4);
|
||||
let mut ids = vec![];
|
||||
mid.walk(&mut |n| ids.push(n.id));
|
||||
assert!(ids.iter().all(|i| *i == NodeId(0)), "{ids:?}");
|
||||
// The step and its two members, all of them new.
|
||||
assert_eq!(ids, [NodeId(0); 3]);
|
||||
}
|
||||
|
||||
/// A blend of `a` and `b` spaced by `spacing`.
|
||||
|
||||
@@ -64,11 +64,10 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn modes_read_back_and_unknown_ones_are_add() {
|
||||
for m in ShapeMode::ALL {
|
||||
let v = serde_json::to_value(m).unwrap();
|
||||
assert_eq!(v, serde_json::json!(m.name()));
|
||||
assert_eq!(serde_json::from_value::<ShapeMode>(v).unwrap(), m);
|
||||
}
|
||||
assert_eq!(serde_json::to_value(ShapeMode::Subtract).unwrap(), serde_json::json!("subtract"));
|
||||
assert_eq!(serde_json::from_value::<ShapeMode>(serde_json::json!("exclude")).unwrap(), ShapeMode::Exclude);
|
||||
assert_eq!(ShapeMode::parse("intersect"), Some(ShapeMode::Intersect));
|
||||
assert_eq!(ShapeMode::parse("Intersect"), None);
|
||||
for v in [serde_json::json!("divide"), serde_json::json!(3), serde_json::json!(null), serde_json::json!({"a": [1]})] {
|
||||
assert_eq!(serde_json::from_value::<ShapeMode>(v).unwrap(), ShapeMode::Add);
|
||||
}
|
||||
|
||||
@@ -613,6 +613,7 @@ mod tests {
|
||||
d.limit_depth_noting(&mut warnings);
|
||||
assert_eq!(warnings, [symbols_note()]);
|
||||
assert!(!d.too_deep(None), "{count} {last}");
|
||||
assert_eq!(d.symbols.len(), count, "every symbol is kept");
|
||||
assert!(d.symbols.iter().all(|s| s.art.children().is_some()), "the art is still a group");
|
||||
}
|
||||
// An edit that makes one hold itself is seen, whatever else stayed as it was.
|
||||
|
||||
@@ -394,9 +394,11 @@ pub enum DimensionSource {
|
||||
/// it is vertical. Versions without this source do not open the file.
|
||||
Extent {
|
||||
node: NodeId,
|
||||
/// Placed with Use Preview Bounds on: the points are moved out to the outside of the
|
||||
/// strokes the path paints ([`preview_extents`]), the width or height that W and H show.
|
||||
/// Versions without it measure between the outermost points themselves.
|
||||
/// The points are moved out to the outside of the strokes the path paints
|
||||
/// ([`preview_extents`]), the width or height that W and H show with Use Preview Bounds on.
|
||||
/// The Dimension tool sets it on every dimension of a whole path it places. Without it,
|
||||
/// as in files saved before the tool set it and in versions without it, the dimension
|
||||
/// measures between the outermost points themselves.
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
preview: bool,
|
||||
},
|
||||
@@ -431,9 +433,9 @@ impl DimensionSource {
|
||||
}
|
||||
/// Whether a path it measures differs between `before` and `after`, or is in only one of them.
|
||||
/// A node without a path, or missing from both, counts as changed. For a dimension of a whole
|
||||
/// path placed with Use Preview Bounds on, so does a change to the strokes the path paints
|
||||
/// ([`stroked_by`]): their appearance, the node they come from, or which arrowheads they draw
|
||||
/// on it, and the path being made into a guide or released from one.
|
||||
/// path measured to the outside of its strokes (`preview`), so does a change to the strokes the
|
||||
/// path paints ([`stroked_by`]): their appearance, the node they come from, or which arrowheads
|
||||
/// they draw on it, and the path being made into a guide or released from one.
|
||||
pub fn art_changed(&self, before: &Document, after: &Document) -> bool {
|
||||
let strokes = matches!(self, Self::Extent { preview: true, .. });
|
||||
self.nodes().into_iter().any(|id| match (before.node(id), after.node(id)) {
|
||||
|
||||
@@ -108,6 +108,7 @@ impl GraphDesign {
|
||||
let mut e = n.extras_mut();
|
||||
e.graph = None;
|
||||
e.series_index = None;
|
||||
e.graph_design_art = false;
|
||||
}
|
||||
if let Some(ch) = n.children_mut() {
|
||||
let old = std::mem::take(ch);
|
||||
|
||||
@@ -457,7 +457,7 @@ mod tests {
|
||||
n.transform(Affine::scale_non_uniform(1.0, 0.25), false);
|
||||
assert!(n.extras().image_quad.is_none());
|
||||
let b = n.geometric_bounds().unwrap();
|
||||
assert!(b.height() < 1e-6 && (b.width() - 150.0).abs() < 60.0, "{b:?}");
|
||||
assert!(b.height() < 1e-6 && (b.x0 + 200.0 / 9.0).abs() < 1e-6 && (b.x1 - 1400.0 / 9.0).abs() < 1e-6, "{b:?}");
|
||||
}
|
||||
|
||||
/// A file's corners that the image cannot take are dropped as it is read, so a later scale
|
||||
|
||||
@@ -22,6 +22,8 @@ pub struct NodeExtras {
|
||||
/// Index of the graph series this generated group belongs to. Axes, the legend and other
|
||||
/// children leave it unset, so a series named "Legend" or "Axes" is not mistaken for them.
|
||||
pub series_index: Option<u32>,
|
||||
/// This object is a generated copy of a graph column or marker design.
|
||||
pub graph_design_art: bool,
|
||||
/// The group holds the glyph outlines of type. Geometry effects that reshape it move and scale
|
||||
/// the placed gradients in it with the outlines.
|
||||
pub type_outlines: bool,
|
||||
@@ -108,6 +110,7 @@ pub(super) static NO_EXTRAS: NodeExtras = NodeExtras {
|
||||
wrap: None,
|
||||
graph: None,
|
||||
series_index: None,
|
||||
graph_design_art: false,
|
||||
type_outlines: false,
|
||||
pixelated: false,
|
||||
shaper: None,
|
||||
|
||||
@@ -13,6 +13,7 @@ fn extras_are_written_flat_in_order() {
|
||||
e.mask = Some(Box::new(OpacityMask::new(Node::group(NodeId(8), vec![]), true)));
|
||||
e.trace = Some(Box::new(serde_json::json!({"preset": "p"})));
|
||||
e.series_index = Some(2);
|
||||
e.graph_design_art = true;
|
||||
e.type_outlines = true;
|
||||
e.graphic_style = Some(3);
|
||||
e.attrs = Some(Box::default());
|
||||
@@ -59,6 +60,7 @@ fn extras_are_written_flat_in_order() {
|
||||
"mask",
|
||||
"trace",
|
||||
"series_index",
|
||||
"graph_design_art",
|
||||
"type_outlines",
|
||||
"kind",
|
||||
"graphic_style",
|
||||
|
||||
@@ -36,6 +36,7 @@ impl Serialize for Node {
|
||||
e.wrap.is_none(),
|
||||
e.graph.is_none(),
|
||||
e.series_index.is_none(),
|
||||
is_default(&e.graph_design_art),
|
||||
is_default(&e.type_outlines),
|
||||
is_default(&e.pixelated),
|
||||
e.shaper.is_none(),
|
||||
@@ -86,6 +87,7 @@ impl Serialize for Node {
|
||||
field!("wrap", &e.wrap);
|
||||
field!("graph", &e.graph);
|
||||
field!("series_index", &e.series_index);
|
||||
field!("graph_design_art", &e.graph_design_art);
|
||||
field!("type_outlines", &e.type_outlines);
|
||||
field!("pixelated", &e.pixelated);
|
||||
field!("shaper", &e.shaper);
|
||||
@@ -220,6 +222,8 @@ pub(super) struct NodeWire {
|
||||
#[serde(default)]
|
||||
series_index: Option<u32>,
|
||||
#[serde(default)]
|
||||
graph_design_art: bool,
|
||||
#[serde(default)]
|
||||
type_outlines: bool,
|
||||
#[serde(default)]
|
||||
pixelated: bool,
|
||||
@@ -480,6 +484,7 @@ impl From<NodeWire> for Node {
|
||||
wrap: w.wrap,
|
||||
graph: w.graph,
|
||||
series_index: w.series_index,
|
||||
graph_design_art: w.graph_design_art,
|
||||
type_outlines: w.type_outlines,
|
||||
pixelated: w.pixelated,
|
||||
shaper: w.shaper,
|
||||
|
||||
@@ -253,6 +253,7 @@ mod tests {
|
||||
let mut a = Node::group(NodeId(1), vec![Arc::new(text)]);
|
||||
apply(&mut a, &[SymbolOverride { path: vec![0], stroke: Some(red.clone()), ..Default::default() }]);
|
||||
let Some(NodeKind::Text(t)) = part(&a, &[0]).map(|n| &n.kind) else { panic!("type") };
|
||||
assert_eq!(t.runs.len(), 1);
|
||||
assert!(t.runs.iter().all(|r| r.style.stroke == red && r.style.stroke_width == 1.0), "the stroke draws at 1 pt");
|
||||
|
||||
// A path whose stroke has neither paint nor weight gets 1 pt too.
|
||||
|
||||
@@ -44,7 +44,7 @@ pub use tabs_lists::{
|
||||
Bullet, DEFAULT_TAB_INTERVAL, LIST_HANGING_INDENT, LIST_LEVEL_INDENT, LIST_LEVELS, ListAlign, ListCounts, MAX_LIST_START, NumberStyle, ParaList,
|
||||
TabAlign, TabStop,
|
||||
};
|
||||
pub use wrap::{resolve_wrap, wrap_copy_units, wrap_outline, wrap_sources, wrap_work};
|
||||
pub use wrap::{resolve_wrap, wrap_copy_units, wrap_outline, wrap_source_objects, wrap_sources, wrap_work};
|
||||
|
||||
/// A text object. `runs` split into paragraphs at `\n`.
|
||||
///
|
||||
|
||||
@@ -217,11 +217,10 @@ fn indic_digits_map_to_their_scripts_block() {
|
||||
assert_eq!(map(d, "a-Z ٪"), "a-Z ٪");
|
||||
}
|
||||
assert_eq!(map(Digits::Devanagari, "page 12"), "page १२");
|
||||
for d in Digits::ALL {
|
||||
assert_eq!(serde_json::to_value(d).unwrap(), d.id());
|
||||
assert_eq!(serde_json::from_value::<Digits>(d.id().into()).unwrap(), d);
|
||||
assert_eq!(Digits::from_id(d.id()), Some(d));
|
||||
}
|
||||
assert_eq!(serde_json::to_value(Digits::Devanagari).unwrap(), "devanagari");
|
||||
assert_eq!(serde_json::from_value::<Digits>("farsi".into()).unwrap(), Digits::Farsi);
|
||||
assert_eq!(Digits::Malayalam.id(), "malayalam");
|
||||
assert_eq!(Digits::from_id("default"), Some(Digits::Default));
|
||||
assert_eq!(Digits::from_id("roman"), None);
|
||||
assert!(serde_json::from_value::<Digits>("roman".into()).is_err());
|
||||
}
|
||||
@@ -695,6 +694,15 @@ fn a_wrap_object_below_every_area_type_object_makes_no_outline() {
|
||||
});
|
||||
assert_eq!(sources, 1);
|
||||
assert_eq!(wrap::OUTLINES_MADE.with(|c| c.get()), 1, "only the wrap object above the type is outlined");
|
||||
// The objects alone come without a copy of any shape into text space.
|
||||
let mut found = vec![];
|
||||
wrap_source_objects(&d, |n, objects| found.push((n.id, objects.iter().map(|o| o.id).collect::<Vec<_>>())));
|
||||
let mut expected = vec![];
|
||||
wrap_sources(&d, |n, objects, _| expected.push((n.id, objects.iter().map(|o| o.id).collect::<Vec<_>>())));
|
||||
assert_eq!(found, expected);
|
||||
wrap::SHAPES_COPIED.with(|c| c.set(0));
|
||||
wrap_source_objects(&d, |_, _| {});
|
||||
assert_eq!(wrap::SHAPES_COPIED.with(|c| c.get()), 0, "no wrap shape is copied");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -11,6 +11,8 @@ use crate::{Document, Node, NodeId, NodeKind};
|
||||
thread_local! {
|
||||
/// How many wrap outlines [`each_text`] has made on this thread (for tests).
|
||||
pub(super) static OUTLINES_MADE: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
/// How many wrap shapes [`shapes_of`] has copied into text space on this thread (for tests).
|
||||
pub(super) static SHAPES_COPIED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// Outline of a wrap object in document coordinates: its paths, or its bounds for other art.
|
||||
@@ -167,6 +169,8 @@ fn shapes_of(t: &TextObject, above: &[(&Node, WrapShape)]) -> Vec<WrapShape> {
|
||||
.iter()
|
||||
.rev()
|
||||
.map(|(_, s)| {
|
||||
#[cfg(test)]
|
||||
SHAPES_COPIED.with(|c| c.set(c.get() + 1));
|
||||
let mut path = s.path.clone();
|
||||
path.transform(inv);
|
||||
WrapShape { path, wrap: s.wrap }
|
||||
@@ -189,6 +193,18 @@ pub fn wrap_sources<'a>(doc: &'a Document, mut f: impl FnMut(&'a Node, Vec<&'a N
|
||||
}
|
||||
}
|
||||
|
||||
/// [`wrap_sources`] without the shapes: each area text object that gets wrap shapes, with the wrap
|
||||
/// objects whose outlines make them, bottom first. No shape is copied into text space.
|
||||
pub fn wrap_source_objects<'a>(doc: &'a Document, mut f: impl FnMut(&'a Node, Vec<&'a Node>)) {
|
||||
for layer in &doc.layers {
|
||||
each_text(layer, |n, above| {
|
||||
if matches!(n.kind, NodeKind::Text(_)) && !above.is_empty() {
|
||||
f(n, above.iter().rev().map(|(s, _)| *s).collect());
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolve the wrap shapes (`TextObject::wrap`, text space) of each area text object from the
|
||||
/// outlines of the wrap objects above it in its layer. With `before`, the layers it holds unchanged
|
||||
/// are skipped; without it, every layer is resolved. Returns the area text objects whose shapes
|
||||
|
||||
@@ -98,11 +98,10 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn ids_round_trip_and_unknown_views_show_the_result() {
|
||||
for v in TraceView::ALL {
|
||||
assert_eq!(TraceView::from_id(v.id()), Some(v));
|
||||
assert_eq!(TraceView::from_id(&v.id().to_ascii_uppercase()), Some(v));
|
||||
assert!(v.shows_result() || v.shows_outlines() || v.shows_source(), "{v:?} shows something");
|
||||
}
|
||||
assert_eq!(TraceView::Source.id(), "sourceImage");
|
||||
assert_eq!(TraceView::from_id("outlinesWithSourceImage"), Some(TraceView::OutlinesWithSource));
|
||||
assert_eq!(TraceView::from_id("TRACINGRESULT"), Some(TraceView::Result), "case does not matter");
|
||||
assert_eq!(TraceView::from_id("tracing"), None);
|
||||
let mut g = Node::group(crate::NodeId(1), vec![]);
|
||||
assert_eq!(g.trace_view(), TraceView::Result);
|
||||
g.extras_mut().trace = Some(Box::new(serde_json::json!({"view": "outlines"})));
|
||||
|
||||
@@ -109,10 +109,9 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn the_effects_are_colour_adjustments_in_their_own_menu() {
|
||||
for id in EFFECTS {
|
||||
assert!(crate::is_adjustment(id), "{id}");
|
||||
assert_eq!(crate::effect_info(id).unwrap().menu, ["Effect", "Color Effects"]);
|
||||
}
|
||||
assert!(crate::is_adjustment(DUOTONE));
|
||||
assert_eq!(crate::effect_info(DUOTONE).unwrap().menu, ["Effect", "Color Effects"]);
|
||||
assert!(!crate::is_adjustment("stylize.dropShadow"), "an effect outside the add-on is not one");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -122,8 +121,12 @@ mod tests {
|
||||
// One stop doubles the light: sRGB 0.5 (linear 0.214) becomes linear 0.428, sRGB 0.686.
|
||||
assert!(close(map(EXPOSURE, json!({"exposure": 1})).apply_rgb(grey), [0.686; 3]));
|
||||
assert!(close(map(EXPOSURE, json!({"exposure": -20})).apply_rgb([1.0; 3]), [0.0; 3]));
|
||||
assert!(map(EXPOSURE, json!({"offset": 0.1})).apply_rgb([0.0; 3])[0] > 0.3, "the offset lifts the shadows");
|
||||
assert!(map(EXPOSURE, json!({"gamma": 2})).apply_rgb(grey)[0] > 0.6);
|
||||
// The offset adds linear light: linear 0.1 is sRGB 0.349.
|
||||
let lifted = map(EXPOSURE, json!({"offset": 0.1})).apply_rgb([0.0; 3]);
|
||||
assert!(lifted.iter().all(|c| (c - 0.349_190_2).abs() < 1e-5), "the offset lifts the shadows: {lifted:?}");
|
||||
// Gamma 2 takes the square root of linear 0.214 (sRGB 0.5): linear 0.463, sRGB 0.710.
|
||||
let raised = map(EXPOSURE, json!({"gamma": 2})).apply_rgb(grey);
|
||||
assert!(raised.iter().all(|c| (c - 0.710_196).abs() < 1e-5), "{raised:?}");
|
||||
assert!(close(map(EXPOSURE, json!({"exposure": 1e300, "gamma": 0})).apply_rgb(grey), [1.0; 3]), "out of range values are clamped");
|
||||
}
|
||||
|
||||
|
||||
@@ -19,7 +19,7 @@ use serde_json::{Value, json};
|
||||
use vectorcraft_doc::color::{BlendMode, Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, Document, Node, NodeId};
|
||||
use vectorcraft_geom::hit::fill_contains;
|
||||
use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, Point, Rect, shapes};
|
||||
use vectorcraft_geom::{Affine, BezPath, CubicBez, FillRule, PathData, Point, Rect, shapes};
|
||||
use vectorcraft_pathops::{self as po, BoolOp};
|
||||
|
||||
use crate::catalog::{EffectInfo, Lengths};
|
||||
@@ -43,7 +43,7 @@ pub(crate) fn catalog() -> Vec<EffectInfo> {
|
||||
id: HALFTONE,
|
||||
label: "Vector Halftone…",
|
||||
menu: &["Effect", "Color Effects"],
|
||||
params: "{shape: \"circle\"|\"ellipse\"|\"square\"|\"diamond\"|\"line\" (circle), frequency: lines per inch 1..300 (20), angle: deg (45; CMYK: the black screen's, cyan −30°, magenta +30°, yellow −45° from it), mode: \"mono\"|\"cmyk\" (mono), color: mono dot colour (\"#000000\"), fromArt: bool (false; mono: each dot takes the art's colour under it), invert: bool (false; dots for light tones), clip: bool (true; the dots clipped to the art's outline)} draws the object as vector halftone dots sized by its tone, as object.vectorHalftone makes them (CMYK screens multiply); the object is sampled as drawn with its other effects; at most 100000 cells per screen, past that the object draws as it is",
|
||||
params: "{shape: \"circle\"|\"ellipse\"|\"square\"|\"diamond\"|\"line\"|\"euclidean\"|\"elliptical\" (circle; euclidean: round dots that meet corner to corner at 50%, then round holes; elliptical: long dots that join into chains at 40% and on all sides at 60%, then long holes), frequency: lines per inch 1..300 (20), angle: deg (45; CMYK: the black screen's, cyan −30°, magenta +30°, yellow −45° from it), mode: \"mono\"|\"cmyk\" (mono), color: mono dot colour (\"#000000\"), fromArt: bool (false; mono: each dot takes the art's colour under it), invert: bool (false; dots for light tones), clip: bool (true; the dots clipped to the art's outline)} draws the object as vector halftone dots sized by its tone, as object.vectorHalftone makes them (CMYK screens multiply); the object is sampled as drawn with its other effects; at most 100000 cells per screen, past that the object draws as it is",
|
||||
defaults: json!({"shape": "circle", "frequency": 20.0, "angle": 45.0, "mode": "mono", "color": "#000000", "fromArt": false, "invert": false, "clip": true}),
|
||||
raster: false,
|
||||
lengths: Lengths::default(),
|
||||
@@ -63,6 +63,12 @@ pub enum DotShape {
|
||||
Square,
|
||||
Diamond,
|
||||
Line,
|
||||
/// Round dots that grow into squares meeting corner to corner at 50% (a checkerboard), then
|
||||
/// round holes, as the Euclidean spot function draws them.
|
||||
Euclidean,
|
||||
/// Elongated dots that join along their long side at 40% into chains, along their short side
|
||||
/// at 60%, then elongated holes.
|
||||
Elliptical,
|
||||
}
|
||||
|
||||
impl DotShape {
|
||||
@@ -73,6 +79,8 @@ impl DotShape {
|
||||
"square" => DotShape::Square,
|
||||
"diamond" => DotShape::Diamond,
|
||||
"line" | "lines" => DotShape::Line,
|
||||
"euclidean" => DotShape::Euclidean,
|
||||
"elliptical" => DotShape::Elliptical,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
@@ -82,22 +90,345 @@ impl DotShape {
|
||||
fn path(self, t: f64, s: f64) -> PathData {
|
||||
let square = |side: f64| shapes::rectangle(Rect::from_center_size(Point::ZERO, (side, side)));
|
||||
match self {
|
||||
DotShape::Circle => {
|
||||
let r = s * (t / std::f64::consts::PI).sqrt();
|
||||
shapes::ellipse(Rect::from_center_size(Point::ZERO, (2.0 * r, 2.0 * r)))
|
||||
}
|
||||
DotShape::Ellipse => {
|
||||
let r = s * (t / std::f64::consts::PI).sqrt();
|
||||
shapes::ellipse(Rect::from_center_size(Point::ZERO, (2.6 * r, 2.0 * r / 1.3)))
|
||||
}
|
||||
DotShape::Circle => cell_dot(t, s / 2.0, CellKind::Circle),
|
||||
DotShape::Ellipse => cell_dot(t, s / 2.0, CellKind::Ellipse),
|
||||
DotShape::Square => square(s * t.sqrt()),
|
||||
DotShape::Diamond => square(s * t.sqrt()).transformed(Affine::rotate(std::f64::consts::FRAC_PI_4)),
|
||||
DotShape::Diamond => cell_dot(t, s / 2.0, CellKind::Diamond),
|
||||
// Cells along a row join into a line as thick as the tone.
|
||||
DotShape::Line => shapes::rectangle(Rect::from_center_size(Point::ZERO, (s * 1.001, s * t))),
|
||||
DotShape::Euclidean => PathData::from_bezpath(&spot(t, s / 2.0, SpotKind::Euclidean)),
|
||||
DotShape::Elliptical => PathData::from_bezpath(&spot(t, s / 2.0, SpotKind::Elliptical)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The Elliptical dot's height over its width: a dot as wide as its cell covers 40% of it
|
||||
/// (π × ratio / 4 = 0.4 of a quadrant).
|
||||
const ELLIPTICAL_RATIO: f64 = 1.6 / std::f64::consts::PI;
|
||||
|
||||
/// The Elliptical dot's middle-tone cut in a quadrant of half side 1, the line
|
||||
/// `ELLIPTICAL_CUT.0 × x + y = ELLIPTICAL_CUT.1`. It meets the side x = 1 at y = 0.25 and the y
|
||||
/// axis at 0.75 and runs through the quadrant's center, so the dot it cuts at 50% is its own
|
||||
/// complement: the dark bridges across the x side from 40%, and the y side stays light until 60%.
|
||||
const ELLIPTICAL_CUT: (f64, f64) = (0.5, 0.75);
|
||||
|
||||
/// Steps of the table of dot sizes per tone ([`dot_sizes`]) over tones 0..0.5.
|
||||
const SIZE_STEPS: usize = 512;
|
||||
|
||||
static EUCLIDEAN: OnceLock<Vec<f64>> = OnceLock::new();
|
||||
static ELLIPTICAL: OnceLock<Vec<f64>> = OnceLock::new();
|
||||
|
||||
/// The two spot-function dots.
|
||||
#[derive(Clone, Copy)]
|
||||
enum SpotKind {
|
||||
Euclidean,
|
||||
Elliptical,
|
||||
}
|
||||
|
||||
impl SpotKind {
|
||||
/// The first quadrant of the dot of width `a` in a quadrant of half side 1.
|
||||
fn quadrant(self, a: f64) -> Vec<CubicBez> {
|
||||
match self {
|
||||
SpotKind::Euclidean => quadrant(a, a, 1.0),
|
||||
SpotKind::Elliptical => elliptical_quadrant(a),
|
||||
}
|
||||
}
|
||||
|
||||
/// The width at which the dot covers half the cell.
|
||||
fn max_size(self) -> f64 {
|
||||
match self {
|
||||
SpotKind::Euclidean => 1.0,
|
||||
SpotKind::Elliptical => ELLIPTICAL_CUT.1 / ELLIPTICAL_RATIO,
|
||||
}
|
||||
}
|
||||
|
||||
fn table(self) -> &'static OnceLock<Vec<f64>> {
|
||||
match self {
|
||||
SpotKind::Euclidean => &EUCLIDEAN,
|
||||
SpotKind::Elliptical => &ELLIPTICAL,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// For tones `k / SIZE_STEPS × 0.5`, the width `a` of the dot of `kind` that covers that tone of the
|
||||
/// cell [-1, 1]².
|
||||
fn dot_sizes(kind: SpotKind) -> Vec<f64> {
|
||||
(0..=SIZE_STEPS)
|
||||
.map(|k| {
|
||||
// A quadrant of the cell has area 1.
|
||||
let target = k as f64 / SIZE_STEPS as f64 * 0.5;
|
||||
let (mut lo, mut hi) = (0.0, kind.max_size());
|
||||
for _ in 0..50 {
|
||||
let mid = (lo + hi) / 2.0;
|
||||
if curves_area(&kind.quadrant(mid)) < target { lo = mid } else { hi = mid }
|
||||
}
|
||||
(lo + hi) / 2.0
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The area between the origin and `curves`, which run from the x axis to the y axis.
|
||||
fn curves_area(curves: &[CubicBez]) -> f64 {
|
||||
use vectorcraft_geom::kurbo::ParamCurveArea;
|
||||
curves.iter().map(|c| c.signed_area()).sum()
|
||||
}
|
||||
|
||||
/// Cubic curves along the ellipse with semi-axes `a`, `b` from angle `t0` to `t1`.
|
||||
fn ellipse_arc(out: &mut Vec<CubicBez>, a: f64, b: f64, t0: f64, t1: f64) {
|
||||
if t1 <= t0 {
|
||||
return;
|
||||
}
|
||||
let at = |th: f64| Point::new(a * th.cos(), b * th.sin());
|
||||
let n = ((t1 - t0) / std::f64::consts::FRAC_PI_4).ceil().max(1.0);
|
||||
let d = (t1 - t0) / n;
|
||||
let k = 4.0 / 3.0 * (d / 4.0).tan();
|
||||
for i in 0..n as usize {
|
||||
let (u0, u1) = (t0 + d * i as f64, t0 + d * (i as f64 + 1.0));
|
||||
let (p0, p3) = (at(u0), at(u1));
|
||||
let c1 = p0 + k * vectorcraft_geom::Vec2::new(-a * u0.sin(), b * u0.cos());
|
||||
let c2 = p3 - k * vectorcraft_geom::Vec2::new(-a * u1.sin(), b * u1.cos());
|
||||
out.push(CubicBez::new(p0, c1, c2, p3));
|
||||
}
|
||||
}
|
||||
|
||||
/// The straight segment from `p` to `q` as a cubic curve.
|
||||
fn segment(p: Point, q: Point) -> CubicBez {
|
||||
CubicBez::new(p, p.lerp(q, 1.0 / 3.0), p.lerp(q, 2.0 / 3.0), q)
|
||||
}
|
||||
|
||||
/// The first quadrant of the Elliptical dot of width `a` (height `ELLIPTICAL_RATIO × a`) in a
|
||||
/// quadrant of half side 1, from the x axis to the y axis. Up to width 1 (40%) it is the whole
|
||||
/// ellipse. Wider, the ellipse is clipped to the side x = 1, which makes a bridge to the next dot
|
||||
/// along x, and to the cut line [`ELLIPTICAL_CUT`], which keeps it off the y side.
|
||||
fn elliptical_quadrant(a: f64) -> Vec<CubicBez> {
|
||||
use std::f64::consts::FRAC_PI_2;
|
||||
let b = a * ELLIPTICAL_RATIO;
|
||||
let mut out = vec![];
|
||||
if a <= 1.0 {
|
||||
ellipse_arc(&mut out, a, b, 0.0, FRAC_PI_2);
|
||||
return out;
|
||||
}
|
||||
let at = |th: f64| Point::new(a * th.cos(), b * th.sin());
|
||||
let (m, c) = ELLIPTICAL_CUT;
|
||||
// The ellipse crosses the side x = 1 at angle t0.
|
||||
let t0 = (1.0 / a).acos();
|
||||
// Between angles ts and te the ellipse lies beyond the cut line.
|
||||
let r = (m * a).hypot(b);
|
||||
let (ts, te) = if r > c {
|
||||
let (phi, alpha) = (b.atan2(m * a), (c / r).acos());
|
||||
(phi - alpha, phi + alpha)
|
||||
} else {
|
||||
(FRAC_PI_2, FRAC_PI_2)
|
||||
};
|
||||
let end = if te < FRAC_PI_2 { at(te) } else { Point::new(0.0, c) };
|
||||
out.push(segment(Point::new(1.0, 0.0), if t0 < ts || t0 >= te { at(t0) } else { Point::new(1.0, c - m) }));
|
||||
if t0 >= te {
|
||||
ellipse_arc(&mut out, a, b, t0, FRAC_PI_2);
|
||||
return out;
|
||||
}
|
||||
if t0 < ts {
|
||||
ellipse_arc(&mut out, a, b, t0, ts.min(FRAC_PI_2));
|
||||
if ts >= FRAC_PI_2 {
|
||||
return out;
|
||||
}
|
||||
}
|
||||
let from = out.last().map_or(Point::new(1.0, 0.0), |q| q.p3);
|
||||
out.push(segment(from, end));
|
||||
ellipse_arc(&mut out, a, b, te, FRAC_PI_2);
|
||||
out
|
||||
}
|
||||
|
||||
/// The first quadrant of the ellipse with semi-axes `a`, `b` clipped to the diamond side x + y ≤
|
||||
/// `h`, from its point on the x axis to its point on the y axis, as cubic curves.
|
||||
fn quadrant(a: f64, b: f64, h: f64) -> Vec<CubicBez> {
|
||||
use std::f64::consts::FRAC_PI_2;
|
||||
let at = |th: f64| Point::new(a * th.cos(), b * th.sin());
|
||||
let mut out = vec![];
|
||||
let r = a.hypot(b);
|
||||
if r <= h {
|
||||
ellipse_arc(&mut out, a, b, 0.0, FRAC_PI_2);
|
||||
return out;
|
||||
}
|
||||
let (phi, alpha) = (b.atan2(a), (h / r).acos());
|
||||
let (ts, te) = (phi - alpha, phi + alpha);
|
||||
let start = if ts > 0.0 {
|
||||
ellipse_arc(&mut out, a, b, 0.0, ts);
|
||||
at(ts)
|
||||
} else {
|
||||
Point::new(h, 0.0)
|
||||
};
|
||||
let end = if te < FRAC_PI_2 { at(te) } else { Point::new(0.0, h) };
|
||||
out.push(segment(start, end));
|
||||
ellipse_arc(&mut out, a, b, te, FRAC_PI_2);
|
||||
out
|
||||
}
|
||||
|
||||
/// `curves` reversed, each curve run backwards.
|
||||
fn reversed(curves: &[CubicBez]) -> Vec<CubicBez> {
|
||||
curves.iter().rev().map(|c| CubicBez::new(c.p3, c.p2, c.p1, c.p0)).collect()
|
||||
}
|
||||
|
||||
/// `curves` with each point mapped by `f`.
|
||||
fn mapped(curves: &[CubicBez], f: impl Fn(Point) -> Point) -> Vec<CubicBez> {
|
||||
curves.iter().map(|c| CubicBez::new(f(c.p0), f(c.p1), f(c.p2), f(c.p3))).collect()
|
||||
}
|
||||
|
||||
/// The quadrant of the `kind` spot for tone `u` (0..0.5) in a cell of half side `h`, its size from
|
||||
/// the kind's table ([`dot_sizes`]).
|
||||
fn spot_quadrant(u: f64, h: f64, kind: SpotKind) -> Vec<CubicBez> {
|
||||
let sizes = kind.table().get_or_init(|| dot_sizes(kind));
|
||||
let x = (u / 0.5).clamp(0.0, 1.0) * SIZE_STEPS as f64;
|
||||
let i = (x.floor() as usize).min(SIZE_STEPS - 1);
|
||||
let (lo, hi) = (sizes.get(i).copied().unwrap_or(0.0), sizes.get(i + 1).copied().unwrap_or(0.0));
|
||||
let a = lo + (hi - lo) * (x - i as f64);
|
||||
mapped(&kind.quadrant(a), |p| Point::new(p.x * h, p.y * h))
|
||||
}
|
||||
|
||||
/// A spot-function dot for tone `t` (0..1) in a cell of half side `h` centered on the origin: up to
|
||||
/// half tone, the `kind` dot with the tone's area (Euclidean: a circle clipped to the cell's
|
||||
/// diamond; Elliptical: an ellipse clipped to the cell's sides and its middle-tone cut); past half,
|
||||
/// the cell with the dot of the opposite tone cut out at each corner, so the dark joins up and the
|
||||
/// light becomes holes.
|
||||
fn spot(t: f64, h: f64, kind: SpotKind) -> BezPath {
|
||||
if t <= 0.5 {
|
||||
return four_quadrants(&spot_quadrant(t, h, kind));
|
||||
}
|
||||
let mut bp = BezPath::new();
|
||||
let mut add = |curves: Vec<CubicBez>, first: bool| {
|
||||
for (k, c) in curves.iter().enumerate() {
|
||||
if k == 0 {
|
||||
if first { bp.move_to(c.p0) } else { bp.line_to(c.p0) }
|
||||
}
|
||||
bp.curve_to(c.p1, c.p2, c.p3);
|
||||
}
|
||||
};
|
||||
// Round the corners counterclockwise, each one's hole the dot of the opposite tone.
|
||||
let q1 = spot_quadrant(1.0 - t.min(1.0), h, kind);
|
||||
add(reversed(&mapped(&q1, |p| Point::new(h - p.x, h - p.y))), true);
|
||||
add(mapped(&q1, |p| Point::new(p.x - h, h - p.y)), false);
|
||||
add(reversed(&mapped(&q1, |p| Point::new(p.x - h, p.y - h))), false);
|
||||
add(mapped(&q1, |p| Point::new(h - p.x, p.y - h)), false);
|
||||
bp.close_path();
|
||||
bp
|
||||
}
|
||||
|
||||
/// The dots that grow past their cell's sides: drawn clipped to the cell, so neighbors meet along
|
||||
/// the shared side instead of overlapping, sized so the clipped dot covers the tone, and the whole
|
||||
/// cell at full tone.
|
||||
#[derive(Clone, Copy)]
|
||||
enum CellKind {
|
||||
Circle,
|
||||
/// 1.69 times as wide as tall.
|
||||
Ellipse,
|
||||
Diamond,
|
||||
}
|
||||
|
||||
static CELL_CIRCLE: OnceLock<Vec<f64>> = OnceLock::new();
|
||||
static CELL_ELLIPSE: OnceLock<Vec<f64>> = OnceLock::new();
|
||||
static CELL_DIAMOND: OnceLock<Vec<f64>> = OnceLock::new();
|
||||
|
||||
impl CellKind {
|
||||
/// The first quadrant of the dot of size `r` clipped to the quadrant [0, 1]², from the x axis to
|
||||
/// the y axis. Circle: radius `r`; Ellipse: semi-axes 1.3 `r` and `r` / 1.3; Diamond: half
|
||||
/// diagonal `r`.
|
||||
fn quadrant(self, r: f64) -> Vec<CubicBez> {
|
||||
let corner = Point::new(1.0, 1.0);
|
||||
match self {
|
||||
CellKind::Diamond if r <= 1.0 => vec![segment(Point::new(r, 0.0), Point::new(0.0, r))],
|
||||
CellKind::Diamond if r < 2.0 => vec![
|
||||
segment(Point::new(1.0, 0.0), Point::new(1.0, r - 1.0)),
|
||||
segment(Point::new(1.0, r - 1.0), Point::new(r - 1.0, 1.0)),
|
||||
segment(Point::new(r - 1.0, 1.0), Point::new(0.0, 1.0)),
|
||||
],
|
||||
CellKind::Diamond => vec![segment(Point::new(1.0, 0.0), corner), segment(corner, Point::new(0.0, 1.0))],
|
||||
CellKind::Circle | CellKind::Ellipse => {
|
||||
let (a, b) = if matches!(self, CellKind::Circle) { (r, r) } else { (1.3 * r, r / 1.3) };
|
||||
// The ellipse stays inside x ≤ 1 from angle tx and inside y ≤ 1 up to angle ty.
|
||||
let tx = (1.0 / a).min(1.0).acos();
|
||||
let ty = (1.0 / b).min(1.0).asin();
|
||||
if tx >= ty {
|
||||
return vec![segment(Point::new(1.0, 0.0), corner), segment(corner, Point::new(0.0, 1.0))];
|
||||
}
|
||||
let at = |th: f64| Point::new(a * th.cos(), b * th.sin());
|
||||
let mut out = vec![];
|
||||
if a > 1.0 {
|
||||
out.push(segment(Point::new(1.0, 0.0), at(tx)));
|
||||
}
|
||||
ellipse_arc(&mut out, a, b, tx, ty);
|
||||
if b > 1.0 {
|
||||
out.push(segment(at(ty), Point::new(0.0, 1.0)));
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The size at which the dot covers the whole quadrant.
|
||||
fn max_size(self) -> f64 {
|
||||
match self {
|
||||
CellKind::Circle => std::f64::consts::SQRT_2,
|
||||
// 1 / (1.3 r)² + (1.3 / r)² = 1 at the corner.
|
||||
CellKind::Ellipse => (1.0 / 1.69 + 1.69_f64).sqrt(),
|
||||
CellKind::Diamond => 2.0,
|
||||
}
|
||||
}
|
||||
|
||||
fn table(self) -> &'static OnceLock<Vec<f64>> {
|
||||
match self {
|
||||
CellKind::Circle => &CELL_CIRCLE,
|
||||
CellKind::Ellipse => &CELL_ELLIPSE,
|
||||
CellKind::Diamond => &CELL_DIAMOND,
|
||||
}
|
||||
}
|
||||
|
||||
/// For tones `k / SIZE_STEPS`, the size of the dot whose clipped quadrant covers that tone.
|
||||
fn sizes(self) -> Vec<f64> {
|
||||
(0..=SIZE_STEPS)
|
||||
.map(|k| {
|
||||
let target = k as f64 / SIZE_STEPS as f64;
|
||||
let (mut lo, mut hi) = (0.0, self.max_size());
|
||||
for _ in 0..50 {
|
||||
let mid = (lo + hi) / 2.0;
|
||||
if curves_area(&self.quadrant(mid)) < target { lo = mid } else { hi = mid }
|
||||
}
|
||||
(lo + hi) / 2.0
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// The `kind` dot for tone `t` (0..1) in a cell of half side `h` centered on the origin, clipped to
|
||||
/// the cell ([`CellKind`]).
|
||||
fn cell_dot(t: f64, h: f64, kind: CellKind) -> PathData {
|
||||
let sizes = kind.table().get_or_init(|| kind.sizes());
|
||||
let x = t.clamp(0.0, 1.0) * SIZE_STEPS as f64;
|
||||
let i = (x.floor() as usize).min(SIZE_STEPS - 1);
|
||||
let (lo, hi) = (sizes.get(i).copied().unwrap_or(0.0), sizes.get(i + 1).copied().unwrap_or(0.0));
|
||||
let r = lo + (hi - lo) * (x - i as f64);
|
||||
let q1 = mapped(&kind.quadrant(r), |p| Point::new(p.x * h, p.y * h));
|
||||
PathData::from_bezpath(&four_quadrants(&q1))
|
||||
}
|
||||
|
||||
/// The closed path through `q1` (from the x axis to the y axis) and its mirror images in the other
|
||||
/// three quadrants, counterclockwise.
|
||||
fn four_quadrants(q1: &[CubicBez]) -> BezPath {
|
||||
let mut bp = BezPath::new();
|
||||
let mut add = |curves: Vec<CubicBez>, first: bool| {
|
||||
for (k, c) in curves.iter().enumerate() {
|
||||
if k == 0 {
|
||||
if first { bp.move_to(c.p0) } else { bp.line_to(c.p0) }
|
||||
}
|
||||
bp.curve_to(c.p1, c.p2, c.p3);
|
||||
}
|
||||
};
|
||||
add(q1.to_vec(), true);
|
||||
add(reversed(&mapped(q1, |p| Point::new(-p.x, p.y))), false);
|
||||
add(mapped(q1, |p| Point::new(-p.x, -p.y)), false);
|
||||
add(reversed(&mapped(q1, |p| Point::new(p.x, -p.y))), false);
|
||||
bp.close_path();
|
||||
bp
|
||||
}
|
||||
|
||||
/// One screen: its ink and angle, and how to read its tone from a sampled pixel.
|
||||
struct Screen {
|
||||
paint: Color,
|
||||
@@ -399,6 +730,7 @@ pub fn halftone_art(d: &Document, n: &Node) -> Option<Node> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
use vectorcraft_doc::Effect;
|
||||
use vectorcraft_geom::Shape;
|
||||
|
||||
/// A black square's samples: `side` points of black from (10, 10), white around it.
|
||||
fn black_square(side: f64, h: &Halftone) -> (Samples, Rect) {
|
||||
@@ -464,6 +796,91 @@ mod tests {
|
||||
assert_eq!(cmyk.layers(&one, Rect::new(2.0, 2.0, 18.0, 18.0), None).0.len(), 2);
|
||||
}
|
||||
|
||||
/// Is `p` (in cells of side 1) inside the dot `shape` draws for tone `t`?
|
||||
fn covers(shape: DotShape, t: f64, p: (f64, f64)) -> bool {
|
||||
fill_contains(&shape.path(t, 1.0).to_bezpath(), FillRule::NonZero, Point::new(p.0, p.1))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spot_dots_cover_the_tone() {
|
||||
for shape in [DotShape::Euclidean, DotShape::Elliptical] {
|
||||
for k in 1..100 {
|
||||
let t = f64::from(k) / 100.0;
|
||||
let area = shape.path(t, 2.0).to_bezpath().area().abs() / 4.0;
|
||||
assert!((area - t).abs() < 2e-3, "{shape:?} at {t}: {area}");
|
||||
let b = shape.path(t, 2.0).control_bounds().unwrap();
|
||||
assert!(b.x0 >= -1.0 - 1e-9 && b.x1 <= 1.0 + 1e-9 && b.y0 >= -1.0 - 1e-9 && b.y1 <= 1.0 + 1e-9, "{shape:?} at {t}: {b:?}");
|
||||
}
|
||||
}
|
||||
assert_eq!((DotShape::parse("Euclidean"), DotShape::parse("elliptical")), (Some(DotShape::Euclidean), Some(DotShape::Elliptical)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn round_and_diamond_dots_stay_in_their_cell_and_fill_it_at_full_tone() {
|
||||
for shape in [DotShape::Circle, DotShape::Ellipse, DotShape::Diamond] {
|
||||
for t in [0.2, 0.6, 0.85, 0.97] {
|
||||
// The dot never reaches into a neighbor's cell, so dots of different tones meet
|
||||
// along the shared side instead of overlapping into notches.
|
||||
let b = shape.path(t, 2.0).control_bounds().unwrap();
|
||||
assert!(b.x0 >= -1.0 - 1e-9 && b.x1 <= 1.0 + 1e-9 && b.y0 >= -1.0 - 1e-9 && b.y1 <= 1.0 + 1e-9, "{shape:?} at {t}: {b:?}");
|
||||
// What it covers of the cell is the tone.
|
||||
let area = shape.path(t, 2.0).to_bezpath().area().abs() / 4.0;
|
||||
assert!((area - t).abs() < 2e-3, "{shape:?} at {t}: {area}");
|
||||
}
|
||||
// Full tone is the whole cell, its corners included.
|
||||
assert!(covers(shape, 1.0, (0.49, 0.49)) && covers(shape, 1.0, (-0.49, 0.49)), "{shape:?}");
|
||||
assert!(!covers(shape, 0.9, (0.499, 0.499)), "{shape:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn euclidean_dots_meet_corner_to_corner_at_half() {
|
||||
let s = DotShape::Euclidean;
|
||||
// Round dots apart from their neighbors below half.
|
||||
assert!(!covers(s, 0.45, (0.49, 0.0)) && !covers(s, 0.45, (0.0, 0.49)) && covers(s, 0.45, (0.3, 0.0)));
|
||||
// At half the dot is the diamond reaching the middle of each side: a checkerboard.
|
||||
for p in [(0.49, 0.0), (-0.49, 0.0), (0.0, 0.49), (0.0, -0.49)] {
|
||||
assert!(covers(s, 0.5, p), "{p:?}");
|
||||
}
|
||||
assert!(!covers(s, 0.5, (0.26, 0.26)) && covers(s, 0.5, (0.24, 0.24)));
|
||||
// Past half the light becomes round holes at the corners.
|
||||
assert!(covers(s, 0.55, (0.0, 0.499)) && covers(s, 0.55, (0.499, 0.0)) && !covers(s, 0.55, (0.49, 0.49)));
|
||||
assert!(covers(s, 0.99, (0.3, 0.3)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn elliptical_dots_join_along_their_length_then_their_width() {
|
||||
let s = DotShape::Elliptical;
|
||||
// Below 40% the dots stand apart.
|
||||
assert!(!covers(s, 0.38, (0.495, 0.0)) && !covers(s, 0.38, (0.0, 0.45)));
|
||||
// From 40% they reach their neighbors along x, making chains, but not along y.
|
||||
assert!(covers(s, 0.42, (0.495, 0.0)) && !covers(s, 0.42, (0.0, 0.45)));
|
||||
// The chains are bridges as tall as the tone allows across the shared side, not single
|
||||
// points: off the axis on the side x = 0.5, and on the cell's other side by symmetry.
|
||||
assert!(covers(s, 0.46, (0.499, 0.03)) && covers(s, 0.46, (-0.499, -0.03)) && !covers(s, 0.46, (0.499, 0.2)));
|
||||
assert!(covers(s, 0.5, (0.499, 0.12)) && !covers(s, 0.5, (0.499, 0.13)) && !covers(s, 0.5, (0.0, 0.49)));
|
||||
// Up to 60% the light still runs along the top edge between the corner holes.
|
||||
assert!(!covers(s, 0.55, (0.02, 0.499)) && covers(s, 0.55, (0.0, 0.3)));
|
||||
// Past 60% the dark joins across the top edge too, leaving elongated holes.
|
||||
assert!(covers(s, 0.65, (0.02, 0.499)) && covers(s, 0.65, (0.495, 0.0)) && !covers(s, 0.65, (0.49, 0.49)));
|
||||
// The holes are longer along x than along y.
|
||||
assert!(!covers(s, 0.8, (0.3, 0.49)) && covers(s, 0.8, (0.49, 0.3)), "ratio {ELLIPTICAL_RATIO}");
|
||||
// Today's Ellipse stays as it was: an ellipse 1.69 times as wide as tall.
|
||||
let b = DotShape::Ellipse.path(0.3, 1.0).control_bounds().unwrap();
|
||||
assert!((b.width() / b.height() - 1.69).abs() < 1e-6, "{b:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spot_shapes_make_dots_through_the_screen() {
|
||||
for shape in [DotShape::Euclidean, DotShape::Elliptical] {
|
||||
let h = Halftone::of(&effect(json!({"frequency": 18, "shape": format!("{shape:?}")}))).unwrap();
|
||||
assert_eq!(h.shape, shape);
|
||||
let (s, b) = black_square(60.0, &h);
|
||||
let (layers, dots) = h.layers(&s, b, None);
|
||||
assert!(layers.len() == 1 && (150..=320).contains(&dots), "{shape:?}: {dots}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_caps_refuse_too_many_cells() {
|
||||
let h = Halftone::of(&effect(json!({"frequency": 300}))).unwrap();
|
||||
|
||||
@@ -744,7 +744,7 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
|
||||
"pixelate.colorHalftone",
|
||||
"Color Halftone…",
|
||||
PIXELATE,
|
||||
"{maxRadius: px 4..127 (8; the radius of a dot at full strength, which fills its square cell, in pixels of the Document Raster Effects resolution), channel1: screen angle deg -360..360 (108), channel2: deg (162), channel3: deg (90), channel4: deg (45)} screens each colour channel (red, green, blue: channels 1 to 3; in CMYK documents cyan, magenta, yellow, black: 1 to 4) at its angle into dots whose area follows the channel's mean over their cell",
|
||||
"{maxRadius: px 4..127 (8; the radius of a dot at full strength, which fills its square cell, in pixels of the Document Raster Effects resolution), channel1: screen angle deg -360..360 (108), channel2: deg (162), channel3: deg (90), channel4: deg (45)} The effect screens cyan, magenta and yellow ink (channels 1 to 3; CMYK mode adds black as channel 4) at their angles into dots whose area follows the cell's mean ink coverage.",
|
||||
json!({"maxRadius": 8.0, "channel1": 108.0, "channel2": 162.0, "channel3": 90.0, "channel4": 45.0}),
|
||||
),
|
||||
r(
|
||||
|
||||
@@ -437,7 +437,7 @@ impl Screen {
|
||||
|
||||
/// Color Halftone: each channel screened at its angle in square cells sized so that a dot of
|
||||
/// `max_radius` (pixels of the document's raster grid, `space.line` each) fills one; each cell's
|
||||
/// dot covers the share of it that is the channel's mean there (white stays white, black black).
|
||||
/// dot covers the mean ink coverage of that cell (white stays white, black black).
|
||||
/// Coverage stays as it is.
|
||||
pub(super) fn color_halftone(px: &mut [[u8; 4]], w: usize, h: usize, space: &PixelSpace, max_radius: f64, angles: [f64; 4]) {
|
||||
let Some(place) = Place::new(space, w, h) else { return };
|
||||
@@ -446,7 +446,8 @@ pub(super) fn color_halftone(px: &mut [[u8; 4]], w: usize, h: usize, space: &Pix
|
||||
if !(side.is_finite() && side / place.px >= 3.0) {
|
||||
return;
|
||||
}
|
||||
let channels = space.channels;
|
||||
// Screen RGB as dark ink against white, like the CMY channel previews.
|
||||
let channels = if space.channels == Channels::Rgb { Channels::CmyPlane } else { space.channels };
|
||||
let n = split([0; 4], channels).1;
|
||||
let limit = w.saturating_mul(h).saturating_add(4096);
|
||||
let mut screens = Vec::with_capacity(n);
|
||||
@@ -478,7 +479,7 @@ pub(super) fn color_halftone(px: &mut [[u8; 4]], w: usize, h: usize, space: &Pix
|
||||
let mean = if sum[1] > 1e-6 { f64::from(sum[0] / sum[1]) } else { 0.0 };
|
||||
// Full strength fills the cell, corners too; none leaves no speck.
|
||||
let radius = match mean {
|
||||
m if m >= 254.5 / 255.0 => f64::INFINITY,
|
||||
m if m >= 254.5 / 255.0 => side / std::f64::consts::SQRT_2 + 0.5 * place.px,
|
||||
m if m <= 0.5 / 255.0 => 0.0,
|
||||
m => dot_radius(m) * side,
|
||||
};
|
||||
|
||||
@@ -694,11 +694,6 @@ fn smart_blur_smooths_noise_and_keeps_edges() {
|
||||
assert_eq!(at(&all, w, 20, 10)[0], 255, "a 155-level step is still past 100");
|
||||
}
|
||||
|
||||
/// FNV-1a of `bytes`.
|
||||
fn digest(bytes: &[u8]) -> u64 {
|
||||
bytes.iter().fold(0xcbf2_9ce4_8422_2325, |h, b| (h ^ u64::from(*b)).wrapping_mul(0x0100_0000_01b3))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn smart_blur_normal_mode_keeps_its_pixels() {
|
||||
let (w, h) = (48, 40);
|
||||
@@ -706,7 +701,6 @@ fn smart_blur_normal_mode_keeps_its_pixels() {
|
||||
let a = if x > 4 && y < 36 { 255 } else { 128 };
|
||||
[((x * 5 + y) as u8).min(a), ((y * 6) as u8).min(a), (((x * y) % 97) as u8).min(a), a]
|
||||
});
|
||||
let mut sums = Vec::new();
|
||||
for p in [json!({}), json!({"radius": 2, "threshold": 10, "quality": "high"}), json!({"radius": 12, "threshold": 40, "quality": "low"})] {
|
||||
let mut d = src.clone();
|
||||
fx("blur.smart", p.clone()).apply(&mut d, w, h, &space(w, h));
|
||||
@@ -715,10 +709,127 @@ fn smart_blur_normal_mode_keeps_its_pixels() {
|
||||
p["blurMode"] = json!("normal");
|
||||
fx("blur.smart", p).apply(&mut normal, w, h, &space(w, h));
|
||||
assert_eq!(d, normal);
|
||||
sums.push(digest(&d));
|
||||
}
|
||||
// The pixels Smart Blur gave before it had a mode.
|
||||
assert_eq!(sums, [11495339692959753241, 14281410954765351056, 5111933201350526354]);
|
||||
}
|
||||
|
||||
/// Smart Blur at radius 1 averages each pixel with the neighbours whose channels, alpha included,
|
||||
/// all lie within the threshold: grays 100 and 110 average to 105 each, 200 is 90 levels from 110
|
||||
/// and stays, and the two grays 100 after it have the same color but alpha 255 and 128, so neither
|
||||
/// takes the other.
|
||||
#[test]
|
||||
fn smart_blur_averages_only_the_neighbours_within_the_threshold() {
|
||||
let (w, h) = (5, 1);
|
||||
let src = image(w, h, |x, _| match x {
|
||||
0 => [100, 100, 100, 255],
|
||||
1 => [110, 110, 110, 255],
|
||||
2 => [200, 200, 200, 255],
|
||||
3 => [100, 100, 100, 255],
|
||||
_ => [100, 100, 100, 128],
|
||||
});
|
||||
let mut d = src.clone();
|
||||
fx("blur.smart", json!({"radius": 1, "threshold": 20})).apply(&mut d, w, h, &space(w, h));
|
||||
assert_eq!(at(&d, w, 0, 0), [105, 105, 105, 255]);
|
||||
assert_eq!(at(&d, w, 1, 0), [105, 105, 105, 255]);
|
||||
assert_eq!(at(&d, w, 2, 0), [200, 200, 200, 255]);
|
||||
assert_eq!(at(&d, w, 3, 0), at(&src, w, 3, 0));
|
||||
assert_eq!(at(&d, w, 4, 0), at(&src, w, 4, 0));
|
||||
}
|
||||
|
||||
/// Smart Blur at radius 12 reads its neighbours from a box-blurred copy. Next to a step from gray
|
||||
/// 100 to gray 200 that copy holds values between them, so at threshold 50 the pixel on the dark
|
||||
/// side of the step takes in some lighter gray and the pixel on the light side some darker gray,
|
||||
/// while pixels more than 15 pixels from the step keep their gray. Medium quality takes in less of
|
||||
/// the other gray than low, and at threshold 30 the pixels next to the step keep their gray.
|
||||
#[test]
|
||||
fn smart_blur_at_a_wide_radius_reads_the_blurred_copy_next_to_an_edge() {
|
||||
let (w, h) = (60, 40);
|
||||
let src = image(w, h, |x, _| grey(if x < 30 { 100 } else { 200 }));
|
||||
let mut d = src.clone();
|
||||
fx("blur.smart", json!({"radius": 12, "threshold": 50, "quality": "low"})).apply(&mut d, w, h, &space(w, h));
|
||||
let dark = at(&d, w, 29, 20)[0];
|
||||
let light = at(&d, w, 30, 20)[0];
|
||||
assert!((101..=150).contains(&dark), "the dark side takes in some lighter gray: {dark}");
|
||||
assert!((150..=199).contains(&light), "the light side takes in some darker gray: {light}");
|
||||
assert_eq!(at(&d, w, 10, 20), grey(100));
|
||||
assert_eq!(at(&d, w, 50, 20), grey(200));
|
||||
// Medium quality spreads 7 samples instead of 5, read from a copy blurred over 2 pixels instead
|
||||
// of 3, so less of the other gray reaches the pixels next to the step.
|
||||
let mut medium = src.clone();
|
||||
fx("blur.smart", json!({"radius": 12, "threshold": 50, "quality": "medium"})).apply(&mut medium, w, h, &space(w, h));
|
||||
let (medium_dark, medium_light) = (at(&medium, w, 29, 20)[0], at(&medium, w, 30, 20)[0]);
|
||||
assert!(100 < medium_dark && medium_dark < dark, "medium {medium_dark}, low {dark}");
|
||||
assert!(light < medium_light && medium_light < 200, "medium {medium_light}, low {light}");
|
||||
// At threshold 30 the blurred values next to the step are too far from both grays, and the
|
||||
// pixels on either side keep their gray.
|
||||
let mut sharp = src.clone();
|
||||
fx("blur.smart", json!({"radius": 12, "threshold": 30, "quality": "low"})).apply(&mut sharp, w, h, &space(w, h));
|
||||
assert_eq!(at(&sharp, w, 29, 20), grey(100));
|
||||
assert_eq!(at(&sharp, w, 30, 20), grey(200));
|
||||
}
|
||||
|
||||
/// Smart Blur at radius 12 and low quality samples offsets 0, 6 and 12 pixels along each axis,
|
||||
/// in both directions, within distance 12.5. A one-column gray-200 stripe at x = 30 on gray 100
|
||||
/// becomes (6 * 100 + 200) / 7, about 114.29, in the copy box-blurred with radius 3. For the
|
||||
/// gray-100 pixel at (24, 20), only the three samples at x = 30 have blurred values above 100.
|
||||
/// Their own value 200 is outside threshold 30, so they are excluded and the result stays 100.
|
||||
/// Including them would average ten samples of 100 with three of about 114.29 and round to 103.
|
||||
#[test]
|
||||
fn smart_blur_at_a_wide_radius_rejects_a_stripes_own_value_outside_the_threshold() {
|
||||
let (w, h) = (60, 40);
|
||||
let src = image(w, h, |x, _| grey(if x == 30 { 200 } else { 100 }));
|
||||
let mut d = src.clone();
|
||||
fx("blur.smart", json!({"radius": 12, "threshold": 30, "quality": "low"})).apply(&mut d, w, h, &space(w, h));
|
||||
assert_eq!(at(&d, w, 24, 20), grey(100));
|
||||
}
|
||||
|
||||
/// Smart Blur at radius 2 reaches two pixels each way: grays 100, 110 and 120 lie within 20 levels
|
||||
/// of each other and all average to 110 (at radius 1 the ends would give 105 and 115), 200 and 210
|
||||
/// average to 205, and 60 is too far from both groups and stays.
|
||||
#[test]
|
||||
fn smart_blur_at_radius_two_averages_the_neighbours_two_pixels_away() {
|
||||
let (w, h) = (6, 1);
|
||||
let src = image(w, h, |x, _| grey([100, 110, 120, 200, 210, 60][x]));
|
||||
let mut d = src.clone();
|
||||
fx("blur.smart", json!({"radius": 2, "threshold": 20, "quality": "high"})).apply(&mut d, w, h, &space(w, h));
|
||||
let want = image(w, h, |x, _| grey([110, 110, 110, 205, 205, 60][x]));
|
||||
assert_eq!(d, want);
|
||||
}
|
||||
|
||||
/// Smart Blur at radius 2 and high quality reads the original pixels within distance 2.5.
|
||||
/// The center at (2, 2) is gray 100, one neighbor is gray 120, and the rest are gray 200,
|
||||
/// outside threshold 20. A neighbor at (4, 2) is two pixels away, so the center averages
|
||||
/// (100 + 120) / 2 = 110. A neighbor at (4, 4) is sqrt(8), about 2.83 pixels away, so it is
|
||||
/// excluded and the center stays 100. Reading the whole square would give 110 in both cases.
|
||||
#[test]
|
||||
fn smart_blur_at_radius_two_keeps_the_neighbours_inside_the_disc() {
|
||||
let (w, h) = (5, 5);
|
||||
for ((nx, ny), want) in [((4, 2), 110), ((4, 4), 100)] {
|
||||
let src = image(w, h, |x, y| match (x, y) {
|
||||
(2, 2) => grey(100),
|
||||
p if p == (nx, ny) => grey(120),
|
||||
_ => grey(200),
|
||||
});
|
||||
let mut d = src.clone();
|
||||
fx("blur.smart", json!({"radius": 2, "threshold": 20, "quality": "high"})).apply(&mut d, w, h, &space(w, h));
|
||||
assert_eq!(at(&d, w, 2, 2), grey(want), "neighbor at ({nx}, {ny})");
|
||||
}
|
||||
}
|
||||
|
||||
/// Smart Blur's default radius 3 and medium quality (7 samples) read every integer offset
|
||||
/// in the 7 by 7 square without prefiltering, keeping offsets within distance 3.5.
|
||||
/// The center at (3, 3) is gray 100, its neighbor at (6, 3) is gray 120, and the rest are
|
||||
/// gray 200, outside the default threshold 25. The center averages (100 + 120) / 2 = 110.
|
||||
/// A search limited to two pixels would leave the center at 100.
|
||||
#[test]
|
||||
fn smart_blur_default_radius_averages_the_neighbour_three_pixels_away() {
|
||||
let (w, h) = (7, 7);
|
||||
let mut d = image(w, h, |x, y| match (x, y) {
|
||||
(3, 3) => grey(100),
|
||||
(6, 3) => grey(120),
|
||||
_ => grey(200),
|
||||
});
|
||||
fx("blur.smart", json!({})).apply(&mut d, w, h, &space(w, h));
|
||||
assert_eq!(at(&d, w, 3, 3), grey(110));
|
||||
}
|
||||
|
||||
/// Smart Blur's test image: grays 56 and 64 in a checkerboard for x < 3 and 66 and 74 for x in 3..6
|
||||
@@ -954,60 +1065,6 @@ fn linear_light_blur_mixes_light_not_values() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Timings on a 2000 × 2000 raster (`cargo test -p vectorcraft-effects --release -- --ignored
|
||||
/// --nocapture pixel_timings`).
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn pixel_timings() {
|
||||
let (w, h) = (2000, 2000);
|
||||
let src = image(w, h, |x, y| [(x % 256) as u8, (y % 256) as u8, ((x ^ y) % 256) as u8, 255]);
|
||||
let s = PixelSpace {
|
||||
to_doc: Affine::IDENTITY,
|
||||
px: 1.0,
|
||||
center: Point::new(1000.0, 1000.0),
|
||||
size: vectorcraft_geom::Vec2::new(2000.0, 2000.0),
|
||||
channels: Channels::Rgb,
|
||||
line: 1.0,
|
||||
extent: 0.0,
|
||||
};
|
||||
let cases = [
|
||||
("blur.radial", json!({"quality": "draft"})),
|
||||
("blur.radial", json!({"quality": "good"})),
|
||||
("blur.radial", json!({"quality": "best", "method": "zoom"})),
|
||||
("blur.smart", json!({"quality": "low"})),
|
||||
("blur.smart", json!({"quality": "high", "radius": 30})),
|
||||
("sharpen.unsharpMask", json!({"radius": 20})),
|
||||
("brushStrokes.accentedEdges", json!({"edgeWidth": 14})),
|
||||
("brushStrokes.angledStrokes", json!({"strokeLength": 50})),
|
||||
("brushStrokes.crosshatch", json!({"strokeLength": 50, "strength": 3})),
|
||||
("brushStrokes.darkStrokes", json!({})),
|
||||
("brushStrokes.inkOutlines", json!({"strokeLength": 50})),
|
||||
("brushStrokes.spatter", json!({"sprayRadius": 25})),
|
||||
("brushStrokes.sprayedStrokes", json!({"strokeLength": 20, "sprayRadius": 25})),
|
||||
("brushStrokes.sumiE", json!({"strokeWidth": 15})),
|
||||
("pixelate.colorHalftone", json!({"maxRadius": 4})),
|
||||
("pixelate.crystallize", json!({"cellSize": 3})),
|
||||
("pixelate.crystallize", json!({"cellSize": 300})),
|
||||
("pixelate.mezzotint", json!({"type": "grainyDots"})),
|
||||
("pixelate.pointillize", json!({"cellSize": 3})),
|
||||
("pixelate.pointillize", json!({"cellSize": 300})),
|
||||
("texture.craquelure", json!({"crackSpacing": 2})),
|
||||
("texture.craquelure", json!({"crackSpacing": 100})),
|
||||
("texture.grain", json!({"grainType": "clumped"})),
|
||||
("texture.mosaicTiles", json!({"tileSize": 2})),
|
||||
("texture.patchwork", json!({"squareSize": 0})),
|
||||
("texture.stainedGlass", json!({"cellSize": 2})),
|
||||
("texture.texturizer", json!({"texture": "sandstone", "scaling": 50})),
|
||||
("texture.texturizer", json!({"texture": "burlap"})),
|
||||
];
|
||||
for (id, p) in cases {
|
||||
let mut d = src.clone();
|
||||
let t = std::time::Instant::now();
|
||||
fx(id, p.clone()).apply(&mut d, w, h, &s);
|
||||
println!("{id} {p}: {:?}", t.elapsed());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pixelate_params_take_defaults_and_stay_in_range() {
|
||||
assert_eq!(fx("pixelate.colorHalftone", json!({})), PixelFx::ColorHalftone { max_radius: 8.0, angles: [108.0, 162.0, 90.0, 45.0] });
|
||||
@@ -1070,13 +1127,44 @@ fn color_halftone_screens_midtones_into_dots_and_keeps_white_and_black() {
|
||||
let mut half = image(w, h, |x, _| if x < 32 { grey(160) } else { [0; 4] });
|
||||
halftone.apply(&mut half, w, h, &space(w, h));
|
||||
assert!((0..h).all(|y| (32..w).all(|x| at(&half, w, x, y) == [0; 4])));
|
||||
// Dots are bigger where the image is brighter.
|
||||
// Brighter areas have fewer dark pixels.
|
||||
let mut ramp = image(w, h, |x, _| grey((x * 4) as u8));
|
||||
halftone.apply(&mut ramp, w, h, &space(w, h));
|
||||
let lit = |x0: usize| (0..h).flat_map(|y| (x0..x0 + 16).map(move |x| (x, y))).filter(|(x, y)| at(&ramp, w, *x, *y)[0] > 127).count();
|
||||
assert!(lit(8) < lit(40), "{} < {}", lit(8), lit(40));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn color_halftone_draws_dark_dots_on_light_rgb() {
|
||||
let (w, h) = (64, 64);
|
||||
let halftone = fx("pixelate.colorHalftone", json!({"maxRadius": 8, "channel1": 0, "channel2": 0, "channel3": 0}));
|
||||
let mut d = image(w, h, |_, _| grey(192));
|
||||
halftone.apply(&mut d, w, h, &space(w, h));
|
||||
assert_eq!(at(&d, w, 37, 37), grey(0));
|
||||
assert_eq!(at(&d, w, 32, 32), grey(255));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn color_halftone_full_coverage_only_overlaps_the_edge_of_an_empty_neighbor() {
|
||||
let (w, h) = (96, 64);
|
||||
let source = image(w, h, |x, _| grey(if x < w / 2 { 0 } else { 255 }));
|
||||
let mut screened = source.clone();
|
||||
fx("pixelate.colorHalftone", json!({"maxRadius": 8, "channel1": 0, "channel2": 0, "channel3": 0})).apply(&mut screened, w, h, &space(w, h));
|
||||
let half_cell = (8.0 * std::f64::consts::SQRT_2 / 2.0) as usize;
|
||||
let (edge, y) = (w / 2, h / 2 + half_cell);
|
||||
assert_eq!(at(&screened, w, edge - half_cell, y), grey(0), "the full cell keeps its center");
|
||||
assert_eq!(at(&screened, w, edge, y), grey(0), "the round dot crosses the straight cell edge");
|
||||
let fringe = at(&screened, w, edge + 2, y)[0];
|
||||
assert!(fringe > 0 && fringe < 255, "the last overlapping column is antialiased: {fringe}");
|
||||
// With an 8 px radius and the grid aligned to this edge, the circle and its antialiasing
|
||||
// can reach only the first three columns of white. Check every row, including cell corners.
|
||||
for y in 0..h {
|
||||
for x in edge + 3..w {
|
||||
assert_eq!(at(&screened, w, x, y), grey(255), "unexpected ink at ({x}, {y})");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn color_halftone_sizes_its_dots_in_pixels_of_the_raster_effects_resolution() {
|
||||
// Max Radius counts the document's raster grid pixels (#3260): 16 px at 144 ppi (lines half a
|
||||
|
||||
@@ -600,9 +600,9 @@ fn check_solids(id: &str, p: &Value, shapes: &[Profile]) -> Result<(), String> {
|
||||
}
|
||||
let (parts, bounds) = solid_parts(shapes, b);
|
||||
if !cast {
|
||||
return built_solids(id, p, &parts, bounds, MAX_OBJECT_FACES).try_for_each(|r| r.map(|_| ()));
|
||||
return built_solids(id, p, &parts, bounds, object_face_limit()).try_for_each(|r| r.map(|_| ()));
|
||||
}
|
||||
let built = built_solids_cast(id, p, &parts, bounds, MAX_OBJECT_FACES, true, false, None)
|
||||
let built = built_solids_cast(id, p, &parts, bounds, object_face_limit(), true, false, None)
|
||||
.map(|r| r.map(|solid| solid.and_then(|(_, faces)| faces)))
|
||||
.collect::<Result<Vec<_>, String>>()?;
|
||||
cast_built(id, p, shapes, built).map(|_| ())
|
||||
@@ -1025,13 +1025,30 @@ thread_local! {
|
||||
/// [`built_solids`] have built on this thread, for the tests. The solids built to cast a shadow
|
||||
/// ([`cast_shadow`]) count too.
|
||||
static SOLID_GEOMETRY_BUILT: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
/// The limit [`object_face_limit`] gives on this thread: [`MAX_OBJECT_FACES`] unless a test sets
|
||||
/// a lower one, so that a test of the limit builds small solids.
|
||||
pub(crate) static OBJECT_FACE_LIMIT: std::cell::Cell<usize> = const { std::cell::Cell::new(MAX_OBJECT_FACES) };
|
||||
}
|
||||
|
||||
/// Most faces the Extrude & Bevel or Inflate solids of one effect on one object keep together:
|
||||
/// [`MAX_OBJECT_FACES`].
|
||||
#[cfg(not(test))]
|
||||
fn object_face_limit() -> usize {
|
||||
MAX_OBJECT_FACES
|
||||
}
|
||||
|
||||
/// Most faces the Extrude & Bevel or Inflate solids of one effect on one object keep together:
|
||||
/// [`MAX_OBJECT_FACES`], or the lower limit a test set in [`OBJECT_FACE_LIMIT`].
|
||||
#[cfg(test)]
|
||||
fn object_face_limit() -> usize {
|
||||
OBJECT_FACE_LIMIT.with(std::cell::Cell::get)
|
||||
}
|
||||
|
||||
/// The solids Extrude & Bevel (Classic included) or Inflate `id` with parameters `p` builds from
|
||||
/// `parts` ([`solid_parts`]) about `bounds`, one result for each part in order, each built only as
|
||||
/// the iterator reaches it. A stroke's solid past its own limits is `None` (left out of the art, its
|
||||
/// faces not counted); a fill's is an error. The faces of the solids kept count together: once they
|
||||
/// pass `limit` ([`MAX_OBJECT_FACES`] for the art) the result is an error, and
|
||||
/// pass `limit` ([`object_face_limit`] for the art) the result is an error, and
|
||||
/// no later part is built. An error ends the iterator.
|
||||
fn built_solids<'a>(
|
||||
id: &'a str,
|
||||
@@ -1211,7 +1228,7 @@ fn rects_overlap(a: Rect, b: Rect) -> bool {
|
||||
|
||||
/// How many faces [`cut_stroke_faces`] may add to solids painted by `items` that hold `faces` faces
|
||||
/// and whose paint copies take `paint_bytes` so far: as many as keep the faces within
|
||||
/// [`MAX_OBJECT_FACES`] and the copies within the allowance, each added face counted as
|
||||
/// [`object_face_limit`] and the copies within the allowance, each added face counted as
|
||||
/// [`MAX_FACET_COPIES`] copies of the costliest stroke's paint.
|
||||
fn cut_room<'a>(items: impl Iterator<Item = &'a AppearanceItem>, faces: usize, paint_bytes: usize) -> usize {
|
||||
let per_face = items
|
||||
@@ -1225,7 +1242,7 @@ fn cut_room<'a>(items: impl Iterator<Item = &'a AppearanceItem>, faces: usize, p
|
||||
.unwrap_or(0)
|
||||
.max(1);
|
||||
let affordable = crate::revolve::MAX_PAINT_COPIES.saturating_sub(paint_bytes) / per_face;
|
||||
MAX_OBJECT_FACES.saturating_sub(faces).min(affordable)
|
||||
object_face_limit().saturating_sub(faces).min(affordable)
|
||||
}
|
||||
|
||||
/// In `solids`, each solid's part ([`Paints`]), its shape's index and its faces, cut each face of a
|
||||
@@ -2403,7 +2420,7 @@ fn surfaces_with(
|
||||
let map_art = MapArt::of(doc, &fx.id, &p).filter(|_| fx.id == CLASSIC_EXTRUDE);
|
||||
let mut layouts: Vec<SolidLayout> = vec![];
|
||||
let mut surfaces_before = 0usize;
|
||||
let made = built_solids_cast(&fx.id, &p, &parts, bounds, MAX_OBJECT_FACES, cast, membrane, carrier);
|
||||
let made = built_solids_cast(&fx.id, &p, &parts, bounds, object_face_limit(), cast, membrane, carrier);
|
||||
for (k, ((item, opacity, area, rule, scopes, member), f)) in parts.iter().zip(made).enumerate() {
|
||||
let item: &AppearanceItem = item;
|
||||
let layout = map_art.as_ref().map(|_| {
|
||||
@@ -2471,7 +2488,7 @@ fn surfaces_with(
|
||||
if solids.iter().any(|s| ordered(s.4)) {
|
||||
// A stroke face that passes through a fill wall or another stroke's face is cut where it
|
||||
// does. The pieces count against the limits as the faces did: cutting stops before the
|
||||
// faces pass MAX_OBJECT_FACES or their paint copies pass the allowance, so an effect that
|
||||
// faces pass object_face_limit() or their paint copies pass the allowance, so an effect that
|
||||
// draws uncut still draws.
|
||||
let counts: Vec<usize> = solids.iter().map(|(.., f, _)| f.len()).collect();
|
||||
let room = cut_room(solids.iter().map(|(item, ..)| *item), counts.iter().sum(), paint_bytes);
|
||||
@@ -2940,7 +2957,7 @@ fn frame_of(doc: Option<&Document>, n: &Node, item: Option<usize>, pick: &Pick<'
|
||||
// their handles. A stroke left out places none of its own. When a fill's solid can't be
|
||||
// built, or the solids together pass the limit, the art draws its source and no piece
|
||||
// places a handle.
|
||||
let built: Vec<Facet> = built_solids_cast(INFLATE, &p, &parts, bounds, MAX_OBJECT_FACES, false, true, None)
|
||||
let built: Vec<Facet> = built_solids_cast(INFLATE, &p, &parts, bounds, object_face_limit(), false, true, None)
|
||||
.collect::<Result<Vec<_>, String>>()
|
||||
.map(|solids| solids.into_iter().flatten().flat_map(|(f, _)| f).collect())
|
||||
.unwrap_or_default();
|
||||
@@ -3065,7 +3082,7 @@ pub fn map_surfaces_at(doc: Option<&Document>, n: &Node, item: Option<usize>, in
|
||||
let surfaces = vectorcraft_three_d::extrude_surfaces(area, *rule, bounds, options).unwrap_or_default();
|
||||
let facets = vectorcraft_three_d::extrude(area, *rule, bounds, options, view).unwrap_or_default();
|
||||
kept = kept.saturating_add(facets.len());
|
||||
if kept > MAX_OBJECT_FACES {
|
||||
if kept > object_face_limit() {
|
||||
return None;
|
||||
}
|
||||
listed(&surfaces, &facets, &mut out);
|
||||
@@ -3309,7 +3326,7 @@ fn meshes_for(fx: &Effect, shapes: &[Profile], total: &mut usize, limit: usize)
|
||||
Err(e) => return Err(e),
|
||||
};
|
||||
kept = kept.saturating_add(solid.facets.len());
|
||||
if kept > MAX_OBJECT_FACES {
|
||||
if kept > object_face_limit() {
|
||||
return Err(vectorcraft_three_d::TOO_COMPLEX_SOLID.to_string());
|
||||
}
|
||||
match solid.mesh() {
|
||||
|
||||
@@ -1642,17 +1642,36 @@ fn polygon_node(id: u64, corners: usize) -> Node {
|
||||
Node::path(NodeId(id), path, Appearance::basic(Paint::solid(RED), Paint::None, 0.0))
|
||||
}
|
||||
|
||||
/// Sets the faces the solids of one object keep together ([`OBJECT_FACE_LIMIT`]) to a lower limit
|
||||
/// on this thread, and sets [`MAX_OBJECT_FACES`] again when dropped, so that a test of the limit
|
||||
/// builds small solids.
|
||||
struct FaceLimit(usize);
|
||||
|
||||
impl FaceLimit {
|
||||
fn set(limit: usize) -> Self {
|
||||
Self(OBJECT_FACE_LIMIT.with(|l| l.replace(limit)))
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for FaceLimit {
|
||||
fn drop(&mut self) {
|
||||
OBJECT_FACE_LIMIT.with(|l| l.set(self.0));
|
||||
}
|
||||
}
|
||||
|
||||
/// A group whose members' solids each fit, but not all of them together, draws its source art, and
|
||||
/// the commands that check the effect report the error, as do its mesh and its wireframe; one
|
||||
/// member fewer, within the limit, draws.
|
||||
/// member fewer, exactly at the limit, draws. The limit is lowered to three members' faces.
|
||||
#[test]
|
||||
fn a_groups_solids_together_past_the_limit_draw_the_source() {
|
||||
let member = polygon_node(1, 16_384);
|
||||
let member = polygon_node(1, 64);
|
||||
let mut alone = member.clone();
|
||||
alone.appearance.effects.push(fx(EXTRUDE, json!({})));
|
||||
let [Ok(Some(each))] = solid_faces(EXTRUDE, &alone, MAX_OBJECT_FACES)[..] else { panic!("one solid") };
|
||||
let limit = 3 * each;
|
||||
let _limit = FaceLimit::set(limit);
|
||||
// Members stacked in one place each build the same solid.
|
||||
let fits = MAX_OBJECT_FACES / each;
|
||||
let fits = limit / each;
|
||||
let group = |count: usize| {
|
||||
let members = (0..count)
|
||||
.map(|k| {
|
||||
@@ -1703,16 +1722,19 @@ fn an_inflate_frame_places_no_handle_when_a_fill_is_past_the_limits() {
|
||||
}
|
||||
|
||||
/// A fill and strokes whose solids each fit, but not all of them together, draw the source art,
|
||||
/// and the strokes after the one past the limit are not left out to make room.
|
||||
/// and the strokes after the one past the limit are not left out to make room. The limit is
|
||||
/// lowered to the fill's faces and three strokes'.
|
||||
#[test]
|
||||
fn a_fill_and_strokes_together_past_the_limit_draw_the_source() {
|
||||
let mut n = polygon_node(1, 16_384);
|
||||
let mut n = polygon_node(1, 64);
|
||||
n.appearance.effects.push(fx(EXTRUDE, json!({})));
|
||||
let stroke = AppearanceItem::Stroke(StrokeLayer::new(Paint::solid(BLUE), 20.0));
|
||||
n.appearance.items.push(stroke.clone());
|
||||
// Strokes alike each build the same solid.
|
||||
let [Ok(Some(fill)), Ok(Some(each))] = solid_faces(EXTRUDE, &n, MAX_OBJECT_FACES)[..] else { panic!("a fill's solid and a stroke's") };
|
||||
let fits = (MAX_OBJECT_FACES - fill) / each;
|
||||
let limit = fill + 3 * each;
|
||||
let _limit = FaceLimit::set(limit);
|
||||
let fits = (limit - fill) / each;
|
||||
assert!(fits >= 2, "{fill} + {fits} × {each}");
|
||||
n.appearance.items.extend(std::iter::repeat_n(stroke, fits - 1));
|
||||
assert!(validate_solid(&n, EXTRUDE, &json!({})).is_ok(), "{fill} + {fits} × {each}");
|
||||
|
||||
@@ -12,8 +12,8 @@ use vectorcraft_three_d::Facet;
|
||||
|
||||
use super::{
|
||||
CLASSIC_EXTRUDE, CLASSIC_ROTATE, EXTRUDE, INFLATE, Profile, ROTATE, built_solids, facets, geometry, has_solid, is_container, is_plane,
|
||||
is_three_d, label_of, members, object_profile, region, reshape_members, resolve, resolve_for, solid, solid_paint_sources, solid_parts,
|
||||
union_bounds,
|
||||
is_three_d, label_of, members, object_face_limit, object_profile, region, reshape_members, resolve, resolve_for, solid, solid_paint_sources,
|
||||
solid_parts, union_bounds,
|
||||
};
|
||||
use crate::{GeomContext, is_geometry};
|
||||
|
||||
@@ -258,7 +258,7 @@ pub(crate) fn facet_paths(fx: &Effect, shapes: &[Profile]) -> Result<Vec<WireFac
|
||||
}
|
||||
let (parts, bounds) = solid_parts(shapes, b);
|
||||
// The solids the art draws, each past the limits of the object's solids together as it is.
|
||||
for f in built_solids(&fx.id, &p, &parts, bounds, vectorcraft_three_d::MAX_OBJECT_FACES) {
|
||||
for f in built_solids(&fx.id, &p, &parts, bounds, object_face_limit()) {
|
||||
out.extend(f?.iter().flatten().map(face));
|
||||
}
|
||||
Ok(out)
|
||||
|
||||
@@ -466,14 +466,16 @@ fn wireframe_mode_is_checked_against_the_edges_it_draws() {
|
||||
assert!(refused.contains("simplify the gradient"), "{refused}");
|
||||
assert_eq!(crate::validate_revolve(&n, &wire), Ok(()));
|
||||
n.appearance.effects.push(crate::new_effect(crate::REVOLVE, &wire).unwrap());
|
||||
assert!(leaves(&drawn(&n)).iter().all(|(_, filled, stroke)| !filled && stroke.is_some()));
|
||||
let edges = leaves(&drawn(&n));
|
||||
assert!(!edges.is_empty() && edges.iter().all(|(_, filled, stroke)| !filled && stroke.is_some()), "{} pieces", edges.len());
|
||||
// On the fill.
|
||||
let fx = n.appearance.effects.remove(0);
|
||||
let at = n.appearance.items.iter().position(|i| matches!(i, AppearanceItem::Fill(_))).unwrap();
|
||||
assert!(crate::revolve::validate_item_revolve(&n, &shaded, at, 0).is_err());
|
||||
assert_eq!(crate::revolve::validate_item_revolve(&n, &wire, at, 0), Ok(()));
|
||||
n.appearance.items[at].effects_mut().push(fx);
|
||||
assert!(leaves(&drawn(&n)).iter().all(|(_, filled, stroke)| !filled && stroke.is_some()));
|
||||
let edges = leaves(&drawn(&n));
|
||||
assert!(!edges.is_empty() && edges.iter().all(|(_, filled, stroke)| !filled && stroke.is_some()), "{} pieces", edges.len());
|
||||
}
|
||||
|
||||
/// A 3D (Classic) effect ignores a `render` it does not take in a loaded file: it draws as before.
|
||||
|
||||
@@ -155,6 +155,7 @@ fn fitted_dashes_on_curves_and_degenerate_paths_stay_finite() {
|
||||
s.profile = profile.clone();
|
||||
});
|
||||
let o = line_outline(&mixed, &st, 4.0, 0.01);
|
||||
assert!(!o.elements().is_empty(), "{pat:?}: the curve's dashes are drawn");
|
||||
assert!(o.elements().iter().filter_map(|e| e.end_point()).all(|p| p.x.is_finite() && p.y.is_finite()), "{pat:?}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -301,7 +301,9 @@ fn a_spread_gradient_runs_its_stops_along_the_stroke_that_many_times() {
|
||||
let mut st = stroke(10.0, mode);
|
||||
let g = Gradient { spread, repeats: 3, ..Gradient::default() };
|
||||
st.paint = Paint::Gradient(Box::new(GradientPaint::new(g.clone())));
|
||||
for s in slices(&bp, &st) {
|
||||
let pieces = slices(&bp, &st);
|
||||
assert!(!pieces.is_empty(), "{mode:?} {spread:?}: the stroke is painted in slices");
|
||||
for s in pieces {
|
||||
let Paint::Gradient(p) = s.paint(&g.unrolled()) else { panic!("a gradient slice") };
|
||||
let geom = p.geom.unwrap();
|
||||
for u in [0.1, 0.5, 0.9] {
|
||||
|
||||
@@ -247,15 +247,14 @@ fn a_warp_draws_with_the_map_its_version_names() {
|
||||
fn a_warp_bends_a_flat_box_as_the_middle_of_its_patch() {
|
||||
let anchors = |p: &PathData| p.subpaths.iter().flat_map(|s| s.anchors.clone()).collect::<Vec<_>>();
|
||||
let vertical = shapes::line(Point::new(100.0, 0.0), Point::new(100.0, 100.0));
|
||||
let out = run("warp.arc", json!({"bend": 50, "version": 1}), &vertical);
|
||||
assert!(anchors(&out).iter().all(|a| close(a.p.x, 100.0, 1e-9) && close(a.h_in.x, 100.0, 1e-9) && close(a.h_out.x, 100.0, 1e-9)), "{out:?}");
|
||||
let out = anchors(&run("warp.arc", json!({"bend": 50, "version": 1}), &vertical));
|
||||
assert!(out.len() >= 2, "{out:?}");
|
||||
assert!(out.iter().all(|a| close(a.p.x, 100.0, 1e-9) && close(a.h_in.x, 100.0, 1e-9) && close(a.h_out.x, 100.0, 1e-9)), "{out:?}");
|
||||
let horizontal = shapes::line(Point::new(0.0, 50.0), Point::new(200.0, 50.0));
|
||||
for style in ["bulge", "fisheye", "inflate", "squeeze"] {
|
||||
let out = run(&format!("warp.{style}"), json!({"bend": 50, "version": 1}), &horizontal);
|
||||
assert!(
|
||||
anchors(&out).iter().all(|a| close(a.p.y, 50.0, 1e-9) && close(a.h_in.y, 50.0, 1e-9) && close(a.h_out.y, 50.0, 1e-9)),
|
||||
"{style}: {out:?}"
|
||||
);
|
||||
let out = anchors(&run(&format!("warp.{style}"), json!({"bend": 50, "version": 1}), &horizontal));
|
||||
assert!(out.len() >= 2, "{style}: {out:?}");
|
||||
assert!(out.iter().all(|a| close(a.p.y, 50.0, 1e-9) && close(a.h_in.y, 50.0, 1e-9) && close(a.h_out.y, 50.0, 1e-9)), "{style}: {out:?}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1343,10 +1342,11 @@ fn transform_copies_of_images_stop_at_the_reach_limit() {
|
||||
fn pucker_bloat_moves_anchors_in_opposite_directions() {
|
||||
let bloat = run("distort.puckerBloat", json!({"amount": 50}), &square());
|
||||
let a = bloat.subpaths[0].anchors[0].p;
|
||||
assert!(a.x > 0.0 && a.y > 0.0, "bloat pulls corners in: {a:?}");
|
||||
// Half the amount of the way to the centre (50, 50): 25% of 50 pt.
|
||||
assert!((a.x - 12.5).abs() < 1e-9 && (a.y - 12.5).abs() < 1e-9, "bloat pulls corners in: {a:?}");
|
||||
let pucker = run("distort.puckerBloat", json!({"amount": -50}), &square());
|
||||
let a = pucker.subpaths[0].anchors[0].p;
|
||||
assert!(a.x < 0.0 && a.y < 0.0, "pucker pushes corners out: {a:?}");
|
||||
assert!((a.x + 12.5).abs() < 1e-9 && (a.y + 12.5).abs() < 1e-9, "pucker pushes corners out: {a:?}");
|
||||
assert_eq!(run("distort.puckerBloat", json!({"amount": 0}), &square()), square());
|
||||
}
|
||||
|
||||
@@ -2083,18 +2083,6 @@ fn bad_params_fall_back_to_defaults() {
|
||||
assert!(close(out.bounds().unwrap().width(), 124.0, 0.1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn bench_catalog_lookup() {
|
||||
let t = std::time::Instant::now();
|
||||
let mut n = 0;
|
||||
for _ in 0..10_000 {
|
||||
n += crate::is_geometry("distort.roughen") as usize;
|
||||
n += crate::merged_params("stylize.dropShadow", &serde_json::Value::Null).as_object().unwrap().len();
|
||||
}
|
||||
eprintln!("10k lookups: {:?} ({n})", t.elapsed());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_repeat_of_a_symbol_whose_art_is_a_repeat_shares_the_instance_budget() {
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -1035,10 +1035,11 @@ fn a_baked_group_with_type_keeps_a_shadow_on_each_copy() {
|
||||
use vectorcraft_doc::text::{CharStyle, TextObject};
|
||||
let style = CharStyle { size: 40.0, fill: Paint::solid(Color::BLACK), ..Default::default() };
|
||||
let words = Node::new(NodeId(161), vectorcraft_doc::NodeKind::Text(Box::new(TextObject::point(Point::new(5.0, 60.0), "IIII", style))));
|
||||
if !crate::outline_text(&words).is_some_and(|o| paths_in(&o) > 0) {
|
||||
if !fonts() {
|
||||
eprintln!("skipped: built without fonts (enable vectorcraft-text's bundled-fonts to run it)");
|
||||
return;
|
||||
}
|
||||
assert!(crate::outline_text(&words).is_some_and(|o| paths_in(&o) > 0), "the type outlines to paths");
|
||||
let g = group(160, vec![words, square(162, vec![])], vec![shadow(10.0, 0.0, 0.0), transform(json!({"moveH": 150, "copies": 1}))]);
|
||||
let b = baked(g);
|
||||
assert!(near(&shadows_in(&b), &[(10.0, 0.0), (10.0, 0.0)]), "{:?}", shadows_in(&b));
|
||||
@@ -1640,6 +1641,17 @@ fn type_node(id: u64, effects: Vec<Effect>) -> Node {
|
||||
n
|
||||
}
|
||||
|
||||
/// Whether the face of the default character style is installed, so that type lays out glyphs.
|
||||
/// When it is, `type_node`'s type must outline to paths.
|
||||
fn fonts() -> bool {
|
||||
let style = vectorcraft_doc::text::CharStyle::default();
|
||||
if vectorcraft_text::FontDb::global().face(&style.font_family, &style.font_style).is_none() {
|
||||
return false;
|
||||
}
|
||||
assert!(crate::outline_text(&type_node(95, vec![])).is_some_and(|o| paths_in(&o) > 0), "{}: the type outlines to paths", style.font_family);
|
||||
true
|
||||
}
|
||||
|
||||
/// An instance at (50, 50) with `effects` of a symbol, and the symbol's art: a black 20 pt square
|
||||
/// centered on its origin.
|
||||
fn instance(id: u64, effects: Vec<Effect>) -> (Node, Node) {
|
||||
@@ -1660,7 +1672,7 @@ fn instance(id: u64, effects: Vec<Effect>) -> (Node, Node) {
|
||||
/// image and the instance are checked.
|
||||
#[test]
|
||||
fn each_copy_of_type_an_image_or_a_symbol_instance_carries_the_shadow_listed_before_it() {
|
||||
let fonts = crate::outline_text(&type_node(95, vec![])).is_some_and(|o| paths_in(&o) > 0);
|
||||
let fonts = fonts();
|
||||
if !fonts {
|
||||
eprintln!("type skipped: built without fonts (enable vectorcraft-text's bundled-fonts to run it)");
|
||||
}
|
||||
@@ -1702,7 +1714,7 @@ fn each_copy_of_type_an_image_or_a_symbol_instance_carries_the_shadow_listed_bef
|
||||
/// listed before that effect, as the canvas draws it, rather than staying type under one shadow.
|
||||
#[test]
|
||||
fn baked_type_whose_transform_moves_its_copies_keeps_a_shadow_on_each() {
|
||||
if !crate::outline_text(&type_node(99, vec![])).is_some_and(|o| paths_in(&o) > 0) {
|
||||
if !fonts() {
|
||||
eprintln!("skipped: built without fonts (enable vectorcraft-text's bundled-fonts to run it)");
|
||||
return;
|
||||
}
|
||||
@@ -1738,7 +1750,7 @@ fn type_carries_its_fills_shadow_on_each_copy() {
|
||||
n
|
||||
};
|
||||
let copying = vec![shadow(10.0, 0.0, 0.0), transform(json!({"moveH": 100, "copies": 1}))];
|
||||
if !crate::outline_text(&type_node(95, vec![])).is_some_and(|o| paths_in(&o) > 0) {
|
||||
if !fonts() {
|
||||
eprintln!("type skipped: built without fonts (enable vectorcraft-text's bundled-fonts to run it)");
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -72,10 +72,11 @@ serde_json = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
log = { workspace = true }
|
||||
|
||||
# Whether a recovery area folder is this account's own (`FolderStore::own_area`). Already in
|
||||
# Cargo.lock (tempfile, ui-egui), so this adds no new crate.
|
||||
# Whether a recovery area folder is this account's own (`FolderStore::own_area`), and opening a
|
||||
# file without following a link (`store::read_capped_plain`). Already in Cargo.lock (tempfile,
|
||||
# ui-egui), so this adds no new crate.
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
rustix = { workspace = true, features = ["std", "process"] }
|
||||
rustix = { workspace = true, features = ["std", "process", "fs"] }
|
||||
|
||||
# Whether a recovery area's lock file is still the one that was opened (`FolderStore::still_named`),
|
||||
# and whether two paths a script names are one file (`script::files`). Already in Cargo.lock
|
||||
@@ -116,7 +117,7 @@ zune-core = { workspace = true }
|
||||
# JPEG XL files for the import fuzz tests (tests/import_fuzz.rs).
|
||||
craft-jxl = { workspace = true }
|
||||
# vectorcraft-doc's Group 3 TIFF reader before craft-stream-codecs, the reference
|
||||
# tests/group3_reference.rs compares it with.
|
||||
# tests/it/group3_reference.rs compares it with.
|
||||
hayro-ccitt = { workspace = true }
|
||||
craft-stream-codecs = { workspace = true }
|
||||
vectorcraft-affinity = { workspace = true, features = ["synth"] }
|
||||
@@ -143,3 +144,14 @@ ruzstd = { workspace = true }
|
||||
vectorcraft-js = { workspace = true }
|
||||
# A bundled font's own glyph boxes, for the glyph bounds tests.
|
||||
skrifa = { workspace = true }
|
||||
|
||||
# The files of other crates that this crate compiles or its tests read, for CI's test selection.
|
||||
[package.metadata.craft]
|
||||
reads = [
|
||||
"crates/affinity/tests/support/corpus.rs",
|
||||
"crates/affinity/tests/support/text_fixture.rs",
|
||||
"crates/apischema/src/conformance.rs",
|
||||
"crates/plugins/tests/fixtures/desaturate.wasm",
|
||||
"xtask/affinity-corpus.sha256",
|
||||
"xtask/src/sha256.rs",
|
||||
]
|
||||
|
||||
@@ -111,6 +111,7 @@ mod textedit;
|
||||
|
||||
pub use textedit::effective_kerning;
|
||||
mod retype;
|
||||
mod stepandrepeat;
|
||||
pub mod textstyles;
|
||||
pub(crate) mod textwrap;
|
||||
pub(crate) mod threads;
|
||||
@@ -327,6 +328,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
|
||||
v.extend(layerpanel::specs());
|
||||
v.extend(draw2::specs());
|
||||
v.extend(xform::specs());
|
||||
v.extend(stepandrepeat::specs());
|
||||
v.extend(effectcmd::specs());
|
||||
v.extend(bevels::specs());
|
||||
v.extend(wireframe::specs());
|
||||
@@ -677,8 +679,24 @@ pub fn matrix_param(p: &Value, key: &str) -> Option<Affine> {
|
||||
}
|
||||
/// A colour from `"#rrggbb"`, a colour key (`"cmyk 0 100 100 0"`, `"lab 55 60 40"`), `[r,g,b]` (0..1),
|
||||
/// `{"c":..,"m":..,"y":..,"k":..}` (percent when any component is above 1, else 0..1), `{"gray":..}` or `{"l":..,"a":..,"b":..}` (CIE Lab: L 0..100, a and b about
|
||||
/// −128..127). `None` for a hex color with an alpha part (`#rrggbbaa` or `#rgba`, with or without the `#`).
|
||||
/// −128..127). `None` for a hex color with an alpha part (`#rrggbbaa` or `#rgba`, with or without the `#`),
|
||||
/// and for a color with a component too large to store ([`color_is_finite`]).
|
||||
pub fn color_value(v: &Value) -> Option<Color> {
|
||||
given_color(v).filter(color_is_finite)
|
||||
}
|
||||
|
||||
/// Is every component of `c` finite? A number past `f32::MAX`, such as `{"c": 1e300}`, is stored
|
||||
/// as an infinity.
|
||||
pub fn color_is_finite(c: &Color) -> bool {
|
||||
match *c {
|
||||
Color::Rgb { r, g, b } | Color::Lab { l: r, a: g, b } => [r, g, b].iter().all(|x| x.is_finite()),
|
||||
Color::Cmyk { c, m, y, k } => [c, m, y, k].iter().all(|x| x.is_finite()),
|
||||
Color::Gray { k } => k.is_finite(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The color `v` gives, as [`color_value`] reads it, with its components unchecked.
|
||||
fn given_color(v: &Value) -> Option<Color> {
|
||||
match v {
|
||||
Value::String(s) if hex_with_alpha(s) => None,
|
||||
// A hex, or a colour key ("cmyk 0 100 100 0", as Recolor Artwork lists colours).
|
||||
@@ -874,6 +892,9 @@ pub(crate) use vectorcraft_doc::range::parse_range;
|
||||
/// What the fill and stroke proxies read from the selected objects, kept with the selection
|
||||
/// ([`crate::doc_state::SelectionRecord`]).
|
||||
pub(crate) use paint::SelectionPaints;
|
||||
/// The faces and edges of Live Paint groups among objects that count with their group
|
||||
/// ([`crate::DocState::live_paint_covered_kept`] keeps an empty answer).
|
||||
pub(crate) use paint::live_paint_covered;
|
||||
#[cfg(test)]
|
||||
pub(crate) use paint::{PAINTS_READ, WEIGHTS_READ};
|
||||
|
||||
@@ -981,7 +1002,8 @@ pub use variablecmds::{VariableSort, VariableSortKey, variable_order};
|
||||
|
||||
/// Command ids kept only so older scripts keep working: `(alias, the command it duplicates)`.
|
||||
/// They run as before but the command palette leaves them out (it lists the command once).
|
||||
pub const ALIASES: &[(&str, &str)] = &[("object.convertDocumentColorMode", "file.documentColorMode")];
|
||||
pub const ALIASES: &[(&str, &str)] =
|
||||
&[("object.convertDocumentColorMode", "file.documentColorMode"), ("addon.pathtools.bridge", "addon.pathtools.commonTangents")];
|
||||
|
||||
/// Is `id` an [`ALIASES`] entry?
|
||||
pub fn is_alias(id: &str) -> bool {
|
||||
|
||||
@@ -5,11 +5,14 @@
|
||||
//! 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. 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
|
||||
//! objects whose visual bounds overlap, Group by Row groups them by the rows (or columns) their
|
||||
//! visual bounds share, 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
|
||||
//! (a view command) are the UI's.
|
||||
//! that order. Mark Bounds of Each ([`marks`]) draws marks on the bounds of each selected object.
|
||||
//! Its submenu (Object › Plug-ins › Arrange Tools), its dialogs and Zoom to Selection (a view
|
||||
//! command) are the UI's.
|
||||
|
||||
pub mod marks;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
@@ -18,7 +21,7 @@ use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::recolor::Rng;
|
||||
use vectorcraft_doc::{Node, NodeId, OrientedBox};
|
||||
use vectorcraft_doc::{Node, NodeId, NodeKind, OrientedBox};
|
||||
use vectorcraft_geom::{Affine, Point, Rect, Vec2};
|
||||
use vectorcraft_render::effects;
|
||||
|
||||
@@ -108,6 +111,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_multi,
|
||||
group_overlapping
|
||||
),
|
||||
cmd!(
|
||||
"addon.arrange.groupRows",
|
||||
"Group by Row",
|
||||
["Object", "Plug-ins", "Arrange Tools"],
|
||||
None,
|
||||
"{direction?: \"row\" (objects whose vertical extents overlap) | \"column\" (objects whose horizontal extents overlap) (\"row\" when omitted; null is invalid)} group the selected objects (the top-level ones, at most 20000) into one group for each row (column), as one undo step. Parameters must be an object. An object joins a row when its visual bounds overlap the row's extent across it. Measurement includes strokes and vector effects, measures a clipping group by its mask, and excludes raster effects such as shadows, glows, and blurs. Extents that only touch stay apart, and an object that overlaps two rows joins them into one. Only objects in the same layer or group and on the same artboard (the one holding the object's center, else the one it overlaps most) share a row. Objects outside all artboards, locked or hidden objects, clipping masks, layers, and sublayers stay in place. Every grouping candidate must have a parent that is a layer or group. The command rejects selections containing editable live blend keys, direct children of Shaper groups, live compound shapes, Objects on Path groups, or Live Paint groups, and any descendants of live graphs. Complete live groups and graphs can be grouped with other artwork. An object alone in its row stays as it is, and each new group goes where its frontmost member was in the stacking order; the new groups (top to bottom, or left to right) and the objects left alone stay selected. A run with no row of two or more objects makes no step → {groups: [id…], grouped (how many objects went into groups)}",
|
||||
has_multi,
|
||||
group_rows
|
||||
),
|
||||
cmd!(
|
||||
"addon.arrange.randomizeOpacity",
|
||||
"Randomize Opacity",
|
||||
@@ -127,6 +139,9 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
sort
|
||||
),
|
||||
]
|
||||
.into_iter()
|
||||
.chain(marks::specs())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Exactly two objects are selected (Swap Objects).
|
||||
@@ -577,11 +592,110 @@ fn group_overlapping(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
roots.iter().filter_map(|id| Some((*id, (d.parent_of(*id), effects::preview::bounds_of(d, &[*id], true)?)))).collect();
|
||||
let keyed: Vec<(Option<NodeId>, Rect)> = items.iter().map(|(_, k)| *k).collect();
|
||||
let sets: Vec<Vec<NodeId>> = overlapping(&keyed).into_iter().map(|set| set.iter().filter_map(|i| Some(items.get(*i)?.0)).collect()).collect();
|
||||
group_each(s, "Group Overlapping Objects", &roots, sets)
|
||||
}
|
||||
|
||||
/// The rows of `items` (each a key and an extent `(start, end)` along the axis across the rows): the sets of
|
||||
/// two or more (each in the order given) among items of the same key whose extents overlap, chains included.
|
||||
/// Extents that only touch stay apart. Sorted by start, then by end, each item joins its key's open row when it
|
||||
/// starts before that row ends, so the rows come out in order along the axis, and an extent with no length at
|
||||
/// another's start stays apart from it whatever their order. Adding 0.0 turns -0.0 into 0.0, which
|
||||
/// `total_cmp` would otherwise order first.
|
||||
fn rows_of<K: Eq + std::hash::Hash + Copy>(items: &[(K, (f64, f64))]) -> Vec<Vec<usize>> {
|
||||
let items: Vec<(K, (f64, f64))> = items.iter().map(|(k, (start, end))| (*k, (start + 0.0, end + 0.0))).collect();
|
||||
let mut order: Vec<usize> = (0..items.len()).collect();
|
||||
order.sort_by(|a, b| items[*a].1.0.total_cmp(&items[*b].1.0).then(items[*a].1.1.total_cmp(&items[*b].1.1)));
|
||||
let mut rows: Vec<Vec<usize>> = vec![];
|
||||
// Each key's open row: its index in `rows` and where it ends.
|
||||
let mut open: HashMap<K, (usize, f64)> = HashMap::new();
|
||||
for i in order {
|
||||
let (key, (start, end)) = items[i];
|
||||
match open.get_mut(&key) {
|
||||
Some((row, until)) if start < *until => {
|
||||
if let Some(r) = rows.get_mut(*row) {
|
||||
r.push(i);
|
||||
}
|
||||
*until = until.max(end);
|
||||
}
|
||||
_ => {
|
||||
open.insert(key, (rows.len(), end));
|
||||
rows.push(vec![i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
rows.retain(|r| r.len() > 1);
|
||||
for r in &mut rows {
|
||||
r.sort_unstable();
|
||||
}
|
||||
rows
|
||||
}
|
||||
|
||||
fn group_rows(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "addon.arrange.groupRows";
|
||||
if !p.is_object() {
|
||||
return Err(bad(C, "parameters must be an object"));
|
||||
}
|
||||
if p.get("direction").is_some_and(Value::is_null) {
|
||||
return Err(bad(C, "`direction` must be row or column"));
|
||||
}
|
||||
let rows = choice(p, C, "direction", &["row", "column"])?.unwrap_or("row") == "row";
|
||||
let roots = selected_roots(s)?;
|
||||
if roots.len() > MAX_OBJECTS {
|
||||
return Err(bad(C, "too many objects selected (at most 20000)"));
|
||||
}
|
||||
let d = &s.doc()?.doc;
|
||||
let editable_roots: Vec<_> = {
|
||||
let editable = d.editable();
|
||||
roots.iter().copied().filter(|id| editable(*id) && d.node(*id).is_some_and(|n| !n.is_layer())).collect()
|
||||
};
|
||||
for id in &editable_roots {
|
||||
let parent = d.parent_of(*id);
|
||||
let valid_parent = parent.and_then(|parent| d.node(parent)).is_some_and(|n| {
|
||||
matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. })
|
||||
&& !n.is_compound_shape()
|
||||
&& n.extras().shaper.is_none()
|
||||
&& n.extras().objects_on_path.is_none()
|
||||
&& !vectorcraft_tools::builder::is_live_paint(n)
|
||||
});
|
||||
let in_graph = parent
|
||||
.and_then(|parent| d.ancestry(parent))
|
||||
.is_some_and(|ancestors| ancestors.iter().any(|ancestor| d.node(*ancestor).is_some_and(|n| n.extras().graph.is_some())));
|
||||
if !valid_parent || in_graph {
|
||||
return Err(bad(C, "selected objects must be in a layer or group without live structural roles"));
|
||||
}
|
||||
}
|
||||
// Each object's row key (its parent and its artboard) and its extent across the rows.
|
||||
type Keyed = ((NodeId, usize), (f64, f64));
|
||||
let symbols = d.symbol_boxes();
|
||||
let items: Vec<(NodeId, Keyed)> = editable_roots
|
||||
.iter()
|
||||
.filter_map(|id| {
|
||||
let parent = d.parent_of(*id)?;
|
||||
let container = d.node(parent)?;
|
||||
if container.clips() && container.children().and_then(|c| c.first()).is_some_and(|c| c.id == *id) {
|
||||
return None;
|
||||
}
|
||||
let b = effects::preview::visual_bounds(&symbols.unmeasured(), d.node(*id)?)?;
|
||||
let extent = if rows { (b.y0, b.y1) } else { (b.x0, b.x1) };
|
||||
Some((*id, ((parent, d.artboard_for_bounds(b)?), extent)))
|
||||
})
|
||||
.collect();
|
||||
let keyed: Vec<_> = items.iter().map(|(_, k)| *k).collect();
|
||||
let sets: Vec<Vec<NodeId>> = rows_of(&keyed).into_iter().map(|set| set.iter().filter_map(|i| Some(items.get(*i)?.0)).collect()).collect();
|
||||
let mut selection = roots;
|
||||
selection.extend(s.doc()?.selection.objects.iter().copied().filter(|id| d.node(*id).is_some_and(|n| n.is_layer())));
|
||||
group_each(s, if rows { "Group by Row" } else { "Group by Column" }, &selection, sets)
|
||||
}
|
||||
|
||||
/// Put each of `sets` (two or more of the selected top-level objects `roots`, each in stacking order) into a
|
||||
/// new group of its own at its frontmost member's place, as undo step `label`, and select the new groups and
|
||||
/// the objects of `roots` left alone. No step when `sets` is empty.
|
||||
fn group_each(s: &mut Session, label: &str, roots: &[NodeId], sets: Vec<Vec<NodeId>>) -> Result<Value> {
|
||||
if sets.is_empty() {
|
||||
return Ok(json!({ "groups": [], "grouped": 0 }));
|
||||
}
|
||||
let grouped: std::collections::HashSet<NodeId> = sets.iter().flatten().copied().collect();
|
||||
let groups = s.edit("Group Overlapping Objects", |d, sel| {
|
||||
let groups = s.edit(label, |d, sel| {
|
||||
// Every group at once: the members behind each front one go, then each front one is
|
||||
// replaced by its group (one pass over the tree each, however many groups).
|
||||
let (mut places, mut behind, mut groups) = (vec![], vec![], vec![]);
|
||||
|
||||
@@ -0,0 +1,162 @@
|
||||
//! Mark Bounds of Each (`addon.arrange.markBounds`; Object › Plug-ins › Arrange Tools › Mark Bounds
|
||||
//! of Each…): corner marks, or a rectangle, on the bounds of each selected object rather than
|
||||
//! around the whole selection, stroked in a color of their own and stacked directly above the
|
||||
//! object, as one undo step.
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, Document, Node, NodeId};
|
||||
use vectorcraft_geom::{PathData, Point, Rect, SubPath, shapes};
|
||||
use vectorcraft_render::drawn_bounds_with;
|
||||
|
||||
use super::super::super::edit::selected_roots;
|
||||
use super::super::super::object::choice;
|
||||
use super::super::super::paint::new_color;
|
||||
use super::super::super::{CommandSpec, bad, cmd, color_param, has_selection};
|
||||
use super::{LEAST, LIMIT, MAX_OBJECTS, number_in};
|
||||
use crate::{Result, Session};
|
||||
|
||||
/// The command.
|
||||
pub const COMMAND: &str = "addon.arrange.markBounds";
|
||||
/// The heaviest stroke (pt) the marks take, and the lightest.
|
||||
const MAX_WEIGHT: f64 = 1000.0;
|
||||
const MIN_WEIGHT: f64 = 0.01;
|
||||
/// A side shorter than this (pt) is no side: its marks are drawn as lines along the other one.
|
||||
const FLAT: f64 = 1e-9;
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![cmd!(
|
||||
"addon.arrange.markBounds",
|
||||
"Mark Bounds of Each",
|
||||
["Object", "Plug-ins", "Arrange Tools"],
|
||||
None,
|
||||
"{style?: \"corners\" (an L-shaped mark on each corner, its two legs running inward along the edges) | \"rectangle\" (a rectangle on the bounds) (\"corners\"), bounds?: \"geometric\" (strokes not counted) | \"visual\" (strokes, brush art and effects as drawn) (\"geometric\"), length?: pt 0.001..1000000 (10; corners: each leg's length, at most half the side it runs along), weight?: pt 0.01..1000 (1), color?: color (\"#ff0000\"; an RGB color takes the document's color mode)} draw marks on the bounds of each selected object (the top-level ones, at most 20000) as new art: a group of four corner marks, or one rectangle, with no fill and the stroke given, stacked directly above its object (above the outermost clip group or clipping sublayer that holds it, so the clip does not hide them). A clip group is measured by its clipping path and other groups by their members together. Guides, objects without bounds such as empty groups, and (for corners) objects whose sides are too short for any leg get no marks. The marks are selected; one undo step, and none when nothing gets marks (an error) → {ids: [the new marks…], count}",
|
||||
has_selection,
|
||||
mark_bounds
|
||||
)]
|
||||
}
|
||||
|
||||
/// The four corners of `r`, each with the directions its legs run in (inward), the corners that
|
||||
/// fall on an earlier one left out.
|
||||
fn corners(r: Rect) -> Vec<(Point, f64, f64)> {
|
||||
let mut out: Vec<(Point, f64, f64)> = vec![];
|
||||
for (x, y, sx, sy) in [(r.x0, r.y0, 1.0, 1.0), (r.x1, r.y0, -1.0, 1.0), (r.x1, r.y1, -1.0, -1.0), (r.x0, r.y1, 1.0, -1.0)] {
|
||||
let at = Point::new(x, y);
|
||||
if out.iter().all(|(p, _, _)| (p.x - at.x).abs() > FLAT || (p.y - at.y).abs() > FLAT) {
|
||||
out.push((at, sx, sy));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The lengths of the across and down legs of the corner marks of `r`: `length`, at most half the
|
||||
/// side each runs along.
|
||||
fn legs(r: Rect, length: f64) -> (f64, f64) {
|
||||
(length.min(r.width() / 2.0), length.min(r.height() / 2.0))
|
||||
}
|
||||
|
||||
/// The corner marks of `r` with legs `length` long, each at most half its side: one open path per
|
||||
/// corner, a line where `r` has no width or no height.
|
||||
fn corner_paths(r: Rect, length: f64) -> Vec<PathData> {
|
||||
let (lx, ly) = legs(r, length);
|
||||
corners(r)
|
||||
.into_iter()
|
||||
.filter_map(|(p, sx, sy)| {
|
||||
let across = Point::new(p.x + sx * lx, p.y);
|
||||
let down = Point::new(p.x, p.y + sy * ly);
|
||||
let points = match (lx > FLAT, ly > FLAT) {
|
||||
(true, true) => vec![across, p, down],
|
||||
(true, false) => vec![across, p],
|
||||
(false, true) => vec![p, down],
|
||||
(false, false) => return None,
|
||||
};
|
||||
Some(PathData::single(SubPath::polyline(&points, false)))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Where the marks of object `id` go: directly above it, or above the outermost clip group or
|
||||
/// clipping sublayer that holds it at any depth, which would otherwise clip them. A top-level layer
|
||||
/// with a clipping mask holds its marks too, since nothing lies outside it.
|
||||
fn anchor(d: &Document, id: NodeId) -> NodeId {
|
||||
let (mut at, mut outermost) = (id, id);
|
||||
while let Some(up) = d.parent_of(at) {
|
||||
if d.node(up).is_some_and(|n| n.clips()) && d.parent_of(up).is_some() {
|
||||
outermost = up;
|
||||
}
|
||||
at = up;
|
||||
}
|
||||
outermost
|
||||
}
|
||||
|
||||
fn mark_bounds(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = COMMAND;
|
||||
let rectangle = choice(p, C, "style", &["corners", "rectangle"])? == Some("rectangle");
|
||||
let visual = choice(p, C, "bounds", &["geometric", "visual"])? == Some("visual");
|
||||
let length = number_in(p, "length", 10.0, (LEAST, LIMIT), C)?;
|
||||
let weight = number_in(p, "weight", 1.0, (MIN_WEIGHT, MAX_WEIGHT), C)?;
|
||||
let color = new_color(s, p, color_param(p, "color", C)?.unwrap_or(Color::rgb(1.0, 0.0, 0.0)));
|
||||
let roots = selected_roots(s)?;
|
||||
if roots.len() > MAX_OBJECTS {
|
||||
return Err(bad(C, "too many objects selected (at most 20000)"));
|
||||
}
|
||||
let d = &s.doc()?.doc;
|
||||
let symbols = d.symbol_boxes();
|
||||
let mut marked: Vec<(NodeId, Rect)> = Vec::with_capacity(roots.len());
|
||||
let mut too_small = false;
|
||||
for id in roots {
|
||||
let Some(n) = d.node(id).filter(|n| !n.is_guide()) else { continue };
|
||||
let bounds = if visual { drawn_bounds_with(&symbols, n) } else { n.geometric_bounds_with(&symbols) };
|
||||
let Some(r) = bounds.filter(|r| r.width() > FLAT || r.height() > FLAT) else { continue };
|
||||
// Corner legs are at most half a side, so an object too small for any leg gets no marks.
|
||||
let (lx, ly) = legs(r, length);
|
||||
if rectangle || lx > FLAT || ly > FLAT {
|
||||
marked.push((anchor(d, id), r));
|
||||
} else {
|
||||
too_small = true;
|
||||
}
|
||||
}
|
||||
if marked.is_empty() {
|
||||
if too_small {
|
||||
return Err(bad(C, "nothing to mark: the selection is too small for corner marks"));
|
||||
}
|
||||
return Err(bad(C, "nothing to mark: the selection has no bounds"));
|
||||
}
|
||||
let ap = Appearance::basic(Paint::None, Paint::solid(color), weight);
|
||||
let ids = s.edit("Mark Bounds of Each", |d, sel| {
|
||||
// Each anchor once, its objects' marks in stacking order from the back.
|
||||
let mut lists: Vec<(NodeId, Vec<Node>)> = vec![];
|
||||
let mut at: HashMap<NodeId, usize> = HashMap::new();
|
||||
let mut out = Vec::with_capacity(marked.len());
|
||||
for (anchor, r) in &marked {
|
||||
let node = if rectangle {
|
||||
let mut n = Node::path(d.alloc_id(), shapes::rectangle(*r), ap.clone());
|
||||
n.name = Some("Bounds".into());
|
||||
n
|
||||
} else {
|
||||
let children = corner_paths(*r, length).into_iter().map(|path| Arc::new(Node::path(d.alloc_id(), path, ap.clone()))).collect();
|
||||
let mut g = Node::group(d.alloc_id(), children);
|
||||
g.name = Some("Corner Marks".into());
|
||||
g
|
||||
};
|
||||
out.push(node.id);
|
||||
let k = *at.entry(*anchor).or_insert_with(|| {
|
||||
lists.push((*anchor, vec![]));
|
||||
lists.len() - 1
|
||||
});
|
||||
if let Some((_, nodes)) = lists.get_mut(k) {
|
||||
nodes.push(node);
|
||||
}
|
||||
}
|
||||
d.insert_beside(lists, false)?;
|
||||
sel.set(out.iter().copied());
|
||||
Ok(out)
|
||||
})?;
|
||||
Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "count": ids.len() }))
|
||||
}
|
||||
@@ -0,0 +1,375 @@
|
||||
//! Mark Bounds of Each: the marks each object gets, where they go in the stacking order, how
|
||||
//! groups, clip groups, strokes and guides are measured, one undo step, and bad params refused.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::{Node, NodeId};
|
||||
use vectorcraft_geom::Rect;
|
||||
|
||||
use super::COMMAND;
|
||||
use crate::Session;
|
||||
|
||||
/// A new document whose new art has no stroke, so visual and geometric bounds agree.
|
||||
fn session() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn rect(s: &mut Session, x: f64, y: f64, w: f64, h: f64) -> NodeId {
|
||||
NodeId(s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": w, "height": h})).unwrap()["id"].as_u64().unwrap())
|
||||
}
|
||||
|
||||
fn select(s: &mut Session, ids: &[NodeId]) {
|
||||
s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})).unwrap();
|
||||
}
|
||||
|
||||
fn steps(s: &Session) -> usize {
|
||||
s.doc().unwrap().history.undo.len()
|
||||
}
|
||||
|
||||
fn node(s: &Session, id: NodeId) -> Node {
|
||||
s.doc().unwrap().doc.node(id).unwrap().clone()
|
||||
}
|
||||
|
||||
fn ids_of(v: &Value) -> Vec<NodeId> {
|
||||
v["ids"].as_array().unwrap().iter().map(|i| NodeId(i.as_u64().unwrap())).collect()
|
||||
}
|
||||
|
||||
/// The ids of the children of `parent`, in stacking order from the back.
|
||||
fn children(s: &Session, parent: NodeId) -> Vec<NodeId> {
|
||||
node(s, parent).children().unwrap().iter().map(|n| n.id).collect()
|
||||
}
|
||||
|
||||
fn parent(s: &Session, id: NodeId) -> NodeId {
|
||||
s.doc().unwrap().doc.parent_of(id).unwrap()
|
||||
}
|
||||
|
||||
/// Each path of the mark `id` (a group's members, or the path itself) as its points.
|
||||
fn lines(s: &Session, id: NodeId) -> Vec<Vec<(f64, f64)>> {
|
||||
let n = node(s, id);
|
||||
let paths: Vec<Node> = match n.children() {
|
||||
Some(c) => c.iter().map(|c| (**c).clone()).collect(),
|
||||
None => vec![n],
|
||||
};
|
||||
paths
|
||||
.iter()
|
||||
.map(|p| {
|
||||
let path = p.path_data().unwrap();
|
||||
path.subpaths[0].anchors.iter().map(|a| ((a.p.x * 1e6).round() / 1e6, (a.p.y * 1e6).round() / 1e6)).collect()
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn near(a: Rect, b: (f64, f64, f64, f64)) -> bool {
|
||||
[(a.x0, b.0), (a.y0, b.1), (a.x1, b.2), (a.y1, b.3)].iter().all(|(x, y)| (x - y).abs() < 1e-6)
|
||||
}
|
||||
|
||||
fn marks_bounds(s: &Session, id: NodeId) -> Rect {
|
||||
node(s, id).geometric_bounds().unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_object_gets_inward_corner_marks_above_it_in_one_step() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 100.0, 50.0);
|
||||
let b = rect(&mut s, 200.0, 100.0, 40.0, 40.0);
|
||||
let layer = parent(&s, a);
|
||||
select(&mut s, &[a, b]);
|
||||
let n = steps(&s);
|
||||
let r = s.execute(COMMAND, &json!({})).unwrap();
|
||||
assert_eq!(steps(&s), n + 1, "one undo step");
|
||||
let marks = ids_of(&r);
|
||||
assert_eq!((marks.len(), r["count"].as_u64()), (2, Some(2)));
|
||||
// Directly above each object, not around the selection.
|
||||
assert_eq!(children(&s, layer), vec![a, marks[0], b, marks[1]]);
|
||||
assert_eq!(s.doc().unwrap().selection.objects.to_vec(), marks, "the marks are selected");
|
||||
assert_eq!(node(&s, marks[0]).name.as_deref(), Some("Corner Marks"));
|
||||
assert_eq!(
|
||||
lines(&s, marks[0]),
|
||||
vec![
|
||||
vec![(10.0, 0.0), (0.0, 0.0), (0.0, 10.0)],
|
||||
vec![(90.0, 0.0), (100.0, 0.0), (100.0, 10.0)],
|
||||
vec![(90.0, 50.0), (100.0, 50.0), (100.0, 40.0)],
|
||||
vec![(10.0, 50.0), (0.0, 50.0), (0.0, 40.0)],
|
||||
]
|
||||
);
|
||||
assert!(near(marks_bounds(&s, marks[1]), (200.0, 100.0, 240.0, 140.0)));
|
||||
// A red 1 pt stroke and no fill.
|
||||
let group = node(&s, marks[1]);
|
||||
let ap = &group.children().unwrap()[0].appearance;
|
||||
assert_eq!((ap.fill_paint(), ap.stroke_paint(), ap.stroke_width()), (Paint::None, Paint::solid(Color::rgb(1.0, 0.0, 0.0)), 1.0));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(children(&s, layer), vec![a, b]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn length_weight_color_and_the_rectangle_style() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 30.0, 100.0);
|
||||
select(&mut s, &[a]);
|
||||
let r = s.execute(COMMAND, &json!({"length": 40, "weight": 2.5, "color": "#0000ff"})).unwrap();
|
||||
let marks = ids_of(&r);
|
||||
// A leg is never longer than half its side, so opposite marks do not overlap.
|
||||
assert_eq!(lines(&s, marks[0])[0], vec![(15.0, 0.0), (0.0, 0.0), (0.0, 40.0)]);
|
||||
let group = node(&s, marks[0]);
|
||||
let ap = &group.children().unwrap()[0].appearance;
|
||||
assert_eq!((ap.stroke_paint(), ap.stroke_width()), (Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 2.5));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
let r = s.execute(COMMAND, &json!({"style": "rectangle"})).unwrap();
|
||||
let mark = ids_of(&r)[0];
|
||||
let rect = node(&s, mark);
|
||||
assert!(rect.children().is_none() && rect.path_data().unwrap().subpaths[0].closed, "one closed path");
|
||||
assert_eq!(rect.name.as_deref(), Some("Bounds"));
|
||||
assert!(near(marks_bounds(&s, mark), (0.0, 0.0, 30.0, 100.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_leg_is_at_most_half_the_side_it_runs_along_vertically() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 200.0, 20.0);
|
||||
select(&mut s, &[a]);
|
||||
let r = s.execute(COMMAND, &json!({"length": 30})).unwrap();
|
||||
assert_eq!(
|
||||
lines(&s, ids_of(&r)[0]),
|
||||
vec![
|
||||
vec![(30.0, 0.0), (0.0, 0.0), (0.0, 10.0)],
|
||||
vec![(170.0, 0.0), (200.0, 0.0), (200.0, 10.0)],
|
||||
vec![(170.0, 20.0), (200.0, 20.0), (200.0, 10.0)],
|
||||
vec![(30.0, 20.0), (0.0, 20.0), (0.0, 10.0)],
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn geometric_bounds_leave_strokes_out_and_visual_bounds_count_them() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0);
|
||||
select(&mut s, &[a]);
|
||||
s.execute("paint.setStroke", &json!({"color": "#000000"})).unwrap();
|
||||
s.execute("stroke.set", &json!({"weight": 4})).unwrap();
|
||||
let r = s.execute(COMMAND, &json!({"style": "rectangle"})).unwrap();
|
||||
assert!(near(marks_bounds(&s, ids_of(&r)[0]), (0.0, 0.0, 20.0, 20.0)), "{:?}", marks_bounds(&s, ids_of(&r)[0]));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
let r = s.execute(COMMAND, &json!({"style": "rectangle", "bounds": "visual"})).unwrap();
|
||||
assert!(near(marks_bounds(&s, ids_of(&r)[0]), (-2.0, -2.0, 22.0, 22.0)), "{:?}", marks_bounds(&s, ids_of(&r)[0]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn visual_bounds_enclose_a_drop_shadow_and_geometric_bounds_leave_it_out() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 50.0, 50.0, 20.0, 20.0);
|
||||
select(&mut s, &[a]);
|
||||
let geometry = marks_bounds(&s, a);
|
||||
let (dx, dy) = (12.0, 8.0);
|
||||
s.execute("effect.apply", &json!({"effect": "stylize.dropShadow", "item": null, "params": {"x": dx, "y": dy, "blur": 0}})).unwrap();
|
||||
let shadow = Rect::new(geometry.x0 + dx, geometry.y0 + dy, geometry.x1 + dx, geometry.y1 + dy);
|
||||
let reach = geometry.union(shadow);
|
||||
let encloses = |r: Rect| r.x0 <= reach.x0 && r.y0 <= reach.y0 && r.x1 >= reach.x1 && r.y1 >= reach.y1;
|
||||
|
||||
let r = s.execute(COMMAND, &json!({"style": "rectangle", "bounds": "geometric"})).unwrap();
|
||||
let geometric = marks_bounds(&s, ids_of(&r)[0]);
|
||||
assert!(near(geometric, (geometry.x0, geometry.y0, geometry.x1, geometry.y1)));
|
||||
assert!(!encloses(geometric), "the geometric mark leaves the shadow outside");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
|
||||
let r = s.execute(COMMAND, &json!({"style": "rectangle", "bounds": "visual"})).unwrap();
|
||||
let visual = marks_bounds(&s, ids_of(&r)[0]);
|
||||
assert!(encloses(visual), "the visual mark encloses the artwork and its shadow: {visual:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn visual_bounds_enclose_brush_art_on_paths_and_in_groups() {
|
||||
for grouped in [false, true] {
|
||||
let mut s = session();
|
||||
let path = NodeId(s.execute("shape.line", &json!({"x1": 50, "y1": 50, "x2": 150, "y2": 50})).unwrap()["id"].as_u64().unwrap());
|
||||
select(&mut s, &[path]);
|
||||
s.execute("paint.setStroke", &json!({"color": "#000000"})).unwrap();
|
||||
s.execute("stroke.set", &json!({"weight": 1})).unwrap();
|
||||
s.execute("brush.apply", &json!({"name": "Dots"})).unwrap();
|
||||
let target = if grouped {
|
||||
s.execute("object.group", &json!({})).unwrap();
|
||||
parent(&s, path)
|
||||
} else {
|
||||
path
|
||||
};
|
||||
select(&mut s, &[target]);
|
||||
let geometry = marks_bounds(&s, path);
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let source = d.node(target).unwrap();
|
||||
let painted = vectorcraft_render::painted_bounds(d, source).unwrap();
|
||||
let drawn = vectorcraft_render::drawn_bounds(d, source).unwrap();
|
||||
let base = vectorcraft_render::effect_bounds(&d.symbol_boxes(), source).unwrap();
|
||||
assert!(drawn.y0 < base.y0 && drawn.y1 > base.y1, "brush art reaches past the base stroke: {drawn:?}, {base:?}");
|
||||
let encloses = |r: Rect| r.x0 <= drawn.x0 && r.y0 <= drawn.y0 && r.x1 >= drawn.x1 && r.y1 >= drawn.y1;
|
||||
|
||||
let r = s.execute(COMMAND, &json!({"style": "rectangle", "bounds": "geometric"})).unwrap();
|
||||
let geometric = marks_bounds(&s, ids_of(&r)[0]);
|
||||
assert!(near(geometric, (geometry.x0, geometry.y0, geometry.x1, geometry.y1)));
|
||||
assert!(!encloses(geometric), "the geometric mark leaves brush art outside");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
|
||||
let r = s.execute(COMMAND, &json!({"style": "rectangle", "bounds": "visual"})).unwrap();
|
||||
let visual = marks_bounds(&s, ids_of(&r)[0]);
|
||||
assert!(near(visual, (drawn.x0, drawn.y0, drawn.x1, drawn.y1)), "the visual mark follows the drawn bounds: {visual:?}, {drawn:?}");
|
||||
assert!(encloses(visual), "the visual mark encloses the brush art: {visual:?}, {drawn:?}");
|
||||
assert!(
|
||||
visual.x0 > painted.x0 && visual.y0 > painted.y0 && visual.x1 < painted.x1 && visual.y1 < painted.y1,
|
||||
"the visual mark stays inside the culling margin: {visual:?}, {painted:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn groups_by_their_members_and_clip_groups_by_the_clipping_path() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
|
||||
let b = rect(&mut s, 50.0, 30.0, 10.0, 10.0);
|
||||
select(&mut s, &[a, b]);
|
||||
s.execute("object.group", &json!({})).unwrap();
|
||||
let group = parent(&s, a);
|
||||
let art = rect(&mut s, 100.0, 100.0, 200.0, 150.0);
|
||||
let clip = rect(&mut s, 150.0, 120.0, 50.0, 40.0);
|
||||
select(&mut s, &[art, clip]);
|
||||
s.execute("object.clippingMask.make", &json!({})).unwrap();
|
||||
let clip_group = parent(&s, art);
|
||||
let layer = parent(&s, group);
|
||||
select(&mut s, &[group, clip_group]);
|
||||
let r = s.execute(COMMAND, &json!({"style": "rectangle"})).unwrap();
|
||||
let marks = ids_of(&r);
|
||||
assert!(near(marks_bounds(&s, marks[0]), (0.0, 0.0, 60.0, 40.0)), "the members together");
|
||||
assert!(near(marks_bounds(&s, marks[1]), (150.0, 120.0, 200.0, 160.0)), "the clipping path");
|
||||
assert_eq!(children(&s, layer), vec![group, marks[0], clip_group, marks[1]]);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
// An object inside the clip group: its marks go above the clip group, where it does not hide them.
|
||||
select(&mut s, &[art]);
|
||||
let r = s.execute(COMMAND, &json!({})).unwrap();
|
||||
let mark = ids_of(&r)[0];
|
||||
assert_eq!(children(&s, layer), vec![group, clip_group, mark]);
|
||||
assert!(near(marks_bounds(&s, mark), (100.0, 100.0, 300.0, 250.0)), "the object's own bounds");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
// And when a plain group lies between the object and the clip group.
|
||||
select(&mut s, &[art]);
|
||||
s.execute("object.group", &json!({})).unwrap();
|
||||
let inner = parent(&s, art);
|
||||
let clip_group = parent(&s, clip);
|
||||
assert_eq!(parent(&s, inner), clip_group);
|
||||
select(&mut s, &[art]);
|
||||
let r = s.execute(COMMAND, &json!({})).unwrap();
|
||||
assert_eq!(children(&s, layer), vec![group, clip_group, ids_of(&r)[0]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn marks_go_outside_a_clipping_sublayer_but_stay_in_a_clipping_top_layer() {
|
||||
let mut s = session();
|
||||
let top = s.doc().unwrap().current_layer().unwrap();
|
||||
let sub = NodeId(s.execute("layer.newSublayer", &json!({"parent": top.0})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("layer.setCurrent", &json!({"id": sub.0})).unwrap();
|
||||
let art = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
|
||||
rect(&mut s, 20.0, 20.0, 10.0, 10.0);
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
assert!(s.execute("layer.clippingMask.toggle", &json!({"id": sub.0})).unwrap()["clip"].as_bool().unwrap());
|
||||
select(&mut s, &[art]);
|
||||
let r = s.execute(COMMAND, &json!({})).unwrap();
|
||||
assert_eq!(children(&s, top), vec![sub, ids_of(&r)[0]], "above the clipping sublayer");
|
||||
|
||||
// A clipping top-level layer has nothing outside it to hold them: they go above the object.
|
||||
let mut s = session();
|
||||
let top = s.doc().unwrap().current_layer().unwrap();
|
||||
let art = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
|
||||
rect(&mut s, 20.0, 20.0, 10.0, 10.0);
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
assert!(s.execute("layer.clippingMask.toggle", &json!({"id": top.0})).unwrap()["clip"].as_bool().unwrap());
|
||||
select(&mut s, &[art]);
|
||||
let r = s.execute(COMMAND, &json!({})).unwrap();
|
||||
let mark = ids_of(&r)[0];
|
||||
let stack = children(&s, top);
|
||||
assert_eq!(stack.iter().position(|id| *id == mark), stack.iter().position(|id| *id == art).map(|i| i + 1), "{stack:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flat_objects_get_lines_and_guides_and_empty_groups_none() {
|
||||
let mut s = session();
|
||||
let line = NodeId(s.execute("shape.line", &json!({"x1": 0, "y1": 50, "x2": 100, "y2": 50})).unwrap()["id"].as_u64().unwrap());
|
||||
select(&mut s, &[line]);
|
||||
let r = s.execute(COMMAND, &json!({})).unwrap();
|
||||
// No height: one mark at each end, along the line.
|
||||
assert_eq!(lines(&s, ids_of(&r)[0]), vec![vec![(10.0, 50.0), (0.0, 50.0)], vec![(90.0, 50.0), (100.0, 50.0)]]);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
|
||||
let guide = rect(&mut s, 0.0, 0.0, 20.0, 20.0);
|
||||
select(&mut s, &[guide]);
|
||||
s.execute("view.guides.make", &json!({})).unwrap();
|
||||
select(&mut s, &[guide]);
|
||||
let layer = s.doc().unwrap().target_parent().unwrap();
|
||||
let empty = s
|
||||
.edit("test", |d, _| {
|
||||
let g = Node::group(d.alloc_id(), vec![]);
|
||||
let id = g.id;
|
||||
d.insert(layer, usize::MAX, g)?;
|
||||
Ok(id)
|
||||
})
|
||||
.unwrap();
|
||||
select(&mut s, &[guide, empty]);
|
||||
let (before, n) = (s.doc().unwrap().doc.clone(), steps(&s));
|
||||
let refused = s.execute(COMMAND, &json!({})).unwrap_err().to_string();
|
||||
assert!(refused.contains("nothing to mark"), "{refused}");
|
||||
assert_eq!(steps(&s), n, "no undo step");
|
||||
assert!(*s.doc().unwrap().doc == *before);
|
||||
// With a real object as well, only it gets marks.
|
||||
let a = rect(&mut s, 100.0, 100.0, 20.0, 20.0);
|
||||
select(&mut s, &[guide, empty, a]);
|
||||
let r = s.execute(COMMAND, &json!({})).unwrap();
|
||||
assert_eq!(r["count"], 1);
|
||||
assert!(near(marks_bounds(&s, ids_of(&r)[0]), (100.0, 100.0, 120.0, 120.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_object_too_small_for_corner_legs_gets_no_empty_group() {
|
||||
let mut s = session();
|
||||
// Wider than the flat limit, but each leg (half the side at most) is shorter than it.
|
||||
let tiny = NodeId(s.execute("shape.line", &json!({"x1": 0, "y1": 50, "x2": 1.5e-9, "y2": 50})).unwrap()["id"].as_u64().unwrap());
|
||||
select(&mut s, &[tiny]);
|
||||
let (before, n) = (s.doc().unwrap().doc.clone(), steps(&s));
|
||||
let refused = s.execute(COMMAND, &json!({})).unwrap_err().to_string();
|
||||
assert!(refused.contains("nothing to mark") && refused.contains("too small for corner marks"), "{refused}");
|
||||
assert_eq!(steps(&s), n, "no undo step");
|
||||
assert!(*s.doc().unwrap().doc == *before);
|
||||
// The rectangle style still marks it, and a real object beside it gets its corner marks alone.
|
||||
let r = s.execute(COMMAND, &json!({"style": "rectangle"})).unwrap();
|
||||
assert_eq!(r["count"], 1);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
let a = rect(&mut s, 100.0, 100.0, 20.0, 20.0);
|
||||
select(&mut s, &[tiny, a]);
|
||||
let r = s.execute(COMMAND, &json!({})).unwrap();
|
||||
assert_eq!(r["count"], 1);
|
||||
assert!(near(marks_bounds(&s, ids_of(&r)[0]), (100.0, 100.0, 120.0, 120.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_params_are_refused_and_it_is_off_without_a_selection() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 20.0, 10.0);
|
||||
select(&mut s, &[a]);
|
||||
let (before, n) = (s.doc().unwrap().doc.clone(), steps(&s));
|
||||
for p in [
|
||||
json!({"style": "cross"}),
|
||||
json!({"bounds": "preview"}),
|
||||
json!({"length": 0}),
|
||||
json!({"length": 1e7}),
|
||||
json!({"length": "10"}),
|
||||
json!({"weight": 0}),
|
||||
json!({"weight": 1001}),
|
||||
json!({"color": "not a color"}),
|
||||
json!({"color": "#ff000080"}),
|
||||
json!({"color": 3}),
|
||||
] {
|
||||
assert!(s.execute(COMMAND, &p).is_err(), "{p}");
|
||||
}
|
||||
assert_eq!(steps(&s), n);
|
||||
assert!(*s.doc().unwrap().doc == *before);
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
assert!(!s.commands().into_iter().find(|c| c.id == COMMAND).unwrap().enabled);
|
||||
assert!(s.execute(COMMAND, &json!({})).is_err());
|
||||
}
|
||||
@@ -779,6 +779,7 @@ fn off_without_a_selection() {
|
||||
"addon.arrange.size",
|
||||
"addon.arrange.match",
|
||||
"addon.arrange.groupOverlapping",
|
||||
"addon.arrange.groupRows",
|
||||
"addon.arrange.randomizeOpacity",
|
||||
"addon.arrange.sort",
|
||||
] {
|
||||
@@ -862,6 +863,503 @@ fn group_overlapping_is_off_with_one_object_and_scales_to_many() {
|
||||
assert!(sets.iter().all(|s| s.len() == 2 && s[1] == s[0] + 1));
|
||||
}
|
||||
|
||||
fn layer_children(s: &Session) -> Vec<NodeId> {
|
||||
s.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|n| n.id).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_rows_groups_each_row_and_leaves_loners() {
|
||||
let mut s = session();
|
||||
// Row one: a and b (y 0 to 12). c only touches it (from y 12), alone in its row. Row two: d and e.
|
||||
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
|
||||
let d = rect(&mut s, 0.0, 40.0, 10.0, 10.0);
|
||||
let b = rect(&mut s, 20.0, 2.0, 10.0, 10.0);
|
||||
let c = rect(&mut s, 40.0, 12.0, 10.0, 10.0);
|
||||
let e = rect(&mut s, 20.0, 45.0, 10.0, 10.0);
|
||||
select(&mut s, &[a, b, c, d, e]);
|
||||
let n = steps(&s);
|
||||
let r = s.execute("addon.arrange.groupRows", &json!({})).unwrap();
|
||||
assert_eq!(steps(&s), n + 1, "one undo step");
|
||||
assert_eq!(r["grouped"], json!(4));
|
||||
let groups = ids_of(&r["groups"]);
|
||||
assert_eq!(groups.len(), 2);
|
||||
assert_eq!(children(&s, groups[0]), [a, b], "the top row first, its members in stacking order");
|
||||
assert_eq!(children(&s, groups[1]), [d, e]);
|
||||
// Each group where its frontmost member was: a d b c e → group(ab) at b, c, group(de) at e.
|
||||
assert_eq!(layer_children(&s), [groups[0], c, groups[1]]);
|
||||
let sel = &s.doc().unwrap().selection.objects;
|
||||
assert!(sel.contains(&groups[0]) && sel.contains(&groups[1]) && sel.contains(&c) && sel.len() == 3, "{sel:?}");
|
||||
assert_eq!(s.doc().unwrap().history.undo.last().map(|step| step.label.as_str()), Some("Group by Row"));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(layer_children(&s), [a, d, b, c, e]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_rows_makes_columns_and_joins_rows_an_object_spans() {
|
||||
let mut s = session();
|
||||
// Columns: a and b share x 0 to 15, c stands apart.
|
||||
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
|
||||
let b = rect(&mut s, 5.0, 50.0, 10.0, 10.0);
|
||||
let c = rect(&mut s, 30.0, 0.0, 10.0, 10.0);
|
||||
select(&mut s, &[a, b, c]);
|
||||
let r = s.execute("addon.arrange.groupRows", &json!({"direction": "column"})).unwrap();
|
||||
let groups = ids_of(&r["groups"]);
|
||||
assert_eq!(groups.len(), 1);
|
||||
assert_eq!(children(&s, groups[0]), [a, b]);
|
||||
assert_eq!(s.doc().unwrap().history.undo.last().map(|step| step.label.as_str()), Some("Group by Column"));
|
||||
// By row, p and q lie in two rows until r, reaching from one to the other, joins them.
|
||||
let mut s = session();
|
||||
let p = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
|
||||
let q = rect(&mut s, 50.0, 20.0, 10.0, 10.0);
|
||||
select(&mut s, &[p, q]);
|
||||
let n = steps(&s);
|
||||
let r = s.execute("addon.arrange.groupRows", &json!({"direction": "row"})).unwrap();
|
||||
assert_eq!((r["grouped"].clone(), steps(&s)), (json!(0), n), "two rows of one: no groups, no step");
|
||||
let bridge = rect(&mut s, 100.0, 5.0, 10.0, 20.0);
|
||||
select(&mut s, &[p, q, bridge]);
|
||||
let r = s.execute("addon.arrange.groupRows", &json!({"direction": "row"})).unwrap();
|
||||
let groups = ids_of(&r["groups"]);
|
||||
assert_eq!(groups.len(), 1);
|
||||
assert_eq!(children(&s, groups[0]), [p, q, bridge]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_rows_keeps_layers_and_artboards_apart_and_measures_visual_bounds() {
|
||||
let mut s = session();
|
||||
s.execute("artboard.new", &json!({"x": 500, "y": 0, "width": 200, "height": 300})).unwrap();
|
||||
let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0);
|
||||
// Touching a's bottom edge: a row of its own until strokes reach over the edge.
|
||||
let below = rect(&mut s, 50.0, 20.0, 20.0, 20.0);
|
||||
let far = rect(&mut s, 550.0, 0.0, 20.0, 20.0);
|
||||
s.execute("layer.new", &json!({})).unwrap();
|
||||
let other = rect(&mut s, 100.0, 0.0, 20.0, 20.0);
|
||||
select(&mut s, &[a, below, far, other]);
|
||||
let n = steps(&s);
|
||||
let r = s.execute("addon.arrange.groupRows", &json!({})).unwrap();
|
||||
assert_eq!((r["grouped"].clone(), steps(&s)), (json!(0), n), "another artboard, another layer, a touching edge: no groups");
|
||||
select(&mut s, &[a, below]);
|
||||
s.execute("paint.setStroke", &json!({"color": "#000000"})).unwrap();
|
||||
s.execute("stroke.set", &json!({"weight": 4})).unwrap();
|
||||
select(&mut s, &[a, below, far, other]);
|
||||
let r = s.execute("addon.arrange.groupRows", &json!({})).unwrap();
|
||||
let groups = ids_of(&r["groups"]);
|
||||
assert_eq!(groups.len(), 1);
|
||||
assert_eq!(children(&s, groups[0]), [a, below], "the strokes overlap");
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
assert_ne!(doc.parent_of(far), Some(groups[0]), "left on its own artboard");
|
||||
assert_ne!(doc.layer_of(other), doc.layer_of(a), "left in its own layer");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_rows_measures_clipping_groups_by_their_mask() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0);
|
||||
// A 200 tall object clipped to a 30 tall mask at y 100.
|
||||
let clipped = rect(&mut s, 50.0, 0.0, 10.0, 200.0);
|
||||
let mask = rect(&mut s, 40.0, 100.0, 30.0, 30.0);
|
||||
select(&mut s, &[clipped, mask]);
|
||||
s.execute("object.clippingMask.make", &json!({})).unwrap();
|
||||
let group = s.doc().unwrap().selection.objects[0];
|
||||
let b = rect(&mut s, 100.0, 110.0, 10.0, 10.0);
|
||||
select(&mut s, &[a, group, b]);
|
||||
let r = s.execute("addon.arrange.groupRows", &json!({})).unwrap();
|
||||
let groups = ids_of(&r["groups"]);
|
||||
assert_eq!(groups.len(), 1);
|
||||
assert_eq!(children(&s, groups[0]), [group, b], "the mask's row, not the clipped art's");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_rows_keeps_clipping_masks_first_in_groups_and_layers() {
|
||||
for clipping_layer in [false, true] {
|
||||
let mut s = session();
|
||||
let mask = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
|
||||
let a = rect(&mut s, 10.0, 10.0, 20.0, 20.0);
|
||||
let b = rect(&mut s, 40.0, 10.0, 20.0, 20.0);
|
||||
select(&mut s, &[mask, a, b]);
|
||||
let parent = if clipping_layer {
|
||||
s.doc().unwrap().doc.layers[0].id
|
||||
} else {
|
||||
s.execute("object.group", &json!({})).unwrap();
|
||||
s.doc().unwrap().selection.objects[0]
|
||||
};
|
||||
s.edit("Set clipping", |d, _| {
|
||||
d.node_mut(parent).unwrap().set_clips(true);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
select(&mut s, &[mask, a]);
|
||||
let n = steps(&s);
|
||||
let r = s.execute("addon.arrange.groupRows", &json!({})).unwrap();
|
||||
assert_eq!((r["grouped"].clone(), steps(&s)), (json!(0), n));
|
||||
assert_eq!(children(&s, parent), [mask, a, b]);
|
||||
select(&mut s, &[mask, a, b]);
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let r = s.execute("addon.arrange.groupRows", &json!({})).unwrap();
|
||||
let groups = ids_of(&r["groups"]);
|
||||
assert_eq!(r["grouped"], json!(2));
|
||||
assert_eq!(children(&s, parent), [mask, groups[0]]);
|
||||
assert_eq!(children(&s, groups[0]), [a, b]);
|
||||
assert!(s.doc().unwrap().selection.objects.contains(&mask));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(*s.doc().unwrap().doc == *before);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_rows_leaves_selected_layers_and_sublayers_in_place() {
|
||||
for sublayers in [false, true] {
|
||||
let mut s = session();
|
||||
let parent = s.doc().unwrap().doc.layers[0].id;
|
||||
let mut layers = vec![];
|
||||
for _ in 0..2 {
|
||||
let command = if sublayers { "layer.newSublayer" } else { "layer.new" };
|
||||
let params = if sublayers { json!({"parent": parent.0}) } else { json!({"top": true}) };
|
||||
let layer = NodeId(s.execute(command, ¶ms).unwrap()["id"].as_u64().unwrap());
|
||||
rect(&mut s, 10.0, 10.0, 20.0, 20.0);
|
||||
layers.push(layer);
|
||||
}
|
||||
s.execute("layer.setCurrent", &json!({"id": parent.0})).unwrap();
|
||||
let a = rect(&mut s, 10.0, 10.0, 20.0, 20.0);
|
||||
let b = rect(&mut s, 15.0, 15.0, 20.0, 20.0);
|
||||
for direction in ["row", "column"] {
|
||||
select(&mut s, &layers);
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let n = steps(&s);
|
||||
let r = s.execute("addon.arrange.groupRows", &json!({"direction": direction})).unwrap();
|
||||
assert_eq!(r["grouped"], json!(0), "layers must not become ordinary group members");
|
||||
assert_eq!(steps(&s), n);
|
||||
assert!(*s.doc().unwrap().doc == *before);
|
||||
select(&mut s, &[layers[0], layers[1], a, b]);
|
||||
let r = s.execute("addon.arrange.groupRows", &json!({"direction": direction})).unwrap();
|
||||
assert_eq!(r["grouped"], json!(2));
|
||||
let groups = ids_of(&r["groups"]);
|
||||
assert_eq!(children(&s, groups[0]), [a, b]);
|
||||
for layer in &layers {
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(*layer), sublayers.then_some(parent));
|
||||
assert!(s.doc().unwrap().selection.objects.contains(layer));
|
||||
}
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(*s.doc().unwrap().doc == *before);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_rows_refuses_objects_without_a_parent() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 10.0, 10.0, 20.0, 20.0);
|
||||
let b = rect(&mut s, 15.0, 15.0, 20.0, 20.0);
|
||||
s.edit("Set root objects", |d, _| {
|
||||
for id in [a, b] {
|
||||
let node = d.remove(id)?;
|
||||
d.layers.push(node);
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
select(&mut s, &[a, b]);
|
||||
refuses(&mut s, "addon.arrange.groupRows", &[json!({"direction": "row"}), json!({"direction": "column"})]);
|
||||
}
|
||||
|
||||
fn refuse_row_parts_and_group_whole(s: &mut Session, group: NodeId, parts: &[Vec<NodeId>]) {
|
||||
let center = bounds(s, group).center();
|
||||
let a = rect(s, center.x - 10.0, center.y - 10.0, 20.0, 20.0);
|
||||
let b = rect(s, center.x - 5.0, center.y - 5.0, 20.0, 20.0);
|
||||
let members = children(s, group);
|
||||
for direction in ["row", "column"] {
|
||||
for selected in parts {
|
||||
select(s, selected);
|
||||
let selection = s.doc().unwrap().selection.clone();
|
||||
refuses(s, "addon.arrange.groupRows", &[json!({"direction": direction})]);
|
||||
assert_eq!(s.doc().unwrap().selection, selection);
|
||||
let mut mixed = selected.clone();
|
||||
mixed.extend([a, b]);
|
||||
select(s, &mixed);
|
||||
refuses(s, "addon.arrange.groupRows", &[json!({"direction": direction})]);
|
||||
assert_eq!(children(s, group), members);
|
||||
}
|
||||
select(s, &[group, a, b]);
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let n = steps(s);
|
||||
let r = s.execute("addon.arrange.groupRows", &json!({"direction": direction})).unwrap();
|
||||
assert_eq!(r["grouped"], json!(3));
|
||||
let groups = ids_of(&r["groups"]);
|
||||
assert_eq!(children(s, groups[0]), [group, a, b]);
|
||||
assert_eq!(children(s, group), members);
|
||||
assert_eq!(steps(s), n + 1);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(*s.doc().unwrap().doc == *before);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_rows_refuses_objects_on_path_children_but_groups_the_whole_group() {
|
||||
let mut s = session();
|
||||
let path = rect(&mut s, 20.0, 20.0, 100.0, 100.0);
|
||||
let member = rect(&mut s, 30.0, 30.0, 20.0, 20.0);
|
||||
let group = NodeId(s.execute("object.objectsOnPath.attach", &json!({"path": path.0, "ids": [member.0]})).unwrap()["id"].as_u64().unwrap());
|
||||
refuse_row_parts_and_group_whole(&mut s, group, &[vec![path, member]]);
|
||||
assert!(s.doc().unwrap().doc.node(group).unwrap().extras().objects_on_path.is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_rows_refuses_live_paint_faces_and_edges_but_groups_the_whole_group() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
|
||||
let b = rect(&mut s, 50.0, 0.0, 100.0, 100.0);
|
||||
select(&mut s, &[a, b]);
|
||||
let group = NodeId(s.execute("livePaint.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
let node = s.doc().unwrap().doc.node(group).unwrap();
|
||||
let faces: Vec<_> = vectorcraft_tools::builder::faces(node).iter().map(|n| n.id).collect();
|
||||
let edges: Vec<_> = vectorcraft_tools::builder::edges(node).iter().map(|n| n.id).collect();
|
||||
assert!(faces.len() >= 2);
|
||||
assert!(edges.len() >= 2);
|
||||
refuse_row_parts_and_group_whole(&mut s, group, &[faces.clone(), edges.clone()]);
|
||||
let node = s.doc().unwrap().doc.node(group).unwrap();
|
||||
assert_eq!(vectorcraft_tools::builder::faces(node).iter().map(|n| n.id).collect::<Vec<_>>(), faces);
|
||||
assert_eq!(vectorcraft_tools::builder::edges(node).iter().map(|n| n.id).collect::<Vec<_>>(), edges);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_rows_refuses_live_graph_descendants_but_groups_the_whole_graph() {
|
||||
let mut s = session();
|
||||
let params = json!({"type": "column", "x": 20, "y": 20, "width": 200, "height": 200, "csv": ",Series\nA,3\nB,5"});
|
||||
let graph = NodeId(s.execute("graph.create", ¶ms).unwrap()["id"].as_u64().unwrap());
|
||||
let node = s.doc().unwrap().doc.node(graph).unwrap();
|
||||
let series = node.children().unwrap().iter().find(|n| n.extras().series_index == Some(0)).unwrap();
|
||||
let marks: Vec<_> = series.children().unwrap().iter().take(2).map(|n| n.id).collect();
|
||||
assert_eq!(marks.len(), 2);
|
||||
let direct = children(&s, graph);
|
||||
refuse_row_parts_and_group_whole(&mut s, graph, &[marks, direct]);
|
||||
assert!(s.doc().unwrap().doc.node(graph).unwrap().extras().graph.is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_rows_refuses_explicitly_selected_live_blend_keys() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0);
|
||||
let b = rect(&mut s, 30.0, 0.0, 20.0, 20.0);
|
||||
select(&mut s, &[a, b]);
|
||||
s.execute("object.blend.make", &json!({})).unwrap();
|
||||
let blend = s.doc().unwrap().selection.objects[0];
|
||||
let c = rect(&mut s, 60.0, 0.0, 20.0, 20.0);
|
||||
let d = rect(&mut s, 90.0, 0.0, 20.0, 20.0);
|
||||
select(&mut s, &[a, b]);
|
||||
refuses(&mut s, "addon.arrange.groupRows", &[json!({})]);
|
||||
select(&mut s, &[a, b, c, d]);
|
||||
refuses(&mut s, "addon.arrange.groupRows", &[json!({})]);
|
||||
assert_eq!(children(&s, blend), [a, b]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_rows_refuses_explicitly_selected_shaper_children() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
|
||||
let b = rect(&mut s, 50.0, 0.0, 100.0, 100.0);
|
||||
select(&mut s, &[a, b]);
|
||||
let shaper = NodeId(s.execute("shaper.scribble", &json!({"points": [[25, 25], [125, 25]]})).unwrap()["id"].as_u64().unwrap());
|
||||
let members = children(&s, shaper);
|
||||
assert!(members.len() >= 2);
|
||||
let sources = members[0];
|
||||
let face = s
|
||||
.doc()
|
||||
.unwrap()
|
||||
.doc
|
||||
.node(shaper)
|
||||
.unwrap()
|
||||
.children()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.find(|n| n.name.as_deref().is_some_and(|name| name.starts_with(vectorcraft_doc::shaper::FILL_PREFIX)))
|
||||
.unwrap()
|
||||
.id;
|
||||
let c = rect(&mut s, 200.0, 0.0, 20.0, 20.0);
|
||||
let d = rect(&mut s, 230.0, 0.0, 20.0, 20.0);
|
||||
for direction in ["row", "column"] {
|
||||
select(&mut s, &[sources, face]);
|
||||
refuses(&mut s, "addon.arrange.groupRows", &[json!({"direction": direction})]);
|
||||
select(&mut s, &[sources, face, c, d]);
|
||||
refuses(&mut s, "addon.arrange.groupRows", &[json!({"direction": direction})]);
|
||||
assert_eq!(children(&s, shaper), members);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_rows_refuses_explicitly_selected_live_compound_shape_operands() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 30.0, 30.0);
|
||||
let b = rect(&mut s, 10.0, 0.0, 30.0, 30.0);
|
||||
select(&mut s, &[a, b]);
|
||||
s.execute("object.compoundShape.make", &json!({"mode": "subtract"})).unwrap();
|
||||
let shape = s.doc().unwrap().selection.objects[0];
|
||||
let c = rect(&mut s, 200.0, 0.0, 20.0, 20.0);
|
||||
let d = rect(&mut s, 230.0, 0.0, 20.0, 20.0);
|
||||
for direction in ["row", "column"] {
|
||||
select(&mut s, &[a, b]);
|
||||
refuses(&mut s, "addon.arrange.groupRows", &[json!({"direction": direction})]);
|
||||
select(&mut s, &[a, b, c, d]);
|
||||
refuses(&mut s, "addon.arrange.groupRows", &[json!({"direction": direction})]);
|
||||
assert_eq!(children(&s, shape), [a, b]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_rows_skips_explicitly_selected_locked_and_hidden_objects() {
|
||||
for command in ["object.lock", "object.hide"] {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0);
|
||||
let b = rect(&mut s, 30.0, 0.0, 20.0, 20.0);
|
||||
let c = rect(&mut s, 60.0, 0.0, 20.0, 20.0);
|
||||
select(&mut s, &[b]);
|
||||
s.execute(command, &json!({})).unwrap();
|
||||
select(&mut s, &[a, b, c]);
|
||||
assert!(s.doc().unwrap().selection.objects.contains(&b));
|
||||
let r = s.execute("addon.arrange.groupRows", &json!({})).unwrap();
|
||||
let groups = ids_of(&r["groups"]);
|
||||
assert_eq!(r["grouped"], json!(2));
|
||||
assert_eq!(children(&s, groups[0]), [a, c]);
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(b), Some(s.doc().unwrap().doc.layers[0].id));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_rows_leaves_objects_outside_all_artboards_ungrouped() {
|
||||
for direction in ["row", "column"] {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 500.0, 500.0, 20.0, 20.0);
|
||||
let b = rect(&mut s, 505.0, 505.0, 20.0, 20.0);
|
||||
select(&mut s, &[a, b]);
|
||||
let (before, n) = (s.doc().unwrap().doc.clone(), steps(&s));
|
||||
let r = s.execute("addon.arrange.groupRows", &json!({"direction": direction})).unwrap();
|
||||
assert_eq!((r["grouped"].clone(), steps(&s)), (json!(0), n));
|
||||
assert!(*s.doc().unwrap().doc == *before);
|
||||
let c = rect(&mut s, 0.0, 0.0, 20.0, 20.0);
|
||||
let d = rect(&mut s, 5.0, 5.0, 20.0, 20.0);
|
||||
select(&mut s, &[a, b, c, d]);
|
||||
let r = s.execute("addon.arrange.groupRows", &json!({"direction": direction})).unwrap();
|
||||
let groups = ids_of(&r["groups"]);
|
||||
assert_eq!(r["grouped"], json!(2));
|
||||
assert_eq!(children(&s, groups[0]), [c, d]);
|
||||
assert_eq!(layer_children(&s), [a, b, groups[0]]);
|
||||
let sel = &s.doc().unwrap().selection.objects;
|
||||
assert!(sel.contains(&a) && sel.contains(&b));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_rows_documents_and_excludes_raster_effects_from_bounds() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0);
|
||||
select(&mut s, &[a]);
|
||||
s.execute("effect.apply", &json!({"effect": "stylize.dropShadow", "params": {"x": 0, "y": 5, "blur": 0}})).unwrap();
|
||||
let b = rect(&mut s, 0.0, 21.0, 20.0, 20.0);
|
||||
select(&mut s, &[a, b]);
|
||||
let n = steps(&s);
|
||||
let r = s.execute("addon.arrange.groupRows", &json!({})).unwrap();
|
||||
assert_eq!((r["grouped"].clone(), steps(&s)), (json!(0), n));
|
||||
assert_eq!(layer_children(&s), [a, b]);
|
||||
let spec = super::specs().into_iter().find(|c| c.id == "addon.arrange.groupRows").unwrap();
|
||||
assert!(spec.params.contains("excludes raster effects"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_rows_is_off_with_one_object_skips_locked_ones_and_refuses_bad_params() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0);
|
||||
select(&mut s, &[a]);
|
||||
assert!(!enabled(&s, "addon.arrange.groupRows"));
|
||||
let b = rect(&mut s, 30.0, 0.0, 20.0, 20.0);
|
||||
let c = rect(&mut s, 60.0, 0.0, 20.0, 20.0);
|
||||
select(&mut s, &[a, b, c]);
|
||||
assert!(enabled(&s, "addon.arrange.groupRows"));
|
||||
refuses(
|
||||
&mut s,
|
||||
"addon.arrange.groupRows",
|
||||
&[json!({"direction": "diagonal"}), json!({"direction": 3}), json!({"direction": true}), json!({"direction": null})],
|
||||
);
|
||||
select(&mut s, &[b]);
|
||||
s.execute("object.lock", &json!({})).unwrap();
|
||||
s.execute("select.all", &json!({})).unwrap();
|
||||
let r = s.execute("addon.arrange.groupRows", &json!({})).unwrap();
|
||||
let groups = ids_of(&r["groups"]);
|
||||
assert_eq!(groups.len(), 1);
|
||||
assert_eq!(children(&s, groups[0]), [a, c], "the locked object stays out");
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(b), Some(s.doc().unwrap().doc.layers[0].id));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_rows_refuses_non_object_params_without_an_edit() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0);
|
||||
let b = rect(&mut s, 30.0, 0.0, 20.0, 20.0);
|
||||
select(&mut s, &[a, b]);
|
||||
let selection = s.doc().unwrap().selection.objects.clone();
|
||||
refuses(&mut s, "addon.arrange.groupRows", &[json!([]), json!(["row"]), json!("row"), json!(true), json!(3)]);
|
||||
assert_eq!(s.doc().unwrap().selection.objects, selection);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_rows_reads_the_symbol_index_once_for_all_members() {
|
||||
use std::sync::Arc;
|
||||
use vectorcraft_doc::{Appearance, Document, Node, NodeKind, Symbol};
|
||||
use vectorcraft_geom::Affine;
|
||||
|
||||
let mut d = Document::new(400.0, 300.0);
|
||||
for i in 0..200 {
|
||||
let art = Node::path(d.alloc_id(), vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art());
|
||||
d.symbols.push(Symbol { dynamic: false, name: format!("Mark {i}"), art: Arc::new(art) });
|
||||
}
|
||||
let layer = d.layers[0].id;
|
||||
let ids: Vec<_> = (0..8)
|
||||
.map(|i| {
|
||||
let xf = Affine::translate((0.0, f64::from(i) * 20.0));
|
||||
let n = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: format!("Mark {i}"), xf });
|
||||
d.insert(Some(layer), usize::MAX, n).unwrap()
|
||||
})
|
||||
.collect();
|
||||
let symbol_count = d.symbols.len();
|
||||
let mut s = Session::new();
|
||||
s.add_document(d, None);
|
||||
select(&mut s, &ids);
|
||||
let n = steps(&s);
|
||||
let before = vectorcraft_doc::symbols_read();
|
||||
let r = s.execute("addon.arrange.groupRows", &json!({})).unwrap();
|
||||
let read = vectorcraft_doc::symbols_read() - before;
|
||||
assert!(read <= symbol_count, "{read} symbols read, {symbol_count} in the document");
|
||||
assert_eq!((r["grouped"].clone(), steps(&s)), (json!(0), n));
|
||||
assert_eq!(layer_children(&s), ids);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_rows_sorts_many_objects_into_rows() {
|
||||
// 20000 objects in pairs up the page, the front one of each pair starting higher: each pair overlaps,
|
||||
// neighboring pairs only touch.
|
||||
let items: Vec<(u8, (f64, f64))> = (0..20_000)
|
||||
.map(|i| {
|
||||
let top = (10_000 - i / 2) as f64 * 10.0;
|
||||
(0, (if i % 2 == 0 { top + 1.0 } else { top }, top + 10.0))
|
||||
})
|
||||
.collect();
|
||||
let rows = super::rows_of(&items);
|
||||
assert_eq!(rows.len(), 10_000);
|
||||
assert!(rows.iter().all(|r| r.len() == 2 && r[1] == r[0] + 1), "pairs, in the order given");
|
||||
assert_eq!(rows.first(), Some(&vec![19_998, 19_999]), "the top row first");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_rows_keeps_a_flat_object_on_a_row_edge_apart_in_either_order() {
|
||||
// An extent with no height at the top edge of another only touches it, whichever is in front.
|
||||
let flat_behind: Vec<(u8, (f64, f64))> = vec![(0, (0.0, 0.0)), (0, (0.0, 10.0))];
|
||||
let flat_in_front: Vec<(u8, (f64, f64))> = vec![(0, (0.0, 10.0)), (0, (0.0, 0.0))];
|
||||
assert!(super::rows_of(&flat_behind).is_empty());
|
||||
assert!(super::rows_of(&flat_in_front).is_empty(), "{:?}", super::rows_of(&flat_in_front));
|
||||
// Inside the row, it joins.
|
||||
assert_eq!(super::rows_of(&[(0u8, (0.0, 10.0)), (0, (5.0, 5.0))]), vec![vec![0, 1]]);
|
||||
// A start of -0.0 is the same edge as 0.0, so the flat extent there still only touches.
|
||||
let negative_zero: Vec<(u8, (f64, f64))> = vec![(0, (0.0, 0.0)), (0, (-0.0, 10.0))];
|
||||
assert!(super::rows_of(&negative_zero).is_empty(), "{:?}", super::rows_of(&negative_zero));
|
||||
}
|
||||
|
||||
fn opacity(s: &Session, id: NodeId) -> f32 {
|
||||
s.doc().unwrap().doc.node(id).unwrap().opacity
|
||||
}
|
||||
|
||||
@@ -5,12 +5,14 @@
|
||||
//! Print Ink Fixes ([`print_fixes`]) prepares a CMYK document's inks for print, Find Nearest
|
||||
//! Swatch ([`nearest`]) matches colours to a swatch library's, Create Swatch Legend
|
||||
//! ([`legend`]) draws labelled chips of the document's swatches, and Apply Fill to Stroke and Apply
|
||||
//! Stroke to Fill ([`copy_paint`]) copy each object's own paint across. Its panel and its submenu,
|
||||
//! Stroke to Fill ([`copy_paint`]) copy each object's own paint across, and Randomize Fill Colors
|
||||
//! ([`random_fill`]) gives each filled path its own color at random. Its panel and its submenu,
|
||||
//! Object › Plug-ins › Color Effects, are the UI's.
|
||||
|
||||
pub mod legend;
|
||||
mod nearest;
|
||||
mod print_fixes;
|
||||
mod random_fill;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
@@ -92,6 +94,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_doc,
|
||||
|s, p| copy_paint(s, p, false)
|
||||
),
|
||||
cmd!(
|
||||
"addon.color.randomFill",
|
||||
"Randomize Fill Colors",
|
||||
["Object", "Plug-ins", "Color Effects"],
|
||||
None,
|
||||
"{scheme?: \"color\" (any color: red, green and blue each at random, in the document's color mode) | \"tint\" (a tint of `swatch`, linked to it) | \"gray\" (a gray) (\"color\"), swatch?: a global or spot color swatch's name (tint only, and needed there; a tint swatch gives tints of its base, which must still support tints), min?: % 0..100 (0), max?: % 0..100 (100; not less than min) (tint and gray only: the tint, or the gray's black, ranges from min to max), seed?: whole number (0; the same seed, objects and settings give the same colors; colors are drawn in the order of ids, a repeated id counting once and an id inside a listed group taking its color with that group's objects, so another order can give each object a different color), ids?: [id…] (default: the selection)} give each selected filled path, compound path and live compound shape, and each one inside the selected groups, its own top fill color, picked at random and evenly within the scheme, as one undo step (none when no fill changes). Compound paths and live compound shapes take one color and keep their members' fills. An id naming a nested member targets the outermost compound. Paths, compound paths and live compound shapes with no fill, clipping paths, hidden and locked objects (and objects in hidden or locked groups and layers, or on a locked artboard, also when given in ids, except new art made there while it is still selected), generated graph design art, paths a user groups inside a graph series, type, images, symbol instances, blends and envelopes keep their fills; a gradient or pattern fill becomes the color. On paths directly in a graph series whose fill changes, the graph stores the fill of the frontmost of them for its next redraw, which gives every mark of the series that one color (docs/mcp.md) → {count: objects whose fill changed}",
|
||||
has_selection,
|
||||
random_fill::run
|
||||
),
|
||||
]
|
||||
.into_iter()
|
||||
.chain(legend::specs())
|
||||
|
||||
@@ -0,0 +1,255 @@
|
||||
//! Randomize Fill Colors (`addon.color.randomFill`, Object › Plug-ins › Color Effects › Randomize
|
||||
//! Fill Colors…): each selected filled path, compound path and live compound shape, and each one inside the selected
|
||||
//! groups, gets a fill color of its own, picked at random from a seed: any color, a tint of one
|
||||
//! global or spot swatch, or a gray, as one undo step.
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
use std::collections::HashSet;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::recolor::Rng;
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::{Document, Node, NodeId, NodeKind};
|
||||
|
||||
use super::super::super::colorcmds::{edit_if_changed, keeping_series_paint};
|
||||
#[cfg(test)]
|
||||
use super::super::super::graph::is_design_art;
|
||||
use super::super::super::graph::{is_series_group, paint_targets};
|
||||
use super::super::super::menucmds::whole_or;
|
||||
use super::super::super::paint::swatch_solid;
|
||||
use super::super::super::{bad, checked_ids_or_selection, number_or, text_param};
|
||||
use crate::{Result, Session};
|
||||
|
||||
const C: &str = "addon.color.randomFill";
|
||||
/// The schemes the colors are picked from (`scheme`).
|
||||
pub const SCHEMES: [&str; 3] = ["color", "tint", "gray"];
|
||||
|
||||
/// How each color is picked.
|
||||
enum Scheme {
|
||||
/// Any color: red, green and blue each at random, in the document's color mode.
|
||||
Color,
|
||||
/// A tint of the swatch, from the least to the most (0..1).
|
||||
Tint(String, f32, f32),
|
||||
/// A gray, from the least black to the most (0..1).
|
||||
Gray(f32, f32),
|
||||
}
|
||||
|
||||
/// The percentage `p` gives for `key` (`default` when left out).
|
||||
fn percent(p: &Value, key: &str, default: f64) -> Result<f64> {
|
||||
let v = number_or(p, key, default, C)?;
|
||||
if (0.0..=100.0).contains(&v) { Ok(v) } else { Err(bad(C, format!("`{key}` must be from 0 to 100"))) }
|
||||
}
|
||||
|
||||
/// The scheme `p` asks for, checked against the document's swatches.
|
||||
fn scheme(s: &Session, p: &Value) -> Result<Scheme> {
|
||||
let name = text_param(p, "scheme", C)?.unwrap_or("color");
|
||||
if !SCHEMES.contains(&name) {
|
||||
return Err(bad(C, "`scheme` must be color, tint or gray"));
|
||||
}
|
||||
let given = |key: &str| p.get(key).is_some_and(|v| !v.is_null());
|
||||
if name == "color" && (given("min") || given("max")) {
|
||||
return Err(bad(C, "`min` and `max` go with scheme tint or gray"));
|
||||
}
|
||||
if name != "tint" && given("swatch") {
|
||||
return Err(bad(C, "`swatch` goes with scheme tint"));
|
||||
}
|
||||
if name == "color" {
|
||||
return Ok(Scheme::Color);
|
||||
}
|
||||
let (min, max) = (percent(p, "min", 0.0)?, percent(p, "max", 100.0)?);
|
||||
if min > max {
|
||||
return Err(bad(C, "`min` is greater than `max`"));
|
||||
}
|
||||
let (min, max) = ((min / 100.0) as f32, (max / 100.0) as f32);
|
||||
if name == "gray" {
|
||||
return Ok(Scheme::Gray(min, max));
|
||||
}
|
||||
let swatch = text_param(p, "swatch", C)?.ok_or_else(|| bad(C, "scheme tint needs a `swatch`: a global or spot color swatch"))?;
|
||||
let d = &s.doc()?.doc;
|
||||
swatch_solid(d, swatch, Some(1.0)).map_err(|e| bad(C, e))?;
|
||||
if let Some((base, _)) = d.swatch_link(swatch)
|
||||
&& d.tint_paint(&base, 1.0).is_none()
|
||||
{
|
||||
return Err(bad(C, format!("`{swatch}` needs a global or spot base swatch `{base}`")));
|
||||
}
|
||||
Ok(Scheme::Tint(swatch.to_string(), min, max))
|
||||
}
|
||||
|
||||
/// Whether the object `id` is left as it is: it, or a layer or group holding it, is hidden or
|
||||
/// locked, or it is the clipping path of the group or layer holding it.
|
||||
fn left_alone(d: &Document, id: NodeId) -> bool {
|
||||
let Some(line) = d.ancestry(id) else { return true };
|
||||
let nodes: Vec<&Node> = line.iter().filter_map(|id| d.node(*id)).collect();
|
||||
if nodes.len() != line.len() || nodes.iter().any(|n| !n.visible || n.locked) {
|
||||
return true;
|
||||
}
|
||||
matches!(nodes.as_slice(), [.., parent, n] if parent.clips() && parent.children().and_then(|c| c.first()).is_some_and(|c| c.id == n.id))
|
||||
}
|
||||
|
||||
/// Add to `out` `n` when it is a filled path, compound path or live compound shape that is shown and unlocked, or the
|
||||
/// ones inside it when it is a group or a layer. A clipping path (the first object of a clipping
|
||||
/// group or clipped layer, a compound path included), a guide, type, images, symbol instances,
|
||||
/// blends and envelopes are left as they are.
|
||||
fn filled(n: &Node, out: &mut Vec<NodeId>) {
|
||||
if !n.visible || n.locked {
|
||||
return;
|
||||
}
|
||||
if n.is_compound_shape() {
|
||||
if !n.appearance.fill_paint().is_none() {
|
||||
out.push(n.id);
|
||||
}
|
||||
return;
|
||||
}
|
||||
match &n.kind {
|
||||
NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => {
|
||||
for c in children.iter().skip(usize::from(n.clips())) {
|
||||
filled(c, out);
|
||||
}
|
||||
}
|
||||
NodeKind::Path { clipping: false, guide: false, .. } | NodeKind::Compound { .. } if !n.appearance.fill_paint().is_none() => out.push(n.id),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// `ids` with each graph series group replaced by the paths, compound paths and live compound shapes directly inside
|
||||
/// it. A compound path or live compound shape directly in a series group is kept, and the other ids go through
|
||||
/// [`paint_targets`], as for `paint.setFill`.
|
||||
fn series_roots(doc: &Document, ids: &[NodeId]) -> Vec<NodeId> {
|
||||
let is_series = |id: NodeId| doc.node(id).is_some_and(|n| is_series_group(doc, n));
|
||||
let compound = |n: &Node| matches!(n.kind, NodeKind::Compound { .. }) || n.is_compound_shape();
|
||||
let ordinary: std::collections::HashSet<NodeId> = paint_targets(doc, ids).into_iter().collect();
|
||||
let mut out = vec![];
|
||||
for id in ids {
|
||||
let Some(n) = doc.node(*id) else { continue };
|
||||
if is_series(*id) {
|
||||
out.extend(n.children().into_iter().flatten().filter(|m| matches!(m.kind, NodeKind::Path { .. }) || compound(m)).map(|m| m.id));
|
||||
} else if (compound(n) && doc.parent_of(*id).is_some_and(is_series)) || ordinary.contains(id) {
|
||||
out.push(*id);
|
||||
}
|
||||
}
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
out.retain(|id| seen.insert(*id));
|
||||
out
|
||||
}
|
||||
|
||||
/// The graph series groups among the ancestors of `targets`, each checked once.
|
||||
fn cached_series_groups(doc: &Document, targets: &[NodeId]) -> HashSet<NodeId> {
|
||||
let mut groups: HashSet<NodeId> = targets.iter().filter_map(|id| doc.ancestry(*id)).flatten().collect();
|
||||
groups.retain(|id| doc.node(*id).is_some_and(|n| is_series_group(doc, n)));
|
||||
groups
|
||||
}
|
||||
|
||||
/// [`is_design_art`] with the series groups looked up in `series_groups`.
|
||||
fn cached_is_design_art(doc: &Document, id: NodeId, series_groups: &HashSet<NodeId>) -> bool {
|
||||
let Some(chain) = doc.ancestry(id) else { return false };
|
||||
let Some(at) = chain.iter().position(|a| series_groups.contains(a)) else { return false };
|
||||
match chain.len() - at {
|
||||
1 => false,
|
||||
2 => doc.node(id).is_some_and(|n| !matches!(n.kind, NodeKind::Path { .. })),
|
||||
_ => true,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn run(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let scheme = scheme(s, p)?;
|
||||
let mut rng = Rng::new(whole_or(p, "seed", 0, C)?);
|
||||
let ids = checked_ids_or_selection(s, p, C)?;
|
||||
if ids.is_empty() {
|
||||
return Ok(json!({ "count": 0 }));
|
||||
}
|
||||
let model = s.doc()?.doc.color_mode.model();
|
||||
// A run that gives every object the fill it has records no undo step.
|
||||
let count = edit_if_changed(s, "Randomize Fill Colors", |before, d| {
|
||||
// Art on a locked artboard is left as it is, as for the other commands that take `ids`.
|
||||
let locks = before.locked_artboards();
|
||||
// A nested member stands for the outermost compound path or live compound shape after each ancestor is checked.
|
||||
let mut resolved = vec![];
|
||||
for id in &ids {
|
||||
let Some(chain) = before.ancestry(*id) else { continue };
|
||||
let mut target = None;
|
||||
let mut blocked = false;
|
||||
let mut parent: Option<&Node> = None;
|
||||
let mut layer_object_checked = false;
|
||||
for ancestor in &chain {
|
||||
let Some(n) = before.node(*ancestor) else {
|
||||
blocked = true;
|
||||
break;
|
||||
};
|
||||
if !n.visible || n.locked || parent.is_some_and(|p| p.clips() && p.children().and_then(|c| c.first()).is_some_and(|c| c.id == n.id)) {
|
||||
blocked = true;
|
||||
break;
|
||||
}
|
||||
if !layer_object_checked && (n.is_ruler_guide() || !n.is_layer()) {
|
||||
layer_object_checked = true;
|
||||
if !n.is_ruler_guide() && locks.holds(n) {
|
||||
blocked = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if matches!(n.kind, NodeKind::Compound { .. }) || n.is_compound_shape() {
|
||||
target.get_or_insert(*ancestor);
|
||||
}
|
||||
parent = Some(n);
|
||||
}
|
||||
if !blocked {
|
||||
resolved.push(target.unwrap_or(*id));
|
||||
}
|
||||
}
|
||||
// A graph's series group stands for its marks, as for `paint.setFill`.
|
||||
let roots = series_roots(before, &resolved);
|
||||
let mut targets = vec![];
|
||||
for id in &roots {
|
||||
let id = *id;
|
||||
if left_alone(before, id) || locks.holds_id(id) {
|
||||
continue;
|
||||
}
|
||||
let Some(n) = before.node(id) else { continue };
|
||||
filled(n, &mut targets);
|
||||
}
|
||||
let series_groups = cached_series_groups(before, &targets);
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
// A compound directly in a series group is one of the series' marks unless the graph drew it from a design;
|
||||
// the rest of the series' art below its top level is design art.
|
||||
let series_compound = |id: NodeId| {
|
||||
let Some(n) = before.node(id) else { return false };
|
||||
if !(matches!(n.kind, NodeKind::Compound { .. }) || n.is_compound_shape()) || n.extras().graph_design_art {
|
||||
return false;
|
||||
}
|
||||
let Some(group) = before.parent_of(id).filter(|p| series_groups.contains(p)).and_then(|p| before.node(p)) else { return false };
|
||||
let Some(index) = group.extras().series_index.and_then(|i| usize::try_from(i).ok()) else { return false };
|
||||
let graph = before.parent_of(group.id).and_then(|p| before.node(p)).and_then(|p| p.extras().graph.as_deref());
|
||||
graph.is_some_and(|spec| {
|
||||
let column = spec.series_columns.get(index).and_then(Option::as_ref).map(|c| c.design.as_str());
|
||||
let marker = spec.series_markers.get(index).and_then(Option::as_deref);
|
||||
![column, marker].into_iter().flatten().any(|name| {
|
||||
before
|
||||
.graph_designs
|
||||
.iter()
|
||||
.any(|design| design.name == name && (matches!(design.art.kind, NodeKind::Compound { .. }) || design.art.is_compound_shape()))
|
||||
})
|
||||
})
|
||||
};
|
||||
targets.retain(|id| seen.insert(*id) && !locks.holds_id(*id) && (series_compound(*id) || !cached_is_design_art(before, *id, &series_groups)));
|
||||
let count = keeping_series_paint(d, &roots, |d| {
|
||||
let mut count = 0;
|
||||
for id in &targets {
|
||||
let paint = match &scheme {
|
||||
Scheme::Color => Paint::solid(Color::rgb(rng.range(0.0, 1.0), rng.range(0.0, 1.0), rng.range(0.0, 1.0)).in_model(model)),
|
||||
Scheme::Tint(swatch, lo, hi) => swatch_solid(d, swatch, Some(rng.range(*lo, *hi))).map_err(|e| bad(C, e))?,
|
||||
Scheme::Gray(lo, hi) => Paint::solid(Color::gray(rng.range(*lo, *hi))),
|
||||
};
|
||||
if let Some(n) = d.node_mut(*id)
|
||||
&& n.appearance.fill_paint() != paint
|
||||
{
|
||||
n.appearance.set_fill(paint);
|
||||
count += 1;
|
||||
}
|
||||
}
|
||||
Ok(count)
|
||||
})?;
|
||||
Ok((count, count > 0))
|
||||
})?;
|
||||
Ok(json!({ "count": count }))
|
||||
}
|
||||
@@ -0,0 +1,705 @@
|
||||
//! Randomize Fill Colors: the colors each scheme gives, which objects take them, one undo step, and
|
||||
//! bad params refused without a change.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::{NodeId, NodeKind};
|
||||
|
||||
use crate::Session;
|
||||
|
||||
const C: &str = "addon.color.randomFill";
|
||||
|
||||
fn session() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn rect(s: &mut Session, x: f64) -> NodeId {
|
||||
NodeId(s.execute("shape.rectangle", &json!({"x": x, "y": 0, "width": 5, "height": 5})).unwrap()["id"].as_u64().unwrap())
|
||||
}
|
||||
|
||||
fn rects(s: &mut Session, n: usize) -> Vec<NodeId> {
|
||||
(0..n).map(|i| rect(s, i as f64 * 10.0)).collect()
|
||||
}
|
||||
|
||||
fn select(s: &mut Session, ids: &[NodeId]) {
|
||||
s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})).unwrap();
|
||||
}
|
||||
|
||||
fn fill(s: &Session, id: NodeId) -> Paint {
|
||||
s.doc().unwrap().doc.node(id).unwrap().appearance.fill_paint()
|
||||
}
|
||||
|
||||
fn fills(s: &Session, ids: &[NodeId]) -> Vec<Paint> {
|
||||
ids.iter().map(|id| fill(s, *id)).collect()
|
||||
}
|
||||
|
||||
fn steps(s: &Session) -> usize {
|
||||
s.doc().unwrap().history.undo.len()
|
||||
}
|
||||
|
||||
fn enabled(s: &Session, cmd: &str) -> bool {
|
||||
s.commands().into_iter().find(|c| c.id == cmd).unwrap().enabled
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_object_gets_its_own_color_from_the_seed() {
|
||||
let mut s = session();
|
||||
let ids = rects(&mut s, 12);
|
||||
select(&mut s, &ids);
|
||||
let before = fills(&s, &ids);
|
||||
let n = steps(&s);
|
||||
let r = s.execute(C, &json!({"seed": 7})).unwrap();
|
||||
assert_eq!(r["count"], json!(12));
|
||||
assert_eq!(steps(&s), n + 1, "one undo step");
|
||||
let first = fills(&s, &ids);
|
||||
assert!(first.iter().all(|p| matches!(p, Paint::Solid { color: Color::Rgb { .. }, swatch: None, .. })), "{first:?}");
|
||||
assert!(first.windows(2).all(|w| w[0] != w[1]), "each its own: {first:?}");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(fills(&s, &ids), before, "undone");
|
||||
// The same seed repeats them; another seed doesn't.
|
||||
s.execute(C, &json!({"seed": 7})).unwrap();
|
||||
assert_eq!(fills(&s, &ids), first);
|
||||
s.execute(C, &json!({"seed": 8})).unwrap();
|
||||
assert_ne!(fills(&s, &ids), first);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repeated_ids_take_one_color_from_the_seed() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0);
|
||||
assert_eq!(s.execute(C, &json!({"ids": [a.0], "seed": 7})).unwrap()["count"], json!(1));
|
||||
let once = fill(&s, a);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(s.execute(C, &json!({"ids": [a.0, a.0], "seed": 7})).unwrap()["count"], json!(1));
|
||||
assert_eq!(fill(&s, a), once);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cmyk_document_gets_cmyk_colors() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300, "colorMode": "cmyk"})).unwrap();
|
||||
let ids = rects(&mut s, 3);
|
||||
select(&mut s, &ids);
|
||||
s.execute(C, &json!({"scheme": "color"})).unwrap();
|
||||
assert!(fills(&s, &ids).iter().all(|p| matches!(p, Paint::Solid { color: Color::Cmyk { .. }, .. })), "{:?}", fills(&s, &ids));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn grays_and_tints_stay_within_the_range() {
|
||||
let mut s = session();
|
||||
let ids = rects(&mut s, 20);
|
||||
select(&mut s, &ids);
|
||||
s.execute(C, &json!({"scheme": "gray", "min": 20, "max": 40, "seed": 3})).unwrap();
|
||||
let grays: Vec<f32> = fills(&s, &ids)
|
||||
.into_iter()
|
||||
.map(|p| match p {
|
||||
Paint::Solid { color: Color::Gray { k }, swatch: None, .. } => k,
|
||||
other => panic!("not a gray: {other:?}"),
|
||||
})
|
||||
.collect();
|
||||
assert!(grays.iter().all(|k| (0.2..=0.4).contains(k)), "{grays:?}");
|
||||
assert!(grays.windows(2).any(|w| w[0] != w[1]), "{grays:?}");
|
||||
s.execute("swatch.new", &json!({"name": "Ink", "color": "#e01020", "spot": true})).unwrap();
|
||||
s.execute(C, &json!({"scheme": "tint", "swatch": "Ink", "min": 10, "max": 50, "seed": 3})).unwrap();
|
||||
for p in fills(&s, &ids) {
|
||||
let Paint::Solid { swatch: Some(name), tint, .. } = p else { panic!("not linked: {p:?}") };
|
||||
assert_eq!(name, "Ink");
|
||||
assert!((0.1..=0.5).contains(&tint), "{tint}");
|
||||
}
|
||||
// min = max gives every object that gray.
|
||||
s.execute(C, &json!({"scheme": "gray", "min": 45, "max": 45})).unwrap();
|
||||
assert!(fills(&s, &ids).iter().all(|p| *p == Paint::solid(Color::gray(0.45))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn groups_are_entered_and_unfilled_hidden_and_locked_objects_left_alone() {
|
||||
let mut s = session();
|
||||
let [a, b, c, hidden, locked] = [0.0, 10.0, 20.0, 30.0, 40.0].map(|x| rect(&mut s, x));
|
||||
select(&mut s, &[a, b, c, hidden, locked]);
|
||||
let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("paint.setFill", &json!({"ids": [c.0], "none": true})).unwrap();
|
||||
s.execute("object.hide", &json!({"ids": [hidden.0]})).unwrap();
|
||||
s.execute("object.lock", &json!({"ids": [locked.0]})).unwrap();
|
||||
select(&mut s, &[g]);
|
||||
let (before_hidden, before_locked) = (fill(&s, hidden), fill(&s, locked));
|
||||
assert!(!before_hidden.is_none() && !before_locked.is_none());
|
||||
let r = s.execute(C, &json!({"scheme": "gray", "min": 50, "max": 50})).unwrap();
|
||||
assert_eq!(r["count"], json!(2));
|
||||
let gray = Paint::solid(Color::gray(0.5));
|
||||
assert_eq!((fill(&s, a), fill(&s, b), fill(&s, c)), (gray.clone(), gray.clone(), Paint::None), "the unfilled one keeps None");
|
||||
assert_eq!(fill(&s, g), Paint::None, "the group gets no fill of its own");
|
||||
assert_eq!((fill(&s, hidden), fill(&s, locked)), (before_hidden, before_locked));
|
||||
// `ids` stand in for the selection; with nothing selected the menu item is off.
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
assert!(!enabled(&s, C));
|
||||
let d = rect(&mut s, 50.0);
|
||||
s.execute("paint.setFill", &json!({"ids": [d.0], "color": "#336699"})).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
s.execute(C, &json!({"ids": [d.0], "scheme": "gray", "min": 10, "max": 10})).unwrap();
|
||||
assert_eq!(fill(&s, d), Paint::solid(Color::gray(0.1)));
|
||||
assert_eq!(fill(&s, a), gray, "not among ids");
|
||||
// An object given by id inside a hidden or locked group keeps its fill.
|
||||
for hide in [true, false] {
|
||||
let e = rect(&mut s, 60.0);
|
||||
s.execute("paint.setFill", &json!({"ids": [e.0], "color": "#336699"})).unwrap();
|
||||
select(&mut s, &[e]);
|
||||
let outer = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute(if hide { "object.hide" } else { "object.lock" }, &json!({"ids": [outer.0]})).unwrap();
|
||||
let kept = fill(&s, e);
|
||||
assert_eq!(s.execute(C, &json!({"ids": [e.0], "scheme": "gray"})).unwrap()["count"], json!(0), "hidden group: {hide}");
|
||||
assert_eq!(fill(&s, e), kept);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_compound_path_takes_one_color_and_a_clipping_path_none() {
|
||||
let mut s = session();
|
||||
let [a, b] = [0.0, 2.0].map(|x| rect(&mut s, x));
|
||||
select(&mut s, &[a, b]);
|
||||
let compound = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
// The topmost becomes the clipping path.
|
||||
let [art, mask] = [100.0, 102.0].map(|x| rect(&mut s, x));
|
||||
select(&mut s, &[art, mask]);
|
||||
let clip = NodeId(s.execute("object.clippingMask.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
let is_clipping = |s: &Session, id: NodeId| matches!(s.doc().unwrap().doc.node(id).unwrap().kind, NodeKind::Path { clipping: true, .. });
|
||||
assert!(is_clipping(&s, mask) && !is_clipping(&s, art));
|
||||
// A clipping path given a fill still keeps it.
|
||||
s.execute("paint.setFill", &json!({"ids": [mask.0], "color": "#00ff00"})).unwrap();
|
||||
let mask_fill = fill(&s, mask);
|
||||
assert!(!mask_fill.is_none());
|
||||
select(&mut s, &[compound, clip]);
|
||||
let r = s.execute(C, &json!({"scheme": "gray", "min": 30, "max": 30})).unwrap();
|
||||
assert_eq!(r["count"], json!(2), "the compound path and the clipped art");
|
||||
assert_eq!(fill(&s, compound), Paint::solid(Color::gray(0.3)));
|
||||
assert_eq!(fill(&s, art), Paint::solid(Color::gray(0.3)));
|
||||
assert_eq!(fill(&s, mask), mask_fill, "the clipping path keeps its fill");
|
||||
// Given by id, the clipping path keeps it too.
|
||||
assert_eq!(s.execute(C, &json!({"ids": [mask.0], "scheme": "gray"})).unwrap()["count"], json!(0));
|
||||
assert_eq!(fill(&s, mask), mask_fill);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_compound_member_given_by_id_colors_the_compound() {
|
||||
let mut s = session();
|
||||
let [a, b] = [0.0, 2.0].map(|x| rect(&mut s, x));
|
||||
select(&mut s, &[a, b]);
|
||||
let compound = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
let before = fill(&s, compound);
|
||||
let members = fills(&s, &[a, b]);
|
||||
assert_eq!(s.execute(C, &json!({"ids": [a.0], "seed": 7})).unwrap()["count"], json!(1));
|
||||
assert_ne!(fill(&s, compound), before);
|
||||
assert_eq!(fills(&s, &[a, b]), members);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_compound_clipping_path_keeps_its_fill() {
|
||||
let mut s = session();
|
||||
let art = rect(&mut s, 0.0);
|
||||
let [a, b] = [0.0, 2.0].map(|x| rect(&mut s, x));
|
||||
select(&mut s, &[a, b]);
|
||||
let compound = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
select(&mut s, &[art, compound]);
|
||||
let clip = NodeId(s.execute("object.clippingMask.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
assert_eq!(s.doc().unwrap().doc.node(clip).unwrap().children().unwrap()[0].id, compound, "the compound path clips");
|
||||
s.execute("paint.setFill", &json!({"ids": [compound.0], "color": "#00ff00"})).unwrap();
|
||||
let mask_fill = fill(&s, compound);
|
||||
assert!(!mask_fill.is_none());
|
||||
select(&mut s, &[clip]);
|
||||
assert_eq!(s.execute(C, &json!({"scheme": "gray", "min": 30, "max": 30})).unwrap()["count"], json!(1), "the clipped art only");
|
||||
assert_eq!(fill(&s, art), Paint::solid(Color::gray(0.3)));
|
||||
assert_eq!(fill(&s, compound), mask_fill);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_live_compound_shape_takes_one_color_and_keeps_its_members_fills() {
|
||||
for target in ["shape", "group", "member"] {
|
||||
let mut s = session();
|
||||
let [a, b] = [0.0, 2.0].map(|x| rect(&mut s, x));
|
||||
select(&mut s, &[a, b]);
|
||||
let shape = NodeId(s.execute("object.compoundShape.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
assert!(s.doc().unwrap().doc.node(shape).unwrap().is_compound_shape());
|
||||
let id = match target {
|
||||
"group" => NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()),
|
||||
"member" => a,
|
||||
_ => shape,
|
||||
};
|
||||
let before = fill(&s, shape);
|
||||
let members = fills(&s, &[a, b]);
|
||||
let n = steps(&s);
|
||||
assert_eq!(s.execute(C, &json!({"ids": [id.0], "scheme": "gray", "min": 30, "max": 30})).unwrap()["count"], json!(1), "{target}");
|
||||
assert_eq!(fill(&s, shape), Paint::solid(Color::gray(0.3)), "{target}");
|
||||
assert_eq!(fills(&s, &[a, b]), members, "{target}");
|
||||
assert_eq!(steps(&s), n + 1);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(fill(&s, shape), before);
|
||||
assert_eq!(fills(&s, &[a, b]), members);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_selected_graph_keeps_the_fills_of_generated_design_art() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0);
|
||||
s.execute("paint.setFill", &json!({"ids": [a.0], "color": "#336699"})).unwrap();
|
||||
select(&mut s, &[a]);
|
||||
s.execute("graph.design", &json!({"new": "Tile"})).unwrap();
|
||||
let graph = NodeId(
|
||||
s.execute("graph.create", &json!({"type": "column", "x": 100, "y": 100, "width": 200, "height": 150, "series": ["A"], "rows": [[20], [30]]}))
|
||||
.unwrap()["id"]
|
||||
.as_u64()
|
||||
.unwrap(),
|
||||
);
|
||||
s.execute("graph.column", &json!({"id": graph.0, "design": "Tile"})).unwrap();
|
||||
let mut design_paths = vec![];
|
||||
let d = &s.doc().unwrap().doc;
|
||||
d.node(graph).unwrap().walk(&mut |n| {
|
||||
if matches!(n.kind, NodeKind::Path { .. }) && super::is_design_art(d, n.id) && !n.appearance.fill_paint().is_none() {
|
||||
design_paths.push(n.id);
|
||||
}
|
||||
});
|
||||
assert!(!design_paths.is_empty());
|
||||
let before = fills(&s, &design_paths);
|
||||
select(&mut s, &[graph]);
|
||||
s.execute(C, &json!({"scheme": "gray", "min": 30, "max": 30})).unwrap();
|
||||
assert_eq!(fills(&s, &design_paths), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_compound_path_in_a_graph_series_takes_a_color() {
|
||||
let mut s = session();
|
||||
let graph = NodeId(
|
||||
s.execute("graph.create", &json!({"type": "column", "x": 100, "y": 100, "width": 200, "height": 150, "series": ["A"], "rows": [[20], [30]]}))
|
||||
.unwrap()["id"]
|
||||
.as_u64()
|
||||
.unwrap(),
|
||||
);
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let series = d.node(graph).unwrap().children().into_iter().flatten().find(|n| n.extras().series_index.is_some()).unwrap();
|
||||
let group = series.id;
|
||||
let marks: Vec<NodeId> = series.children().into_iter().flatten().filter(|m| matches!(m.kind, NodeKind::Path { .. })).map(|m| m.id).collect();
|
||||
assert!(marks.len() >= 2);
|
||||
let marks = &marks[..2];
|
||||
select(&mut s, marks);
|
||||
let compound = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(compound), Some(group), "the compound path is directly in the series group");
|
||||
for ids in [vec![compound], vec![marks[0]], vec![group]] {
|
||||
let before = fill(&s, compound);
|
||||
let r = s.execute(C, &json!({"scheme": "gray", "min": 40, "max": 40, "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})).unwrap();
|
||||
assert!(r["count"].as_u64().unwrap() >= 1, "{ids:?}");
|
||||
assert_ne!(fill(&s, compound), before, "{ids:?}");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_compound_in_a_graph_series_takes_a_color_after_its_design_is_deleted() {
|
||||
for kind in ["column", "line", "scatter"] {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0);
|
||||
select(&mut s, &[a]);
|
||||
s.execute("graph.design", &json!({"new": "Tile"})).unwrap();
|
||||
let graph = NodeId(
|
||||
s.execute(
|
||||
"graph.create",
|
||||
&json!({"type": kind, "x": 100, "y": 100, "width": 200, "height": 150, "series": ["X", "A"], "rows": [[10, 20], [20, 30]]}),
|
||||
)
|
||||
.unwrap()["id"]
|
||||
.as_u64()
|
||||
.unwrap(),
|
||||
);
|
||||
s.execute(if kind == "column" { "graph.column" } else { "graph.marker" }, &json!({"id": graph.0, "design": "Tile"})).unwrap();
|
||||
s.execute("graph.design", &json!({"delete": "Tile"})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert!(d.graph_designs.is_empty());
|
||||
let series = d.node(graph).unwrap().children().into_iter().flatten().find(|n| n.extras().series_index.is_some()).unwrap();
|
||||
let group = series.id;
|
||||
let index = series.extras().series_index.unwrap() as usize;
|
||||
let spec = d.node(graph).unwrap().extras().graph.as_deref().unwrap();
|
||||
if kind == "column" {
|
||||
assert_eq!(spec.series_columns[index].as_ref().unwrap().design, "Tile");
|
||||
} else {
|
||||
assert_eq!(spec.series_markers[index].as_deref(), Some("Tile"));
|
||||
}
|
||||
let marks: Vec<NodeId> = series
|
||||
.children()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter(|m| matches!(m.kind, NodeKind::Path { .. }) && !m.appearance.fill_paint().is_none())
|
||||
.map(|m| m.id)
|
||||
.collect();
|
||||
assert!(marks.len() >= 2, "{kind}");
|
||||
let marks = &marks[..2];
|
||||
select(&mut s, marks);
|
||||
let compound = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(compound), Some(group), "{kind}");
|
||||
let before = fill(&s, compound);
|
||||
let members = fills(&s, marks);
|
||||
select(&mut s, &[graph]);
|
||||
let result = s.execute(C, &json!({"scheme": "gray", "min": 40, "max": 40})).unwrap();
|
||||
assert!(result["count"].as_u64().unwrap() >= 1, "{kind}");
|
||||
assert_ne!(fill(&s, compound), before, "{kind}");
|
||||
assert_eq!(fills(&s, marks), members, "{kind}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_user_compound_in_a_series_with_a_plain_path_design_takes_a_color() {
|
||||
for kind in ["column", "line", "scatter"] {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0);
|
||||
select(&mut s, &[a]);
|
||||
s.execute("graph.design", &json!({"new": "Tile"})).unwrap();
|
||||
assert!(matches!(s.doc().unwrap().doc.graph_designs[0].art.kind, NodeKind::Path { .. }));
|
||||
let graph = NodeId(
|
||||
s.execute(
|
||||
"graph.create",
|
||||
&json!({"type": kind, "x": 100, "y": 100, "width": 200, "height": 150, "series": ["X", "A"], "rows": [[10, 20], [20, 30]]}),
|
||||
)
|
||||
.unwrap()["id"]
|
||||
.as_u64()
|
||||
.unwrap(),
|
||||
);
|
||||
s.execute(if kind == "column" { "graph.column" } else { "graph.marker" }, &json!({"id": graph.0, "design": "Tile"})).unwrap();
|
||||
let designed = s.doc().unwrap().doc.node(graph).unwrap().extras().graph.clone();
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.edit("Set series design without replacing ordinary marks", |d, _| {
|
||||
d.node_mut(graph).unwrap().extras_mut().graph = designed;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let series = d.node(graph).unwrap().children().into_iter().flatten().find(|n| n.extras().series_index.is_some()).unwrap();
|
||||
let group = series.id;
|
||||
let marks: Vec<NodeId> = series
|
||||
.children()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter(|m| matches!(m.kind, NodeKind::Path { .. }) && !m.appearance.fill_paint().is_none())
|
||||
.map(|m| m.id)
|
||||
.collect();
|
||||
assert!(marks.len() >= 2, "{kind}");
|
||||
let marks = &marks[..2];
|
||||
select(&mut s, marks);
|
||||
let compound = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(compound), Some(group), "{kind}");
|
||||
assert!(!s.doc().unwrap().doc.node(compound).unwrap().extras().graph_design_art, "{kind}");
|
||||
let members = fills(&s, marks);
|
||||
for ids in [vec![compound], vec![marks[0]], vec![group], vec![graph]] {
|
||||
let before = fill(&s, compound);
|
||||
let result = s.execute(C, &json!({"scheme": "gray", "min": 40, "max": 40, "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})).unwrap();
|
||||
assert!(result["count"].as_u64().unwrap() >= 1, "{kind}: {ids:?}");
|
||||
assert_eq!(fill(&s, compound), Paint::solid(Color::gray(0.4)), "{kind}: {ids:?}");
|
||||
assert_ne!(fill(&s, compound), before, "{kind}: {ids:?}");
|
||||
assert_eq!(fills(&s, marks), members, "{kind}: {ids:?}");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn grouped_paths_in_a_graph_series_keep_their_fills_as_for_paint_set_fill() {
|
||||
for kind in ["column", "line", "scatter"] {
|
||||
let mut s = session();
|
||||
let graph = NodeId(
|
||||
s.execute(
|
||||
"graph.create",
|
||||
&json!({"type": kind, "x": 100, "y": 100, "width": 200, "height": 150, "series": ["X", "A"], "rows": [[10, 20], [20, 30]]}),
|
||||
)
|
||||
.unwrap()["id"]
|
||||
.as_u64()
|
||||
.unwrap(),
|
||||
);
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let series = d.node(graph).unwrap().children().into_iter().flatten().find(|n| n.extras().series_index.is_some()).unwrap();
|
||||
let group = series.id;
|
||||
let marks: Vec<NodeId> = series
|
||||
.children()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter(|m| matches!(m.kind, NodeKind::Path { .. }) && !m.appearance.fill_paint().is_none())
|
||||
.map(|m| m.id)
|
||||
.collect();
|
||||
assert!(marks.len() >= 2, "{kind}");
|
||||
let marks = &marks[..2];
|
||||
select(&mut s, marks);
|
||||
let nested = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(nested), Some(group), "{kind}");
|
||||
let before = fills(&s, marks);
|
||||
select(&mut s, &[graph]);
|
||||
// `paint.setFill` on the graph leaves a group inside a series alone, as design art; so does this command.
|
||||
s.execute("paint.setFill", &json!({"color": "#aa0000"})).unwrap();
|
||||
let after_set_fill = fills(&s, marks);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute(C, &json!({"scheme": "gray", "min": 40, "max": 40})).unwrap();
|
||||
assert_eq!(fills(&s, marks), before, "{kind}");
|
||||
assert_eq!(after_set_fill, before, "{kind}: paint.setFill keeps grouped marks too");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generated_compound_design_copies_in_a_graph_series_keep_their_fills() {
|
||||
// `legacy` clears the design flags and keeps the series' design reference; `flag_only` keeps the flags and clears the
|
||||
// reference, so each check keeps the copies' fills on its own.
|
||||
let modes = [(false, false), (true, false), (false, true)];
|
||||
for (kind, (legacy, flag_only)) in ["column", "line", "scatter"].into_iter().flat_map(|kind| modes.map(|mode| (kind, mode))) {
|
||||
let mut s = session();
|
||||
let marks = rects(&mut s, 2);
|
||||
select(&mut s, &marks);
|
||||
let compound = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("paint.setFill", &json!({"ids": [compound.0], "color": "#336699"})).unwrap();
|
||||
select(&mut s, &[compound]);
|
||||
s.execute("graph.design", &json!({"new": "Tile"})).unwrap();
|
||||
let graph = NodeId(
|
||||
s.execute(
|
||||
"graph.create",
|
||||
&json!({"type": kind, "x": 100, "y": 100, "width": 200, "height": 150, "series": ["X", "A"], "rows": [[10, 20], [20, 30]]}),
|
||||
)
|
||||
.unwrap()["id"]
|
||||
.as_u64()
|
||||
.unwrap(),
|
||||
);
|
||||
s.execute(if kind == "column" { "graph.column" } else { "graph.marker" }, &json!({"id": graph.0, "design": "Tile"})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let series = d.node(graph).unwrap().children().into_iter().flatten().find(|n| n.extras().series_index.is_some()).unwrap();
|
||||
let group = series.id;
|
||||
let copies: Vec<NodeId> =
|
||||
series.children().into_iter().flatten().filter(|m| matches!(m.kind, NodeKind::Compound { .. })).map(|m| m.id).collect();
|
||||
assert!(!copies.is_empty(), "{kind}: the generated compound is directly in the series group");
|
||||
for id in &copies {
|
||||
assert!(d.node(*id).unwrap().extras().graph_design_art, "{kind}");
|
||||
assert!(super::is_design_art(d, *id), "{kind}");
|
||||
}
|
||||
let mut art = vec![];
|
||||
series.walk(&mut |n| {
|
||||
if super::is_design_art(d, n.id) {
|
||||
art.push(n.id);
|
||||
}
|
||||
});
|
||||
if legacy {
|
||||
s.edit("Clear graph design flags", |d, _| {
|
||||
for id in &art {
|
||||
d.node_mut(*id).unwrap().extras_mut().graph_design_art = false;
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
}
|
||||
if flag_only {
|
||||
s.edit("Clear series design reference", |d, _| {
|
||||
let mut extras = d.node_mut(graph).unwrap().extras_mut();
|
||||
let spec = extras.graph.as_deref_mut().unwrap();
|
||||
spec.series_columns.iter_mut().for_each(|c| *c = None);
|
||||
spec.series_markers.iter_mut().for_each(|m| *m = None);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
for id in &copies {
|
||||
assert!(s.doc().unwrap().doc.node(*id).unwrap().extras().graph_design_art, "{kind}");
|
||||
}
|
||||
}
|
||||
let before = fills(&s, &art);
|
||||
let runs = if flag_only { vec![copies.clone()] } else { vec![vec![graph], vec![group], copies] };
|
||||
for ids in runs {
|
||||
s.execute(C, &json!({"scheme": "gray", "min": 40, "max": 40, "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})).unwrap();
|
||||
assert_eq!(fills(&s, &art), before, "{kind}, legacy: {legacy}, flag only: {flag_only}: {ids:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hidden_or_locked_compound_members_given_by_id_keep_the_compounds_fill() {
|
||||
for hide in [true, false] {
|
||||
let mut s = session();
|
||||
let [a, b] = [0.0, 2.0].map(|x| rect(&mut s, x));
|
||||
select(&mut s, &[a, b]);
|
||||
let compound = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("object.setProps", &if hide { json!({"id": a.0, "visible": false}) } else { json!({"id": a.0, "locked": true}) }).unwrap();
|
||||
let member = s.doc().unwrap().doc.node(a).unwrap();
|
||||
assert!(if hide { !member.visible } else { member.locked });
|
||||
let parent = s.doc().unwrap().doc.node(compound).unwrap();
|
||||
assert!(parent.visible && !parent.locked);
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let n = steps(&s);
|
||||
assert_eq!(s.execute(C, &json!({"ids": [a.0], "scheme": "gray", "min": 30, "max": 30})).unwrap()["count"], json!(0), "hidden: {hide}");
|
||||
assert_eq!(fill(&s, compound), before.node(compound).unwrap().appearance.fill_paint());
|
||||
assert!(*s.doc().unwrap().doc == *before);
|
||||
assert_eq!(steps(&s), n);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn seeded_colors_follow_ids_order_without_repeating_objects() {
|
||||
let mut s = session();
|
||||
let ids = rects(&mut s, 3);
|
||||
s.execute(C, &json!({"ids": ids.iter().map(|id| id.0).collect::<Vec<_>>(), "seed": 7})).unwrap();
|
||||
let first = fills(&s, &ids);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(s.execute(C, &json!({"ids": [ids[2].0, ids[0].0, ids[2].0, ids[1].0], "seed": 7})).unwrap()["count"], json!(3));
|
||||
assert_eq!(fills(&s, &[ids[2], ids[0], ids[1]]), first);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nested_members_color_the_outermost_compound_unless_an_ancestor_is_blocked() {
|
||||
for blocked in ["none", "hidden", "locked", "artboard"] {
|
||||
let mut s = session();
|
||||
let [a, b, c] = [0.0, 2.0, 4.0].map(|x| rect(&mut s, x));
|
||||
select(&mut s, &[a]);
|
||||
let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
select(&mut s, &[group, b]);
|
||||
let inner = NodeId(s.execute("object.compoundShape.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
select(&mut s, &[inner, c]);
|
||||
let outer = NodeId(s.execute("object.compoundShape.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
match blocked {
|
||||
"hidden" => {
|
||||
s.execute("object.setProps", &json!({"id": group.0, "visible": false})).unwrap();
|
||||
}
|
||||
"locked" => {
|
||||
s.execute("object.setProps", &json!({"id": inner.0, "locked": true})).unwrap();
|
||||
}
|
||||
"artboard" => {
|
||||
s.execute("artboard.setProps", &json!({"index": 0, "locked": true})).unwrap();
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let members = fills(&s, &[a, b, c, group, inner]);
|
||||
let n = steps(&s);
|
||||
let r = s.execute(C, &json!({"ids": [a.0], "scheme": "gray", "min": 30, "max": 30})).unwrap();
|
||||
assert_eq!(fills(&s, &[a, b, c, group, inner]), members, "{blocked}");
|
||||
if blocked == "none" {
|
||||
assert_eq!(r["count"], json!(1));
|
||||
assert_eq!(fill(&s, outer), Paint::solid(Color::gray(0.3)));
|
||||
assert_eq!(steps(&s), n + 1);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
} else {
|
||||
assert_eq!(r["count"], json!(0), "{blocked}");
|
||||
assert_eq!(steps(&s), n, "{blocked}");
|
||||
}
|
||||
assert!(*s.doc().unwrap().doc == *before, "{blocked}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_invalid_series_index_keeps_ordinary_subgroups_reachable() {
|
||||
let mut s = session();
|
||||
let graph = NodeId(
|
||||
s.execute("graph.create", &json!({"type": "column", "x": 100, "y": 100, "width": 200, "height": 150, "series": ["A"], "rows": [[20], [30]]}))
|
||||
.unwrap()["id"]
|
||||
.as_u64()
|
||||
.unwrap(),
|
||||
);
|
||||
let series = s.doc().unwrap().doc.node(graph).unwrap().children().unwrap().iter().find(|n| n.extras().series_index == Some(0)).unwrap();
|
||||
let group = series.id;
|
||||
let marks: Vec<NodeId> = series.children().unwrap().iter().filter(|n| matches!(n.kind, NodeKind::Path { .. })).map(|n| n.id).collect();
|
||||
assert!(!marks.is_empty());
|
||||
select(&mut s, &marks);
|
||||
s.execute("object.group", &json!({})).unwrap();
|
||||
s.edit("Set series index", |d, _| {
|
||||
d.node_mut(group).unwrap().extras_mut().series_index = Some(u32::MAX);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let before = fills(&s, &marks);
|
||||
let r = s.execute(C, &json!({"ids": [group.0], "scheme": "gray", "min": 30, "max": 30})).unwrap();
|
||||
assert_eq!(r["count"], json!(marks.len()));
|
||||
assert!(fills(&s, &marks).iter().all(|p| *p == Paint::solid(Color::gray(0.3))));
|
||||
assert_ne!(fills(&s, &marks), before);
|
||||
assert!(s.doc().unwrap().doc.node(graph).unwrap().extras().graph.as_ref().unwrap().series_paints.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tint_swatch_with_a_deleted_base_is_refused_without_a_change() {
|
||||
let mut s = session();
|
||||
let ids = rects(&mut s, 2);
|
||||
select(&mut s, &ids);
|
||||
s.execute("swatch.new", &json!({"name": "Ink", "color": "#e01020", "spot": true})).unwrap();
|
||||
let tint = s.execute("swatch.new", &json!({"name": "Pale", "swatch": "Ink", "tint": 40})).unwrap()["name"].as_str().unwrap().to_string();
|
||||
s.execute("swatch.delete", &json!({"name": "Ink", "unlink": false})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert!(d.swatch("Ink").is_none());
|
||||
assert_eq!(d.swatch_link(&tint), Some(("Ink".to_string(), 0.4)));
|
||||
let before = d.clone();
|
||||
let n = steps(&s);
|
||||
let e = s.execute(C, &json!({"scheme": "tint", "swatch": tint, "min": 10, "max": 80})).unwrap_err().to_string();
|
||||
assert!(e.contains("base swatch `Ink`"), "{e}");
|
||||
assert!(*s.doc().unwrap().doc == *before);
|
||||
assert_eq!(steps(&s), n);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_inverted_range_that_rounds_to_equal_f32_bounds_is_refused() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0);
|
||||
select(&mut s, &[a]);
|
||||
s.execute("swatch.new", &json!({"name": "Ink", "color": "#e01020", "spot": true})).unwrap();
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let n = steps(&s);
|
||||
for p in [json!({"scheme": "gray", "min": 50.0000001, "max": 50}), json!({"scheme": "tint", "swatch": "Ink", "min": 50.0000001, "max": 50})] {
|
||||
let e = s.execute(C, &p).unwrap_err().to_string();
|
||||
assert!(e.contains("`min` is greater than `max`"), "{p}: {e}");
|
||||
assert!(*s.doc().unwrap().doc == *before);
|
||||
assert_eq!(steps(&s), n);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_undo_step_when_no_fill_changes() {
|
||||
let mut s = session();
|
||||
let ids = rects(&mut s, 2);
|
||||
select(&mut s, &ids);
|
||||
s.execute(C, &json!({"scheme": "gray", "min": 40, "max": 40})).unwrap();
|
||||
let n = steps(&s);
|
||||
let r = s.execute(C, &json!({"scheme": "gray", "min": 40, "max": 40})).unwrap();
|
||||
assert_eq!((r["count"].clone(), steps(&s)), (json!(0), n), "the same grays again");
|
||||
// Only unfilled objects: nothing to color.
|
||||
s.execute("paint.setFill", &json!({"none": true})).unwrap();
|
||||
let n = steps(&s);
|
||||
assert_eq!(s.execute(C, &json!({})).unwrap()["count"], json!(0));
|
||||
assert_eq!(steps(&s), n);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_params_are_refused() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0);
|
||||
select(&mut s, &[a]);
|
||||
s.execute("swatch.new", &json!({"name": "Process", "color": "#336699"})).unwrap();
|
||||
s.execute("swatch.new", &json!({"name": "Ink", "color": "#e01020", "spot": true})).unwrap();
|
||||
let (before, n) = (s.doc().unwrap().doc.clone(), steps(&s));
|
||||
let bad: [(Value, &str); 14] = [
|
||||
(json!({"scheme": "rainbow"}), "`scheme` must be color, tint or gray"),
|
||||
(json!({"scheme": 3}), "`scheme` must be a string"),
|
||||
(json!({"min": 10}), "`min` and `max` go with scheme tint or gray"),
|
||||
(json!({"scheme": "gray", "swatch": "Ink"}), "`swatch` goes with scheme tint"),
|
||||
(json!({"scheme": "gray", "min": -1}), "`min` must be from 0 to 100"),
|
||||
(json!({"scheme": "gray", "max": 101}), "`max` must be from 0 to 100"),
|
||||
(json!({"scheme": "gray", "min": 80, "max": 20}), "`min` is greater than `max`"),
|
||||
(json!({"scheme": "gray", "max": "50"}), "`max` must be a number"),
|
||||
(json!({"scheme": "tint"}), "scheme tint needs a `swatch`"),
|
||||
(json!({"scheme": "tint", "swatch": "Nope"}), "no swatch `Nope`"),
|
||||
(json!({"scheme": "tint", "swatch": "Process"}), "is a process colour"),
|
||||
(json!({"seed": -1}), "`seed` must be a whole number"),
|
||||
(json!({"seed": 1.5}), "`seed` must be a whole number"),
|
||||
(json!({"ids": [999_999]}), "no such object id"),
|
||||
];
|
||||
for (p, want) in bad {
|
||||
let e = s.execute(C, &p).unwrap_err().to_string();
|
||||
assert!(e.contains(want), "{p}: {e}");
|
||||
}
|
||||
assert_eq!(steps(&s), n);
|
||||
assert!(*s.doc().unwrap().doc == *before, "the document is unchanged");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn art_on_a_locked_artboard_given_by_id_keeps_its_fill() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0);
|
||||
let before = fill(&s, a);
|
||||
s.execute("artboard.setProps", &json!({"index": 0, "locked": true})).unwrap();
|
||||
let n = steps(&s);
|
||||
assert_eq!(s.execute(C, &json!({"ids": [a.0], "seed": 3})).unwrap()["count"], json!(0));
|
||||
assert_eq!(fill(&s, a), before);
|
||||
assert_eq!(steps(&s), n);
|
||||
}
|
||||
@@ -449,6 +449,7 @@ fn cropping_off_the_pixel_grid_keeps_the_hidden_colors_in_the_pixels() {
|
||||
})
|
||||
.unwrap()
|
||||
.to_rgba8();
|
||||
assert_eq!(own.dimensions(), (6, 5), "the cut's pixels");
|
||||
assert!(own.pixels().all(|p| p.0[3] == 255), "the cut pixels are the image's own, white included");
|
||||
assert_eq!(drawn(d, id, 0, 0)[3], 0, "white is hidden");
|
||||
s.execute(REMOVE_COLOR_MASK, &json!({"ids": [id.0]})).unwrap();
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
//! the bridges connect, replacing the circles or added above them.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{NodeId, NodeKind};
|
||||
use vectorcraft_doc::{Document, LiveShape, Node, NodeId, NodeKind};
|
||||
use vectorcraft_geom::PathData;
|
||||
use vectorcraft_pathops::addons::pathtools as pt;
|
||||
|
||||
@@ -32,15 +32,15 @@ pub(super) fn specs() -> Vec<CommandSpec> {
|
||||
vec![cmd!(
|
||||
"addon.pathtools.bridge",
|
||||
"Smooth Bridge",
|
||||
["Object", "Plug-ins", "Path Precision Tools"],
|
||||
[],
|
||||
None,
|
||||
"{radius?: % 1..1000 (100; the radius of each bridge's two arcs as a percentage of the smaller circle's radius: larger makes a wider, gentler bridge), gap?: pt 0..1000 (instead of radius: the arcs' radius is the smaller circle's radius plus this gap, so each arc stays this gap away from a circle of the smaller circle's size about the arc's center; for equal circles this gap apart that is where a third circle this gap from both sits, as in a triangular grid, so the channels around an empty place in such a grid are one width; giving both is an error), reach?: pt 0..10000 (10; with three or more circles: how far apart two circles' outlines may be for a bridge between them, overlapping ones included; two circles are bridged at any distance), keepOriginals?: bool (false: each outline replaces its circles, painted as the topmost of them; true: it goes directly above that circle and the circles stay), ids?: [id] (default: the selection)} join circles (paths whose outline is a circle, not hidden or locked) into metaball (aka meatball) shapes. Two circles become one closed outline: around each circle on its side away from the other, and along two concave arcs, one on each side, that touch both circles so the outline runs on smoothly into them. With three or more, every two circles within reach are bridged the same way, and the bridges that connect are united into one shape each (holes smaller than 1% of the smallest circle's area are filled); a pair within reach but too far apart for the radius gets no bridge, and so does one whose neck would be thinner than the precision its shape is united at, and a circle bridged to no other is left as it is. Overlapping and touching circles are joined too. One circle inside another (among three or more, any such pair within reach) is an error; so are two circles too far apart for the radius (the arcs would not reach both, or would cross), or three or more with no pair the arcs can join, which suggests a larger radius or gap when the largest one would bridge them; so are no two circles within reach, more than 2000 circles and more than 8000 bridges. One undo step; the outlines (and the circles left as they are) are selected → {ids, alone}, with {id} too for two circles",
|
||||
"{radius?: % 1..1000 (100; the radius of each bridge's two arcs as a percentage of the smaller circle's radius: larger makes a wider, gentler bridge), gap?: pt 0..1000 (instead of radius: the arcs' radius is the smaller circle's radius plus this gap, so each arc stays this gap away from a circle of the smaller circle's size about the arc's center; for equal circles this gap apart that is where a third circle this gap from both sits, as in a triangular grid, so the channels around an empty place in such a grid are one width; giving both is an error), reach?: pt 0..10000 (10; with three or more circles: how far apart two circles' outlines may be for a bridge between them, overlapping ones included; two circles are bridged at any distance), keepOriginals?: bool (false: each outline replaces its circles, painted as the topmost of them, and a group or compound path the other circles leave empty goes; true: it goes directly above that circle and the circles stay), ids?: [id] (default: the selection; a group, other than a clipping group, gives the objects inside it)} join circles (paths whose outline is a circle, not hidden or locked) into metaball (aka meatball) shapes. Two circles become one closed outline: around each circle on its side away from the other, and along two concave arcs, one on each side, that touch both circles so the outline runs on smoothly into them. With three or more, every two circles within reach are bridged the same way, and the bridges that connect are united into one shape each (holes smaller than 1% of the smallest circle's area are filled); a pair within reach but too far apart for the radius gets no bridge, and so does one whose neck would be thinner than the precision its shape is united at, and a circle bridged to no other is left as it is. Overlapping and touching circles are joined too. An object that is not a circle is an error that says why (an ellipse whose width and height differ, a compound path, a hidden or locked object, or another object). One circle inside another (among three or more, any such pair within reach) is an error; so are two circles too far apart for the radius (the arcs would not reach both, or would cross), or three or more with no pair the arcs can join, which suggests a larger radius or gap when the largest one would bridge them; so are no two circles within reach, more than 2000 circles and more than 8000 bridges. One undo step; the outlines (and the circles left as they are) are selected → {ids, alone}, with {id} too for two circles (kept for older scripts: Common Tangents makes the same outline with `curved`, and the command palette leaves this command out)",
|
||||
has_selection,
|
||||
bridge
|
||||
)]
|
||||
}
|
||||
|
||||
fn bridge(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
pub(super) fn bridge(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let percent = given(p, "radius", Some(RADII), C)?;
|
||||
let gap = given(p, "gap", Some(GAPS), C)?;
|
||||
let reach = given(p, "reach", Some(REACHES), C)?.unwrap_or(REACH);
|
||||
@@ -54,24 +54,37 @@ fn bridge(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
None => pt::ArcRadius::Share(percent.unwrap_or(RADIUS) / 100.0),
|
||||
};
|
||||
let keep = switch_or(p, "keepOriginals", false, C)?;
|
||||
let mut roots = checked_ids_or_selection(s, p, C)?;
|
||||
// An id given twice is one circle.
|
||||
let mut roots = members(&s.doc()?.doc, &checked_ids_or_selection(s, p, C)?);
|
||||
// An id given twice, or a circle given with its group, is one circle.
|
||||
roots.sort_unstable();
|
||||
roots.dedup();
|
||||
if roots.len() > pt::MAX_BRIDGED_CIRCLES {
|
||||
return Err(bad(C, "select at most 2000 circles to bridge"));
|
||||
}
|
||||
let circles: Vec<(NodeId, pt::Circle)> = {
|
||||
// The circles, and why the first object that is not one is refused.
|
||||
let (circles, why): (Vec<(NodeId, pt::Circle)>, Option<&str>) = {
|
||||
let d = &s.doc()?.doc;
|
||||
let editable = d.editable();
|
||||
d.paint_order(roots.iter().copied())
|
||||
let mut why = None;
|
||||
let circles = d
|
||||
.paint_order(roots.iter().copied())
|
||||
.into_iter()
|
||||
.filter_map(|id| match &d.node(id)?.kind {
|
||||
NodeKind::Path { path, guide: false, clipping: false, .. } if editable(id) => Some((id, pt::circle_of(path)?)),
|
||||
_ => None,
|
||||
.filter_map(|id| {
|
||||
let found = match &d.node(id)?.kind {
|
||||
NodeKind::Path { path, guide: false, clipping: false, .. } if editable(id) => pt::circle_of(path).map(|c| (id, c)),
|
||||
_ => None,
|
||||
};
|
||||
if found.is_none() && why.is_none() {
|
||||
why = Some(not_a_circle(d, id, editable(id)));
|
||||
}
|
||||
found
|
||||
})
|
||||
.collect()
|
||||
.collect();
|
||||
(circles, why)
|
||||
};
|
||||
if let Some(why) = why {
|
||||
return Err(bad(C, format!("select two or more circles to bridge: {why}")));
|
||||
}
|
||||
if circles.len() != roots.len() || circles.len() < 2 {
|
||||
return Err(bad(C, "select two or more circles to bridge"));
|
||||
}
|
||||
@@ -117,7 +130,8 @@ fn bridge(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
beside.finish(d)?;
|
||||
} else {
|
||||
// Each shape's topmost circle becomes its outline (a plain path now) and the others go.
|
||||
// Each shape's topmost circle becomes its outline (a plain path now) and the others go,
|
||||
// with each group they leave empty.
|
||||
let mut gone = vec![];
|
||||
for (members, outline) in shapes {
|
||||
let Some((&top, rest)) = members.split_last() else { continue };
|
||||
@@ -128,7 +142,9 @@ fn bridge(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
made.push(top);
|
||||
gone.extend_from_slice(rest);
|
||||
}
|
||||
let parents: Vec<NodeId> = gone.iter().filter_map(|id| d.parent_of(*id)).collect();
|
||||
remove_each(d, &gone)?;
|
||||
remove_emptied(d, parents)?;
|
||||
}
|
||||
sel.set(made.iter().chain(&alone).copied());
|
||||
Ok(made)
|
||||
@@ -140,6 +156,60 @@ fn bridge(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The objects `ids` names, with each group among them (a clipping group excepted) as the objects
|
||||
/// inside it, at any depth.
|
||||
fn members(d: &Document, ids: &[NodeId]) -> Vec<NodeId> {
|
||||
fn visit(n: &Node, out: &mut Vec<NodeId>) {
|
||||
match &n.kind {
|
||||
NodeKind::Group { children, clip: false } => children.iter().for_each(|c| visit(c, out)),
|
||||
_ => out.push(n.id),
|
||||
}
|
||||
}
|
||||
let mut out = vec![];
|
||||
for n in ids.iter().filter_map(|&id| d.node(id)) {
|
||||
visit(n, &mut out);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Why object `id`, which is not a circle the command bridges, is refused; `editable` says whether it can be
|
||||
/// edited (not hidden or locked).
|
||||
fn not_a_circle(d: &Document, id: NodeId, editable: bool) -> &'static str {
|
||||
// A pie spanning the whole turn, or none of it, is the whole ellipse.
|
||||
let whole = |(start, end): (f64, f64)| {
|
||||
let span = (end - start).rem_euclid(360.0);
|
||||
span < 1e-9 || 360.0 - span < 1e-9
|
||||
};
|
||||
match d.node(id).map(|n| &n.kind) {
|
||||
_ if !editable => "a selected object is hidden or locked",
|
||||
// A transform that stretches an ellipse leaves its stored width and height as they were, so one stored with
|
||||
// equal width and height gets the general message.
|
||||
Some(NodeKind::Path { live: Some(live), guide: false, clipping: false, .. }) if matches!(**live, LiveShape::Ellipse { w, h, pie, .. } if whole(pie) && w != h) => {
|
||||
"an ellipse whose width and height differ is not a circle: draw it with Shift held, or give it equal width and height"
|
||||
}
|
||||
Some(NodeKind::Compound { .. }) => "a compound path is not a circle: release it first",
|
||||
_ => "a selected object is not a circle",
|
||||
}
|
||||
}
|
||||
|
||||
/// Remove each of `parents` that is left with nothing in it, and then each group above it left with
|
||||
/// nothing in it in turn. Layers stay.
|
||||
fn remove_emptied(d: &mut Document, parents: Vec<NodeId>) -> Result<()> {
|
||||
for parent in parents {
|
||||
let mut at = Some(parent);
|
||||
while let Some(id) = at {
|
||||
match d.node(id) {
|
||||
Some(n) if !n.is_layer() && n.children().is_some_and(|c| c.is_empty()) => {
|
||||
at = d.parent_of(id);
|
||||
d.remove(id)?;
|
||||
}
|
||||
_ => break,
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The ids of `circles` at indices `at`, in paint order (the circles are listed in paint order).
|
||||
fn roots_of(circles: &[(NodeId, pt::Circle)], at: &[usize]) -> Vec<NodeId> {
|
||||
at.iter().filter_map(|&i| circles.get(i)).map(|(id, _)| *id).collect()
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user