mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-01 02:35:37 +01:00
Merge upstream panel harness changes for Layers appearance markers
This commit is contained in:
commit
3d0183495c
474 files changed
+39599
-4181
No files matched your search
@@ -0,0 +1,2 @@
|
||||
# The DXF writer goldens are compared byte for byte with the writer's output (LF line endings).
|
||||
crates/cad/tests/data/*.dxf -text
|
||||
@@ -38,27 +38,32 @@
|
||||
"applicability": "required"
|
||||
},
|
||||
{
|
||||
"name": "gate / test 1/5 (ubuntu-24.04)",
|
||||
"name": "gate / test 1/6 (ubuntu-24.04)",
|
||||
"app_id": 15368,
|
||||
"applicability": "required"
|
||||
},
|
||||
{
|
||||
"name": "gate / test 2/5 (ubuntu-24.04)",
|
||||
"name": "gate / test 2/6 (ubuntu-24.04)",
|
||||
"app_id": 15368,
|
||||
"applicability": "required"
|
||||
},
|
||||
{
|
||||
"name": "gate / test 3/5 (ubuntu-24.04)",
|
||||
"name": "gate / test 3/6 (ubuntu-24.04)",
|
||||
"app_id": 15368,
|
||||
"applicability": "required"
|
||||
},
|
||||
{
|
||||
"name": "gate / test 4/5 (ubuntu-24.04)",
|
||||
"name": "gate / test 4/6 (ubuntu-24.04)",
|
||||
"app_id": 15368,
|
||||
"applicability": "required"
|
||||
},
|
||||
{
|
||||
"name": "gate / test 5/5 (ubuntu-24.04)",
|
||||
"name": "gate / test 5/6 (ubuntu-24.04)",
|
||||
"app_id": 15368,
|
||||
"applicability": "required"
|
||||
},
|
||||
{
|
||||
"name": "gate / test 6/6 (ubuntu-24.04)",
|
||||
"app_id": 15368,
|
||||
"applicability": "required"
|
||||
},
|
||||
@@ -118,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",
|
||||
@@ -130,7 +137,15 @@
|
||||
"unsigned_artifact_name": "nightly-unsigned-linux-x86_64",
|
||||
"trust": {
|
||||
"fingerprint": "2B76741B414AAD6CD33E631213A005C0B9D7C3ED"
|
||||
}
|
||||
},
|
||||
"package_formats": [
|
||||
"appimage",
|
||||
"arch",
|
||||
"deb",
|
||||
"flatpak",
|
||||
"oci",
|
||||
"rpm"
|
||||
]
|
||||
},
|
||||
"macos-aarch64": {
|
||||
"unsigned_artifact_name": "nightly-unsigned-macos-aarch64",
|
||||
|
||||
@@ -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()
|
||||
@@ -39,11 +39,12 @@ jobs:
|
||||
dev-strip: true
|
||||
# The workspace crates also build without line tables. A panic still names its file and line.
|
||||
dev-debug: "0"
|
||||
# Five legs instead of one: shards 1 to 4 each build and run the tests of their own crates,
|
||||
# and shard 5 runs the other `cargo xtask ci` steps (xtask/src/shards.rs). `gate (<os>)`
|
||||
# passes only when all five did. On pushes to main, a `cache warm` leg builds what every
|
||||
# shard builds and saves the dependency cache.
|
||||
test-shards: 5
|
||||
# Six legs instead of one: shards 1 and 2 each build vectorcraft-ui-egui's tests and run
|
||||
# half of them, shards 3 to 5 each build and run the tests of their own crates, and shard 6
|
||||
# runs the other `cargo xtask ci` steps (xtask/src/shards.rs). `gate (<os>)` passes only
|
||||
# when all six did. On pushes to main, a `cache warm` leg builds what every shard builds and
|
||||
# saves the dependency cache.
|
||||
test-shards: 6
|
||||
shard-command: cargo xtask ci shard
|
||||
warm-command: cargo xtask ci warm
|
||||
# The dependency cache also keeps the compiled workspace crates and test executables, so a
|
||||
|
||||
@@ -11,9 +11,9 @@ permissions: {}
|
||||
|
||||
jobs:
|
||||
dispatch:
|
||||
# SOURCE PREPARATION: literal off until immutable shared tooling and policy qualification.
|
||||
# Enabled for automated scheduled producer completions on main.
|
||||
if: >-
|
||||
false && github.repository == 'storytold/vectorcraft' &&
|
||||
github.repository == 'storytold/vectorcraft' &&
|
||||
github.event_name == 'workflow_run'
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
name: VectorCraft unsigned nightly
|
||||
|
||||
# Enabled for supervised manual runs by the reviewed manual actor only; no schedule yet.
|
||||
# A later explicit opt-in may add a cadence (and turn on nightly-dispatch.yml with it).
|
||||
# Automated daily nightly builds at 06:30 UTC, plus supervised manual runs by reviewed manual actors.
|
||||
on:
|
||||
schedule:
|
||||
- cron: '30 6 * * *'
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
|
||||
@@ -7,9 +7,26 @@ on:
|
||||
- "apps/vectorcraft/Cargo.toml"
|
||||
- "apps/vectorcraft/src/printing.rs"
|
||||
- "apps/vectorcraft/src/printing/**"
|
||||
- "crates/ui-egui/Cargo.toml"
|
||||
- "crates/ui-egui/src/print.rs"
|
||||
- "crates/ui-egui/src/tests/printps.rs"
|
||||
- ".github/workflows/print.yml"
|
||||
# A push to main saves the Windows cache entry that pull requests restore.
|
||||
push:
|
||||
branches: [main]
|
||||
paths:
|
||||
- "Cargo.toml"
|
||||
- "Cargo.lock"
|
||||
- "apps/vectorcraft/Cargo.toml"
|
||||
- "apps/vectorcraft/src/printing.rs"
|
||||
- "apps/vectorcraft/src/printing/**"
|
||||
- "crates/ui-egui/Cargo.toml"
|
||||
- "crates/ui-egui/src/print.rs"
|
||||
- "crates/ui-egui/src/tests/printps.rs"
|
||||
- ".github/workflows/print.yml"
|
||||
# A weekly run on main saves a fresh entry after a new stable Rust changes the cache key.
|
||||
schedule:
|
||||
- cron: "23 6 * * 1"
|
||||
workflow_dispatch:
|
||||
permissions:
|
||||
contents: read
|
||||
@@ -18,15 +35,14 @@ concurrency:
|
||||
group: print-${{ github.ref }}
|
||||
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
|
||||
jobs:
|
||||
# Desktop printing on Windows, through the suite's shared gate. Pull requests restore the cache
|
||||
# but never save one; a manual run on main saves the cache they restore.
|
||||
# Desktop printing on Windows, through the suite's shared gate. Pushes to main, the weekly run and
|
||||
# manual runs on main save the cache; pull requests restore it and never save one.
|
||||
windows:
|
||||
# Tracks @main so suite-wide CI fixes reach every app without a PR in each repository.
|
||||
uses: storytold/craft-common-actions/.github/workflows/gate.yml@main
|
||||
with:
|
||||
os: '["windows-2022"]'
|
||||
# A change to Cargo.lock finds no cache (only main saves one) and builds everything cold:
|
||||
# about 55 minutes for `-p vectorcraft` alone, then the UI crate's tests.
|
||||
# A run that finds no cache builds everything cold, which took 76 to 126 minutes.
|
||||
timeout-minutes: 150
|
||||
# As in ci.yml: test binaries without debug info or symbols, and workspace crates without
|
||||
# line tables. A panic still names its file and line.
|
||||
@@ -36,10 +52,14 @@ jobs:
|
||||
craft-fonts-ref: ""
|
||||
tools: ""
|
||||
targets: ""
|
||||
# A filter that matches nothing still passes, so the printps run fails unless some test ran.
|
||||
# Both test runs select the same two packages, so Cargo resolves features once and the
|
||||
# second run reuses the first run's dependencies. The first runs every test of the app
|
||||
# (`--bin vectorcraft --test it`), the second the UI crate's `tests::printps` tests. A filter
|
||||
# that matches nothing still passes, so the printps run fails unless some test ran.
|
||||
command: |
|
||||
set -o pipefail
|
||||
cargo clippy --locked -p vectorcraft --all-targets -- -D warnings
|
||||
cargo test --locked -p vectorcraft
|
||||
cargo test --locked -p vectorcraft -p vectorcraft-ui-egui --bin vectorcraft --test it
|
||||
log="$RUNNER_TEMP/printps.log"
|
||||
cargo test --locked -p vectorcraft-ui-egui --lib -- tests::printps | tee "$log"
|
||||
cargo test --locked -p vectorcraft -p vectorcraft-ui-egui --lib -- tests::printps | tee "$log"
|
||||
grep -Eq 'test result: ok\. [1-9][0-9]* passed' "$log" || { echo "::error::tests::printps matched no tests"; exit 1; }
|
||||
@@ -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
|
||||
@@ -42,6 +42,8 @@ jobs:
|
||||
dry-run: ${{ github.event_name == 'schedule' }}
|
||||
app-name: vectorcraft
|
||||
app-title: VectorCraft
|
||||
macos-runner: macos-15
|
||||
macos-split-build: true
|
||||
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
|
||||
web-craft-fonts: true
|
||||
version: ${{ inputs.version }}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
name: SonarCloud
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
@@ -10,7 +11,7 @@ permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: sonarcloud-${{ github.ref }}
|
||||
group: ${{ github.ref == 'refs/heads/main' && format('sonarcloud-main-{0}', github.sha) || format('sonarcloud-{0}', github.ref) }}
|
||||
# A push to main is the run that publishes coverage; superseded runs there would never finish.
|
||||
cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
|
||||
|
||||
@@ -20,4 +21,7 @@ jobs:
|
||||
# The reusable workflow defaults build-jobs to 2 so a cold instrumented
|
||||
# archive stays within hosted-runner memory (craft-common-actions#333).
|
||||
uses: storytold/craft-common-actions/.github/workflows/sonarcloud.yml@main
|
||||
with:
|
||||
python-coverage-source: .github/scripts
|
||||
python-coverage-script: .github/scripts/tests/test_release_rpm_smoke.py
|
||||
secrets: inherit
|
||||
Generated
+192
-195
File diff suppressed because it is too large.
Load diff
+53
-55
@@ -4,53 +4,57 @@ members = ["crates/*", "apps/*", "xtask"]
|
||||
default-members = ["crates/*", "apps/vectorcraft", "apps/vectorcraft-cli", "xtask"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.24.1"
|
||||
version = "0.25.1"
|
||||
edition = "2024"
|
||||
license = "MIT OR Apache-2.0"
|
||||
rust-version = "1.95"
|
||||
repository = "https://github.com/storytold/vectorcraft"
|
||||
|
||||
[workspace.dependencies]
|
||||
craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703", default-features = false, features = ["interpret", "write"] }
|
||||
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d", default-features = false, features = ["interpret", "write"] }
|
||||
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
|
||||
craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
|
||||
# Language packs: the Craft apps' shared font store installs them (#4936).
|
||||
craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
|
||||
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
|
||||
# The `.vectorcraft` envelope: its members, version, embedded images and the data after the JSON.
|
||||
craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
|
||||
craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
|
||||
# `.pcraft` documents: their manifest, full-size composite, preview, layer pixels and ICC profile.
|
||||
craft-doc = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703", features = ["pcraft-pixels"] }
|
||||
craft-doc = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d", features = ["pcraft-pixels"] }
|
||||
# Native Affinity documents (craft-libs#914).
|
||||
craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
|
||||
# Bounded CDR (v1-v27) and CMX (32-bit) reader (craft-libs#778).
|
||||
craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
|
||||
# SVG parsing, limits, SVGZ and writer (craft-libs#778).
|
||||
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703", features = ["tree"] }
|
||||
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d", features = ["tree"] }
|
||||
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
|
||||
# EPS container, previews, ASCII85 and DSC comments (craft-libs#778).
|
||||
craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
|
||||
# DXF tags, reader and writer (craft-libs#778, #926, #927).
|
||||
craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
|
||||
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
|
||||
# WMF, EMF and EMF+ reader (craft-libs#778).
|
||||
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703", default-features = false, features = ["read", "write"] }
|
||||
craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
|
||||
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
|
||||
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
|
||||
craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
|
||||
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
|
||||
craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d", default-features = false, features = ["read", "write"] }
|
||||
craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
|
||||
craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
|
||||
craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
|
||||
craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
|
||||
# The framework facade (`craft::ui`, `craft::settings`, `craft::platform`, ...). No default features: each crate names
|
||||
# the members it imports.
|
||||
craft = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
craft = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
|
||||
# Below the egui layer, so not through the facade: the colour harmony rules and their settings (craft-color-ui
|
||||
# without its `ui` feature), the colour type they work in, and the craft-fonts tables the text crate's build writes.
|
||||
craft-color-ui = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
craft-color-ui = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
|
||||
craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
|
||||
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
|
||||
# Nightly profile isolation, launch protocol, and security fence.
|
||||
craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
|
||||
# internal
|
||||
vectorcraft-geom = { path = "crates/geom" }
|
||||
vectorcraft-color = { path = "crates/color" }
|
||||
@@ -86,7 +90,6 @@ vectorcraft-apischema = { path = "crates/apischema" }
|
||||
|
||||
# foundation
|
||||
kurbo = { version = "0.13", features = ["serde"] }
|
||||
peniko = "0.6"
|
||||
thiserror = "2"
|
||||
serde = { version = "1", features = ["derive", "rc"] }
|
||||
serde_json = { version = "1", features = ["float_roundtrip"] }
|
||||
@@ -156,10 +159,8 @@ egui = "0.37"
|
||||
egui_extras = { version = "0.37", default-features = false, features = ["svg"] }
|
||||
eframe = { version = "0.37", default-features = false }
|
||||
egui_kittest = "0.37"
|
||||
rfd = "0.17"
|
||||
arboard = { version = "3.6", default-features = false }
|
||||
clipboard-win = "5.4"
|
||||
webbrowser = "1"
|
||||
|
||||
[workspace.lints.rust]
|
||||
unsafe_code = "deny"
|
||||
@@ -193,25 +194,22 @@ lto = "thin"
|
||||
codegen-units = 1
|
||||
|
||||
[patch.crates-io]
|
||||
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
krilla = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
emath = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
epaint = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
eframe = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" }
|
||||
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
|
||||
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
|
||||
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
|
||||
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
|
||||
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
|
||||
krilla = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
|
||||
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
|
||||
emath = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
|
||||
epaint = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
|
||||
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
|
||||
egui = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
|
||||
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
|
||||
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
|
||||
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
|
||||
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
|
||||
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
|
||||
eframe = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
|
||||
winit = { git = "https://github.com/storytold/winit.git", rev = "0dfcec0eb62fda5904137a63a6dd0c3d83295f45" }
|
||||
@@ -163,6 +163,8 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
|
||||
- 2026-11-01: Expand Dashes into Paths joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): each selected path's dashed stroke becomes separate open paths, one per dash, laid out exactly as the stroke draws them (pattern, offset, Align Dashes to Corners and Path Ends), each keeping the stroke with the dashes off, so the gaps are real gaps for cutters and plotters, as one undo step (`addon.pathtools.expandDashes`, #4922).
|
||||
- 2026-11-01: Randomize Opacity joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): each selected object gets its own opacity at random between a minimum and a maximum percent, with a seed that repeats the result, as one undo step (`addon.arrange.randomizeOpacity`, #4925).
|
||||
- 2026-11-01: Sort Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects are sorted by width, height, area, position, opacity or stacking order (small to large, large to small or at random) and take another of those in that order, trading their values or stepping them evenly, as one undo step (`addon.arrange.sort`, #4917).
|
||||
- 2026-11-29: Match Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the other selected objects take the width, the height or both, the bounding-box angle and the stacking place of the key object, or of the top or the bottom selected object, about a reference point, with Preview, as one undo step (`addon.arrange.match`). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-29: Offset Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects are chained one after another in a row or a column with a set gap (negative to overlap them), in stacking order or by position, either way; the first stays in place and the others move only along the row or column, as one undo step (`addon.arrange.offset`). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-15: Tangent Circle joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the circles that touch two selected paths or compound paths at a set radius, or three of them (up to eight for three circles), touching each outline without crossing it; circles, rotated ellipses and other paths alike. A dialog that previews every circle or one picked by number, the current paint, one undo step (`addon.pathtools.tangentCircle`). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-17: Add Bounding Rectangle and Add Bounding Circle join the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): a live rectangle on the selection's geometric bounding box, or the smallest live circle that holds its outlines, around the whole selection or around each object, with the current paint and one undo step; the menu items open a dialog with Offset, One per Object and Preview (`addon.pathtools.boundingRectangle`, `addon.pathtools.boundingCircle`, #6966). A VectorCraft addition: headline numbers unchanged.
|
||||
- 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.
|
||||
@@ -174,6 +176,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
|
||||
- 2026-11-18: Common Tangents also takes a point (a path of one anchor) and a convex closed path: the lines from the point that touch the path, and the line from the point to the path's center if asked; a point on the outline gets the one tangent there, and a point inside gets none, with a message (#7846). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-15: With Smart Guides and Snap to Tangent on, a Line Segment drag pressed on one convex curved path and dragged near another lands on a common tangent of the two: both ends move to where the line touches the paths, each labeled "tangent" (#7845). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-17: Three-Point Arc tool, in the Line Segment tool's group after the Arc tool: two ends placed by a drag or two clicks, then a third point the open circular arc passes through, or with Third Point Sets Direction (Tool Options, or `]` while drawing) the direction the arc leaves an end in; it previews the arc, its center and, with Measurement Labels on, its radius, and draws it in one undo step (`shape.threePointArc`). Points with no arc are refused with a message. A VectorCraft addition: headline numbers unchanged.
|
||||
- 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-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.
|
||||
|
||||
@@ -211,6 +211,9 @@ fn main() -> ExitCode {
|
||||
#[cfg(target_os = "macos")]
|
||||
mac_fonts::install();
|
||||
prefs_dir::install_fonts();
|
||||
// The Language packs installed in the shared font store; `proof.installPack` returns once
|
||||
// installed.
|
||||
prefs_dir::use_language_packs();
|
||||
let mut args: Vec<String> = std::env::args().skip(1).collect();
|
||||
// Before any subcommand attaches the plug-in folder.
|
||||
let safe_mode = args.first().is_some_and(|a| a == "--safe-mode");
|
||||
|
||||
@@ -20,14 +20,15 @@ vectorcraft-format = { workspace = true }
|
||||
vectorcraft-text = { workspace = true }
|
||||
craft = { workspace = true, features = ["ui", "keymap", "automation", "platform"] }
|
||||
egui = { workspace = true }
|
||||
egui_extras = { workspace = true }
|
||||
log = { workspace = true }
|
||||
|
||||
[target.'cfg(target_arch = "wasm32")'.dependencies]
|
||||
# Image loaders for `src/web.rs`, which builds only for wasm32.
|
||||
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 = "51fcc3b0413af193db952df28dffae2321745703", version = "0.1.0" }
|
||||
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d", version = "0.1.0" }
|
||||
|
||||
wasm-bindgen = "0.2"
|
||||
serde_json = { workspace = true }
|
||||
|
||||
@@ -5,6 +5,10 @@ dist = "../../dist/web"
|
||||
public_url = "./"
|
||||
filehash = true
|
||||
|
||||
[tools]
|
||||
# Binaryen 123 crashes while optimizing the release bundle; keep the optimizer explicit.
|
||||
wasm_opt = "version_133"
|
||||
|
||||
[serve]
|
||||
addresses = ["127.0.0.1"]
|
||||
port = 8766
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
//! The hand-off from the browser's input hook to the visible UI pass.
|
||||
|
||||
use std::cell::Cell;
|
||||
|
||||
use egui::{DroppedFileHandle, Pos2, RawInput};
|
||||
|
||||
/// CSS pixels from the canvas origin, and whether Shift was held.
|
||||
pub(crate) type DragPosition = (f32, f32, bool);
|
||||
|
||||
pub(crate) struct DropBatch {
|
||||
pub(crate) files: Vec<DroppedFileHandle>,
|
||||
pub(crate) pos: Option<Pos2>,
|
||||
pub(crate) shift: bool,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct FileDrops(Vec<DroppedFileHandle>);
|
||||
|
||||
impl FileDrops {
|
||||
pub(crate) fn capture(&mut self, raw: &mut RawInput) {
|
||||
// The shared router reads dropped files at the start of the pass, before the web UI runs.
|
||||
self.0.append(&mut raw.dropped_files);
|
||||
}
|
||||
|
||||
pub(crate) fn take(&mut self, ctx: &egui::Context, position: &Cell<Option<DragPosition>>) -> Option<DropBatch> {
|
||||
let files = std::mem::take(&mut self.0);
|
||||
if files.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let at = position.take();
|
||||
let z = ctx.zoom_factor();
|
||||
let pos = at.map(|(x, y, _)| egui::pos2(x / z, y / z));
|
||||
let shift = at.is_some_and(|(_, _, shift)| shift);
|
||||
Some(DropBatch { files, pos, shift })
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(test, not(target_arch = "wasm32")))]
|
||||
mod tests {
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
use super::*;
|
||||
|
||||
#[derive(Debug)]
|
||||
struct Svg;
|
||||
|
||||
impl egui::DroppedFile for Svg {
|
||||
fn path(&self) -> &Path {
|
||||
Path::new("drawing.svg")
|
||||
}
|
||||
|
||||
fn bytes(&self) -> Result<Vec<u8>, String> {
|
||||
Err("test file has no contents".into())
|
||||
}
|
||||
}
|
||||
|
||||
fn check_handoff(at: Option<DragPosition>, expected_pos: Option<Pos2>, expected_shift: bool) {
|
||||
let ctx = egui::Context::default();
|
||||
let shared_files = Arc::new(AtomicUsize::new(0));
|
||||
ctx.on_begin_pass("observe dropped files before the app UI", {
|
||||
let shared_files = shared_files.clone();
|
||||
Arc::new(move |ui| {
|
||||
shared_files.fetch_add(ui.ctx().input(|input| input.raw.dropped_files.len()), Ordering::Relaxed);
|
||||
})
|
||||
});
|
||||
let mut drops = FileDrops::default();
|
||||
let position = Cell::new(at);
|
||||
let svg = Arc::new(Svg) as DroppedFileHandle;
|
||||
let mut raw = RawInput { dropped_files: vec![svg.clone()], ..Default::default() };
|
||||
|
||||
drops.capture(&mut raw);
|
||||
let mut delivered = Vec::new();
|
||||
ctx.run_ui(raw, |ui| delivered.extend(drops.take(ui.ctx(), &position))).textures_delta.clear();
|
||||
let mut next = RawInput::default();
|
||||
drops.capture(&mut next);
|
||||
ctx.run_ui(next, |ui| delivered.extend(drops.take(ui.ctx(), &position))).textures_delta.clear();
|
||||
|
||||
assert_eq!(shared_files.load(Ordering::Relaxed), 0, "the shared router must not see browser-owned drops");
|
||||
assert_eq!(delivered.len(), 1, "the browser UI must receive exactly one batch");
|
||||
let batch = &delivered[0];
|
||||
assert_eq!(batch.files.len(), 1, "the browser UI must receive exactly one file");
|
||||
assert!(Arc::ptr_eq(&batch.files[0], &svg));
|
||||
assert_eq!((batch.pos, batch.shift), (expected_pos, expected_shift));
|
||||
assert!(position.get().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_positioned_browser_drop_reaches_the_web_ui_once() {
|
||||
check_handoff(Some((53.0, 27.0, true)), Some(egui::pos2(53.0, 27.0)), true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_browser_drop_without_a_position_reaches_the_web_ui_once() {
|
||||
check_handoff(None, None, false);
|
||||
}
|
||||
}
|
||||
@@ -22,6 +22,8 @@
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
mod api;
|
||||
#[cfg(any(target_arch = "wasm32", test))]
|
||||
mod file_drops;
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
mod fonts;
|
||||
#[cfg(any(target_arch = "wasm32", test))]
|
||||
|
||||
@@ -22,6 +22,7 @@ use vectorcraft_ui_egui::print::{PrintJob, PrintService, Printer};
|
||||
use vectorcraft_ui_egui::{Services, VectorcraftApp};
|
||||
use wasm_bindgen::JsCast as _;
|
||||
|
||||
use crate::file_drops::{DragPosition, DropBatch, FileDrops};
|
||||
use crate::locks::WebLocks;
|
||||
use crate::pencil::SharedPointers;
|
||||
|
||||
@@ -39,7 +40,7 @@ struct OpenInboxes {
|
||||
|
||||
/// Where the pointer was over the canvas during the last file drag (CSS px from its top-left) and
|
||||
/// whether Shift was held: where dropped files land.
|
||||
type DragPos = Rc<Cell<Option<(f32, f32, bool)>>>;
|
||||
type DragPos = Rc<Cell<Option<DragPosition>>>;
|
||||
|
||||
/// A picture or file pasted into the page, read and waiting for the next frame with the modifiers
|
||||
/// held at the paste, and the context to wake for it (the current runner's).
|
||||
@@ -176,7 +177,7 @@ async fn run(host: Host, canvas: web_sys::HtmlCanvasElement, moving: Option<Movi
|
||||
}
|
||||
};
|
||||
app.adopt_context(ctx);
|
||||
Ok(Box::new(WebShell { app: Some(app), host, canvas: page, loss }))
|
||||
Ok(Box::new(WebShell { app: Some(app), host, canvas: page, loss, dropped: FileDrops::default() }))
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
@@ -376,6 +377,7 @@ struct WebShell {
|
||||
host: Host,
|
||||
canvas: web_sys::HtmlCanvasElement,
|
||||
loss: GraphicsLoss,
|
||||
dropped: FileDrops,
|
||||
}
|
||||
|
||||
impl WebShell {
|
||||
@@ -410,9 +412,9 @@ impl eframe::App for WebShell {
|
||||
embed::logic(ctx, || app.close_decision());
|
||||
}
|
||||
|
||||
/// Forward host-gathered pointer events into this frame's raw input, then let the app apply its
|
||||
/// shared input hook before egui runs.
|
||||
/// Gather browser drops and forward host pointer events before egui runs.
|
||||
fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) {
|
||||
self.dropped.capture(raw);
|
||||
raw.events.extend(self.host.pointers.borrow_mut().take());
|
||||
if let Some(app) = &mut self.app {
|
||||
app.raw_input(ctx, raw);
|
||||
@@ -425,18 +427,13 @@ impl eframe::App for WebShell {
|
||||
fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
|
||||
let ctx = ui.ctx().clone();
|
||||
if let Some(app) = &mut self.app {
|
||||
// DOM paste and drop are host input: read them in the UI phase, once per pass, not in
|
||||
// `logic` where a hidden tab replays the last shown frame's input.
|
||||
// Deliver host input in a visible UI pass. Hidden tabs only run `logic`.
|
||||
let pasted = self.host.pasted.borrow_mut().flavour.take();
|
||||
if let Some((f, held)) = pasted {
|
||||
app.paste_from_host(&ctx, f, held);
|
||||
}
|
||||
let dropped = ctx.input_mut(|i| std::mem::take(&mut i.raw.dropped_files));
|
||||
if !dropped.is_empty() {
|
||||
let at = self.host.drag.take();
|
||||
let z = ctx.zoom_factor();
|
||||
let (pos, shift) = (at.map(|(x, y, _)| egui::pos2(x / z, y / z)), at.is_some_and(|a| a.2));
|
||||
for f in dropped {
|
||||
if let Some(DropBatch { files, pos, shift }) = self.dropped.take(&ctx, &self.host.drag) {
|
||||
for f in files {
|
||||
let name = f.path().file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| "dropped".into());
|
||||
let target = app.drop_target(&name, app.drop_spot(pos), shift);
|
||||
let (inbox, place_inbox, repaint) = (self.host.inbox.dropped.clone(), self.host.place_inbox.clone(), ctx.clone());
|
||||
|
||||
@@ -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 }
|
||||
@@ -129,5 +130,3 @@ winresource = "0.1"
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile = "3"
|
||||
# Bound socket buffers in real loopback transport deadline regressions.
|
||||
socket2 = { workspace = true }
|
||||
@@ -1,30 +1,13 @@
|
||||
//! Build-time channel is distinct from a launch selector. A runtime environment cannot promote a
|
||||
//! stable build, and a nightly build refuses to start without its profile.
|
||||
use crate::launch_profile::Profile;
|
||||
use std::ffi::OsString;
|
||||
//! stable build, and a nightly build self-isolates into its canonical nightly profile root (or the
|
||||
//! profile root supplied by ArtCraft Launcher).
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum BuildFlavor {
|
||||
Stable,
|
||||
NightlyV1,
|
||||
}
|
||||
pub use craft_nightly::BuildFlavor;
|
||||
|
||||
pub const COMPILED: BuildFlavor = if cfg!(vectorcraft_nightly_v1) { BuildFlavor::NightlyV1 } else { BuildFlavor::Stable };
|
||||
|
||||
pub fn require_profile(flavor: BuildFlavor, profile: &Profile) -> Result<(), String> {
|
||||
match (flavor, profile.is_nightly()) {
|
||||
(BuildFlavor::NightlyV1, false) => Err("Open VectorCraft Nightly from ArtCraft Launcher".to_string()),
|
||||
(BuildFlavor::Stable, true) => Err("This is a stable VectorCraft build; nightly-v1 requires the nightly build".to_string()),
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn needs_native_error(flavor: BuildFlavor, desktop_session: bool) -> bool {
|
||||
desktop_session && flavor == BuildFlavor::NightlyV1
|
||||
}
|
||||
|
||||
/// `--version` and `-V` on their own, before any other argument is read.
|
||||
pub fn version_query(args: &[OsString]) -> bool {
|
||||
/// An exact plain version query, before resolving any profile or environment paths.
|
||||
pub fn version_query(args: &[std::ffi::OsString]) -> bool {
|
||||
matches!(args, [arg] if arg == "--version" || arg == "-V")
|
||||
}
|
||||
|
||||
@@ -37,40 +20,19 @@ pub fn version(flavor: BuildFlavor, stable: &str) -> String {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use super::{BuildFlavor, version, version_query};
|
||||
|
||||
#[test]
|
||||
fn only_a_nightly_desktop_refusal_requests_a_native_dialog() {
|
||||
assert!(needs_native_error(BuildFlavor::NightlyV1, true));
|
||||
assert!(!needs_native_error(BuildFlavor::NightlyV1, false));
|
||||
assert!(!needs_native_error(BuildFlavor::Stable, true));
|
||||
assert!(!needs_native_error(BuildFlavor::Stable, false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nightly_build_without_a_profile_is_refused_before_startup() {
|
||||
let started = std::cell::Cell::new(false);
|
||||
let result = require_profile(BuildFlavor::NightlyV1, &Profile::Stable).map(|()| started.set(true));
|
||||
assert!(result.unwrap_err().contains("ArtCraft Launcher"));
|
||||
assert!(!started.get());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stable_and_nightly_flavors_accept_only_their_own_profile() {
|
||||
let nightly = Profile::NightlyV1(std::path::PathBuf::from("already validated root"));
|
||||
assert!(require_profile(BuildFlavor::Stable, &Profile::Stable).is_ok());
|
||||
assert!(require_profile(BuildFlavor::Stable, &nightly).is_err());
|
||||
assert!(require_profile(BuildFlavor::NightlyV1, &nightly).is_ok());
|
||||
assert!(require_profile(BuildFlavor::NightlyV1, &Profile::Stable).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nightly_version_query_is_unambiguous_and_never_reinterprets_file_arguments() {
|
||||
assert_eq!(version(BuildFlavor::Stable, "0.24.1"), "0.24.1");
|
||||
assert_eq!(version(BuildFlavor::NightlyV1, "0.24.1"), "0.24.1 (nightly-v1)");
|
||||
fn plain_version_query_is_exact() {
|
||||
assert!(version_query(&["--version".into()]));
|
||||
assert!(version_query(&["-V".into()]));
|
||||
assert!(!version_query(&["--".into(), "--version".into()]));
|
||||
assert!(!version_query(&[]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn version_labels_nightly_without_changing_stable() {
|
||||
assert_eq!(version(BuildFlavor::Stable, "0.24.1"), "0.24.1");
|
||||
assert_eq!(version(BuildFlavor::NightlyV1, "0.24.1"), "0.24.1 (nightly-v1)");
|
||||
}
|
||||
}
|
||||
@@ -1,130 +1,28 @@
|
||||
//! Launcher-owned nightly-v1 bootstrap. Selected before logging, updates, fonts or saved state.
|
||||
//! Stable launches retain their original arguments and directory policy.
|
||||
//!
|
||||
//! The protocol is `vectorcraft --launch-profile nightly-v1 --profile-root <abs> -- [files…]`: the
|
||||
//! selector and the root are separate tokens, exactly once each, and everything after `--` is a file
|
||||
//! even when it looks like one of them. The Launcher's version check
|
||||
//! (`… --version`) is answered before the root is validated or touched.
|
||||
//! Nightly-v1 bootstrap backed by [`craft_nightly`]. Selected before logging, updates, fonts or
|
||||
//! saved state. Stable launches retain their original arguments and directory policy; direct
|
||||
//! nightly launches self-isolate into [`craft_nightly::canonical_profile_root`], while ArtCraft
|
||||
//! Launcher can supply `--launch-profile nightly-v1 --profile-root <abs> -- [args…]`.
|
||||
|
||||
use std::ffi::OsString;
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
use std::sync::OnceLock;
|
||||
|
||||
pub const VERSION: &str = "nightly-v1";
|
||||
pub use craft_nightly::NIGHTLY_V1_CONTRACT as VERSION;
|
||||
use craft_nightly::{BuildFlavor, Launch, Profile, ProfileError, StartupOptions};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum Profile {
|
||||
Stable,
|
||||
NightlyV1(PathBuf),
|
||||
}
|
||||
|
||||
impl Profile {
|
||||
pub fn is_nightly(&self) -> bool {
|
||||
matches!(self, Self::NightlyV1(_))
|
||||
}
|
||||
|
||||
pub fn root(&self) -> Option<&Path> {
|
||||
match self {
|
||||
Self::Stable => None,
|
||||
Self::NightlyV1(root) => Some(root),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub struct Launch {
|
||||
pub profile: Profile,
|
||||
pub args: Vec<OsString>,
|
||||
}
|
||||
|
||||
static PROFILE: OnceLock<Profile> = OnceLock::new();
|
||||
static STABLE: Profile = Profile::Stable;
|
||||
|
||||
pub fn current() -> &'static Profile {
|
||||
PROFILE.get().unwrap_or(&Profile::Stable)
|
||||
craft_nightly::current().unwrap_or(&STABLE)
|
||||
}
|
||||
|
||||
pub fn install(profile: Profile) -> Result<(), String> {
|
||||
PROFILE.set(profile).map_err(|_| "the launch profile was already selected".to_string())
|
||||
}
|
||||
|
||||
/// Recognize only the agreed literal selector/root pair before `--`. No filesystem or startup hook
|
||||
/// runs here.
|
||||
pub fn parse(args: Vec<OsString>) -> Result<Launch, String> {
|
||||
let mut selector = None;
|
||||
let mut root = None;
|
||||
let mut other = Vec::new();
|
||||
let mut files = Vec::new();
|
||||
let mut iter = args.iter();
|
||||
let mut delimiter = false;
|
||||
while let Some(arg) = iter.next() {
|
||||
if arg == "--" {
|
||||
delimiter = true;
|
||||
files.extend(iter.cloned());
|
||||
break;
|
||||
}
|
||||
if arg == "--launch-profile" || arg == "--profile-root" {
|
||||
let slot = if arg == "--launch-profile" { &mut selector } else { &mut root };
|
||||
if slot.is_some() {
|
||||
return Err("the profile selector and root must each occur exactly once".to_string());
|
||||
}
|
||||
let value = iter.next().filter(|v| !v.is_empty()).ok_or_else(|| "the profile selector/root needs a value".to_string())?;
|
||||
if value.to_string_lossy().starts_with("--") {
|
||||
return Err("the profile selector/root needs a value".to_string());
|
||||
}
|
||||
*slot = Some(value.clone());
|
||||
} else if arg.to_string_lossy().starts_with("--launch-profile=") || arg.to_string_lossy().starts_with("--profile-root=") {
|
||||
return Err("the nightly protocol requires separate literal selector/root argument tokens".to_string());
|
||||
} else {
|
||||
other.push(arg.clone());
|
||||
}
|
||||
}
|
||||
match (selector, root) {
|
||||
(None, None) => Ok(Launch { profile: Profile::Stable, args }),
|
||||
(Some(version), Some(root)) if version == VERSION => {
|
||||
if !delimiter || !other.is_empty() {
|
||||
return Err("nightly-v1 accepts only its selector/root followed by -- and file names".to_string());
|
||||
}
|
||||
let root = PathBuf::from(root);
|
||||
if !root.is_absolute() || root.components().any(|c| matches!(c, Component::ParentDir)) {
|
||||
return Err("the nightly profile root must be absolute and contain no parent traversal".to_string());
|
||||
}
|
||||
Ok(Launch { profile: Profile::NightlyV1(root), args: std::iter::once(OsString::from("--")).chain(files).collect() })
|
||||
}
|
||||
(Some(_), Some(_)) => Err("unsupported launch profile (expected nightly-v1)".to_string()),
|
||||
_ => Err("--launch-profile and --profile-root must be supplied together".to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The Launcher's version check: the selector/root pair followed by exactly `--version` (or `-V`),
|
||||
/// answered like a plain version query. Only [`parse`]'s lexical checks apply; the root is never
|
||||
/// validated or touched, and `-- --version` stays a file name.
|
||||
pub fn version_query(args: &[OsString]) -> bool {
|
||||
let Some((last, pair)) = args.split_last() else { return false };
|
||||
if last != "--version" && last != "-V" {
|
||||
return false;
|
||||
}
|
||||
let lexical = pair.iter().cloned().chain(std::iter::once(OsString::from("--"))).collect();
|
||||
matches!(parse(lexical), Ok(Launch { profile: Profile::NightlyV1(_), args }) if args.len() == 1)
|
||||
}
|
||||
|
||||
/// Validation finishes before the caller's first startup effect. Stable never calls the nightly root
|
||||
/// validator, so its portable and config resolution stays unchanged.
|
||||
pub fn prepare(mut launch: Launch, validate: impl FnOnce(&Path) -> Result<PathBuf, String>) -> Result<Launch, String> {
|
||||
if let Profile::NightlyV1(root) = &launch.profile {
|
||||
launch.profile = Profile::NightlyV1(validate(root)?);
|
||||
}
|
||||
Ok(launch)
|
||||
}
|
||||
|
||||
/// Resolve the selected private root before the caller's first startup effect.
|
||||
pub fn validate_root(root: &Path, env: impl Fn(&str) -> Option<OsString>, exe: Option<&Path>) -> Result<PathBuf, String> {
|
||||
crate::profile_root::validate(root, env, exe, crate::prefs_dir::profile::ensure_writable)
|
||||
pub fn prepare_launch(flavor: BuildFlavor, args: impl IntoIterator<Item = OsString>) -> Result<Launch, ProfileError> {
|
||||
let spec = crate::profile_root::app_profile_spec();
|
||||
craft_nightly::prepare_launch(flavor, &spec, args, &StartupOptions::default())
|
||||
}
|
||||
|
||||
/// The arguments a child of this process starts with: a nightly launch hands its profile on, so the
|
||||
/// child opens the same private profile instead of being refused ("Open VectorCraft Nightly…"), and
|
||||
/// `--` keeps a file whose name starts with '-' a file. Stable's child arguments are unchanged.
|
||||
/// Only `single_instance` starts a child, and macOS does not build it.
|
||||
/// child opens the same private profile, and `--` keeps a file whose name starts with '-' a file.
|
||||
/// Stable's child arguments are unchanged. Only `single_instance` starts a child, and macOS does
|
||||
/// not build it.
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
pub fn child_args(files: &[String]) -> Vec<OsString> {
|
||||
child_args_for(current(), files)
|
||||
@@ -132,21 +30,24 @@ pub fn child_args(files: &[String]) -> Vec<OsString> {
|
||||
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
fn child_args_for(profile: &Profile, files: &[String]) -> Vec<OsString> {
|
||||
let mut args: Vec<OsString> = match profile {
|
||||
Profile::Stable => Vec::new(),
|
||||
Profile::NightlyV1(root) => {
|
||||
vec![OsString::from("--launch-profile"), OsString::from(VERSION), OsString::from("--profile-root"), root.clone().into_os_string()]
|
||||
}
|
||||
};
|
||||
args.push(OsString::from("--"));
|
||||
args.extend(files.iter().map(OsString::from));
|
||||
args
|
||||
let delimited: Vec<OsString> = std::iter::once(OsString::from("--")).chain(files.iter().map(OsString::from)).collect();
|
||||
match profile {
|
||||
Profile::Stable => delimited,
|
||||
Profile::NightlyV1(root) => craft_nightly::launch_arguments(root, &delimited),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::cell::Cell;
|
||||
use std::ffi::OsString;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use craft_nightly::{BuildFlavor, Profile, ProfileError, StartupOptions, canonical_profile_root, parse_startup};
|
||||
|
||||
use super::VERSION;
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
use super::child_args_for;
|
||||
use crate::profile_root::app_profile_spec;
|
||||
|
||||
fn args(values: &[&str]) -> Vec<OsString> {
|
||||
values.iter().map(OsString::from).collect()
|
||||
@@ -156,95 +57,72 @@ mod tests {
|
||||
if cfg!(windows) { r"C:\NightlyData\profiles\vectorcraft" } else { "/nightly-data/profiles/vectorcraft" }
|
||||
}
|
||||
|
||||
fn nightly() -> Vec<OsString> {
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--"])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stable_arguments_and_directory_policy_are_unchanged() {
|
||||
fn stable_arguments_are_unchanged_and_nightly_flags_are_refused() {
|
||||
let spec = app_profile_spec();
|
||||
for argv in [args(&[]), args(&["--new-instance", "a.svg"]), args(&["--", "--launch-profile", "file.svg"])] {
|
||||
let launch = prepare(parse(argv.clone()).unwrap(), |_| panic!("stable must never validate a nightly root")).unwrap();
|
||||
assert_eq!(launch, Launch { profile: Profile::Stable, args: argv });
|
||||
let launch = parse_startup(BuildFlavor::Stable, &spec, argv.clone(), &StartupOptions::default()).unwrap();
|
||||
assert_eq!(launch.profile, Profile::Stable);
|
||||
assert_eq!(launch.passthrough_args, argv);
|
||||
}
|
||||
|
||||
let nightly_flags = args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--"]);
|
||||
let err = parse_startup(BuildFlavor::Stable, &spec, nightly_flags, &StartupOptions::default()).unwrap_err();
|
||||
assert!(matches!(err, ProfileError::NightlyFlagsInStableBuild));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exact_version_and_root_are_parsed_without_reinterpreting_file_names() {
|
||||
let mut argv = nightly();
|
||||
argv.extend(args(&["--profile-root", "art with spaces.svg"]));
|
||||
let launch = parse(argv).unwrap();
|
||||
fn nightly_direct_launch_self_isolates_into_canonical_profile_root() {
|
||||
let spec = app_profile_spec();
|
||||
let expected_root = canonical_profile_root("vectorcraft").unwrap();
|
||||
|
||||
let empty = parse_startup(BuildFlavor::NightlyV1, &spec, Vec::new(), &StartupOptions::default()).unwrap();
|
||||
assert_eq!(empty.profile, Profile::NightlyV1(expected_root.clone()));
|
||||
assert!(empty.passthrough_args.is_empty());
|
||||
|
||||
let with_args = parse_startup(BuildFlavor::NightlyV1, &spec, args(&["--safe-mode", "art.svg"]), &StartupOptions::default()).unwrap();
|
||||
assert_eq!(with_args.profile, Profile::NightlyV1(expected_root));
|
||||
assert_eq!(with_args.passthrough_args, args(&["--safe-mode", "art.svg"]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_launcher_arguments_preserve_profile_root_and_user_args() {
|
||||
let spec = app_profile_spec();
|
||||
let argv = args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--", "--profile-root", "art with spaces.svg"]);
|
||||
let launch = parse_startup(BuildFlavor::NightlyV1, &spec, argv, &StartupOptions::default()).unwrap();
|
||||
assert_eq!(launch.profile, Profile::NightlyV1(PathBuf::from(absolute())));
|
||||
assert_eq!(launch.args, args(&["--", "--profile-root", "art with spaces.svg"]));
|
||||
assert_eq!(launch.passthrough_args, args(&["--profile-root", "art with spaces.svg"]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_duplicate_unknown_and_conflicting_profile_arguments_are_refused() {
|
||||
for argv in [
|
||||
args(&["--launch-profile", VERSION]),
|
||||
args(&["--profile-root", absolute()]),
|
||||
args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--"]),
|
||||
args(&["--launch-profile", VERSION, "--launch-profile", VERSION, "--profile-root", absolute(), "--"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--profile-root", absolute(), "--"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", "relative", "--"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", "../escape", "--"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", "", "--"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--new-instance", "--"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute()]),
|
||||
] {
|
||||
assert!(parse(argv.clone()).is_err(), "{argv:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_launcher_version_check_is_a_version_query_only_in_its_exact_form() {
|
||||
let pair = &["--launch-profile", VERSION, "--profile-root", absolute()];
|
||||
let reversed = &["--profile-root", absolute(), "--launch-profile", VERSION];
|
||||
fn version_queries_are_recognized_plain_and_via_launcher() {
|
||||
let spec = app_profile_spec();
|
||||
for flag in ["--version", "-V"] {
|
||||
for form in [pair, reversed] {
|
||||
let mut argv = args(form);
|
||||
argv.push(flag.into());
|
||||
assert!(version_query(&argv), "{argv:?}");
|
||||
for argv in [
|
||||
args(&[flag]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), flag]),
|
||||
args(&["--profile-root", absolute(), "--launch-profile", VERSION, flag]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--", flag]),
|
||||
] {
|
||||
let launch = parse_startup(BuildFlavor::NightlyV1, &spec, argv.clone(), &StartupOptions::default()).unwrap();
|
||||
assert!(launch.is_version_query(), "{argv:?}");
|
||||
}
|
||||
}
|
||||
for argv in [
|
||||
args(&["--version"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--", "--version"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--new-instance", "--version"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--version"]),
|
||||
args(&["--version", "--launch-profile", VERSION, "--profile-root", absolute()]),
|
||||
args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--version"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", "relative", "--version"]),
|
||||
args(&["--launch-profile", VERSION, "--version"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--help"]),
|
||||
] {
|
||||
assert!(!version_query(&argv), "{argv:?}");
|
||||
}
|
||||
// Outside the query the strict protocol still refuses the version flag.
|
||||
assert!(parse(args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version"])).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_root_validation_never_reaches_startup_or_falls_back_to_stable() {
|
||||
let reached = Cell::new(false);
|
||||
let result = prepare(parse(nightly()).unwrap(), |_| Err("read-only or unsafe profile".to_string())).map(|_| reached.set(true));
|
||||
assert!(result.is_err());
|
||||
assert!(!reached.get());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn successful_root_validation_keeps_the_persistent_root_not_the_binary_tag() {
|
||||
let checked = PathBuf::from(absolute()).join("checked");
|
||||
let launch = prepare(parse(nightly()).unwrap(), |_| Ok(checked.clone())).unwrap();
|
||||
assert_eq!(launch.profile.root(), Some(checked.as_path()));
|
||||
assert!(launch.profile.is_nightly());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_joined_flag_form_is_refused() {
|
||||
for joined in [format!("--launch-profile={VERSION}"), format!("--profile-root={}", absolute())] {
|
||||
let argv = vec![OsString::from(joined), OsString::from("--")];
|
||||
assert!(parse(argv).is_err());
|
||||
fn version_and_document_arguments_are_not_a_version_only_query() {
|
||||
let spec = app_profile_spec();
|
||||
for flag in ["--version", "-V"] {
|
||||
for argv in [
|
||||
args(&[flag, "art with spaces.svg"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), flag, "art with spaces.svg"]),
|
||||
args(&["--profile-root", absolute(), "--launch-profile", VERSION, flag, "art with spaces.svg"]),
|
||||
] {
|
||||
let launch = parse_startup(BuildFlavor::NightlyV1, &spec, argv, &StartupOptions::default()).unwrap();
|
||||
assert!(!launch.is_version_query());
|
||||
assert_eq!(launch.passthrough_args, args(&[flag, "art with spaces.svg"]));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -258,6 +136,7 @@ mod tests {
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
#[test]
|
||||
fn a_nightly_child_inherits_the_selected_profile() {
|
||||
let spec = app_profile_spec();
|
||||
let root = PathBuf::from(absolute());
|
||||
let child = child_args_for(&Profile::NightlyV1(root.clone()), &["art.svg".to_string()]);
|
||||
let expected = vec![
|
||||
@@ -266,12 +145,12 @@ mod tests {
|
||||
OsString::from("--profile-root"),
|
||||
root.into_os_string(),
|
||||
OsString::from("--"),
|
||||
OsString::from("--"),
|
||||
OsString::from("art.svg"),
|
||||
];
|
||||
assert_eq!(child, expected);
|
||||
// The child's own parse finds the same profile and the file list.
|
||||
let launch = parse(child).unwrap();
|
||||
let launch = parse_startup(BuildFlavor::NightlyV1, &spec, child, &StartupOptions::default()).unwrap();
|
||||
assert!(launch.profile.is_nightly());
|
||||
assert_eq!(launch.args, args(&["--", "art.svg"]));
|
||||
assert_eq!(launch.passthrough_args, args(&["--", "art.svg"]));
|
||||
}
|
||||
}
|
||||
@@ -112,6 +112,43 @@ use prefs::{load_prefs, log_dir, open_store, prefs_enabled};
|
||||
const DEFAULT_SIZE: [f32; 2] = [1440.0, 900.0];
|
||||
const MIN_SIZE: [f32; 2] = [800.0, 500.0];
|
||||
|
||||
/// Apply the saved main-window placement before the first frame. On a first launch the
|
||||
/// framework maximizes the window when its default size would not fit the current screen.
|
||||
fn restore_main_window(window: &winit::window::Window, store: &Store, legacy: Option<vectorcraft_ui_egui::state::LegacyWindow>, wayland: bool) {
|
||||
use craft::behavior::placement::{Defaults, Placement, place};
|
||||
use craft::behavior::{Monitor, MonitorKey};
|
||||
use winit::dpi::{LogicalSize, PhysicalPosition};
|
||||
|
||||
let handles: Vec<_> = window.available_monitors().collect();
|
||||
let monitors: Vec<_> = handles
|
||||
.iter()
|
||||
.map(|monitor| {
|
||||
let size = monitor.size();
|
||||
let size = [size.width, size.height];
|
||||
let position = monitor.position();
|
||||
Monitor::new(MonitorKey::new(monitor.name().unwrap_or_default(), size), [position.x, position.y], size, monitor.scale_factor() as f32)
|
||||
})
|
||||
.collect();
|
||||
let home = window.current_monitor().or_else(|| window.primary_monitor()).and_then(|monitor| handles.iter().position(|m| *m == monitor));
|
||||
let defaults = Defaults::new(DEFAULT_SIZE, MIN_SIZE).with_no_position(wayland);
|
||||
let saved = store.get(craft::window::restore::MAIN).or_else(|| {
|
||||
let old = legacy?;
|
||||
let mut placement = Placement::new(old.size, window.scale_factor() as f32);
|
||||
placement.position_px = old.pos;
|
||||
placement.maximized = old.maximized;
|
||||
placement.repaired()
|
||||
});
|
||||
let placement = place(saved.as_ref(), &monitors, home, &defaults);
|
||||
if let Some([x, y]) = placement.position_px {
|
||||
window.set_outer_position(PhysicalPosition::new(x, y));
|
||||
}
|
||||
let [width, height] = placement.normal.size;
|
||||
let _ = window.request_inner_size(LogicalSize::new(width, height));
|
||||
if placement.maximized {
|
||||
window.set_maximized(true);
|
||||
}
|
||||
}
|
||||
|
||||
/// The window, Dock, taskbar and app-switcher icon (`assets/app-icon/`, see its README). macOS gets
|
||||
/// the version with Apple's transparent margin; elsewhere the full-bleed tile. The app ID matches
|
||||
/// `packaging/linux/ai.storyteller.vectorcraft.desktop` so Wayland docks find the launcher icon.
|
||||
@@ -384,58 +421,47 @@ fn channel_name() -> &'static str {
|
||||
|
||||
/// Says why a nightly launch was refused, then exits 2. A window could not have shown it yet: this
|
||||
/// app has no message box of its own before eframe starts (its dialogs are egui windows), so the
|
||||
/// text goes to standard error, which a Launcher launch records. The desktop-session test still
|
||||
/// decides whether a daily user would have seen it, for the message's wording.
|
||||
/// text goes to standard error, which a Launcher launch records.
|
||||
fn report_launch_profile_error(error: &str) {
|
||||
eprintln!("VectorCraft launch profile: {error}");
|
||||
let desktop_session = cfg!(windows)
|
||||
|| cfg!(target_os = "macos")
|
||||
|| (cfg!(target_os = "linux") && ["DISPLAY", "WAYLAND_DISPLAY"].into_iter().any(|key| std::env::var_os(key).is_some_and(|v| !v.is_empty())));
|
||||
if build_flavor::needs_native_error(build_flavor::COMPILED, desktop_session) {
|
||||
eprintln!("VectorCraft Nightly: open it from ArtCraft Launcher, which starts it in its own profile");
|
||||
}
|
||||
}
|
||||
|
||||
fn write_nightly_version() {
|
||||
use std::io::Write as _;
|
||||
let line = format!("VectorCraft {}\n", build_flavor::version(build_flavor::COMPILED, env!("VECTORCRAFT_BUILT_VERSION")));
|
||||
let _ = std::io::stdout().write_all(line.as_bytes());
|
||||
}
|
||||
|
||||
/// Selects the immutable launch profile before any startup service or side effect, and returns the
|
||||
/// arguments the rest of `main` reads. `None` means the process ends here (`--version` answered).
|
||||
fn prepare_launch() -> Option<Vec<std::ffi::OsString>> {
|
||||
// The trusted Launcher protocol is decided before the logger, updates, fonts or any saved state.
|
||||
// The launch profile is decided before the logger, updates, fonts or any saved state.
|
||||
let argv: Vec<_> = std::env::args_os().skip(1).collect();
|
||||
// A nightly answers its version before root validation, process identity, IPC or any window:
|
||||
// plain `--version`/`-V`, or the Launcher's `--launch-profile nightly-v1 --profile-root <dir>
|
||||
// --version`. A stable build leaves the answer to `read_command_line`, exactly as before.
|
||||
if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && (build_flavor::version_query(&argv) || launch_profile::version_query(&argv))
|
||||
{
|
||||
use std::io::Write as _;
|
||||
let line = format!("VectorCraft {}\n", build_flavor::version(build_flavor::COMPILED, env!("VECTORCRAFT_BUILT_VERSION")));
|
||||
let _ = std::io::stdout().write_all(line.as_bytes());
|
||||
// A plain nightly version query does not even need the OS home/data root to resolve.
|
||||
if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && build_flavor::version_query(&argv) {
|
||||
write_nightly_version();
|
||||
return None;
|
||||
}
|
||||
let early = launch_profile::prepare_launch(build_flavor::COMPILED, argv).unwrap_or_else(|error| {
|
||||
report_launch_profile_error(&error.to_string());
|
||||
std::process::exit(2)
|
||||
});
|
||||
// A launcher version query also exits before process identity, IPC or any window.
|
||||
// `craft_nightly::prepare_launch` skips root preparation for version queries.
|
||||
// A stable build leaves the answer to `read_command_line`, exactly as before.
|
||||
if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && early.is_version_query() {
|
||||
write_nightly_version();
|
||||
return None;
|
||||
}
|
||||
let early = launch_profile::parse(argv)
|
||||
.and_then(|launch| {
|
||||
build_flavor::require_profile(build_flavor::COMPILED, &launch.profile)?;
|
||||
Ok(launch)
|
||||
})
|
||||
.and_then(|launch| {
|
||||
launch_profile::prepare(launch, |root| {
|
||||
launch_profile::validate_root(root, |key| std::env::var_os(key), std::env::current_exe().ok().as_deref())
|
||||
})
|
||||
})
|
||||
.unwrap_or_else(|error| {
|
||||
report_launch_profile_error(&error);
|
||||
std::process::exit(2)
|
||||
});
|
||||
let nightly = early.profile.is_nightly();
|
||||
let identity =
|
||||
if nightly { vectorcraft_ui_egui::os_window::LaunchIdentity::NightlyV1 } else { vectorcraft_ui_egui::os_window::LaunchIdentity::Stable };
|
||||
let install = launch_profile::install(early.profile).and_then(|()| {
|
||||
// Every data path follows the selected profile from here on: settings, logs, recovery, the
|
||||
// user's libraries, plug-ins, caches and the single-instance record.
|
||||
if let Some(root) = launch_profile::current().root() {
|
||||
prefs_dir::profile::install_data_root(root.to_path_buf())?;
|
||||
}
|
||||
vectorcraft_ui_egui::os_window::select_identity(identity)
|
||||
});
|
||||
// Every data path follows the selected profile from here on: settings, logs, recovery, the
|
||||
// user's libraries, plug-ins, caches and the single-instance record.
|
||||
let install = launch_profile::current()
|
||||
.root()
|
||||
.map_or(Ok(()), |root| prefs_dir::profile::install_data_root(root.to_path_buf()))
|
||||
.and_then(|()| vectorcraft_ui_egui::os_window::select_identity(identity));
|
||||
if let Err(error) = install {
|
||||
report_launch_profile_error(&error);
|
||||
std::process::exit(2);
|
||||
@@ -453,11 +479,11 @@ fn prepare_launch() -> Option<Vec<std::ffi::OsString>> {
|
||||
// The window's identity, not the profile, failed: main's own failure status (1).
|
||||
std::process::exit(1);
|
||||
}
|
||||
Some(early.args)
|
||||
Some(early.passthrough_args)
|
||||
}
|
||||
|
||||
/// The arguments the rest of `main` reads: a nightly's profile tokens were consumed by
|
||||
/// `prepare_launch`, so what is left is `--` and the files to open. A stable launch reads its
|
||||
/// `prepare_launch`, leaving any user flags and files to open. A stable launch reads its
|
||||
/// arguments exactly as it always did.
|
||||
fn launch_arguments(nightly: bool, arguments: &[std::ffi::OsString]) -> Vec<String> {
|
||||
if nightly { arguments.iter().map(|a| a.to_string_lossy().into_owned()).collect() } else { std::env::args().skip(1).collect() }
|
||||
@@ -520,8 +546,9 @@ fn finish_pending_update(nightly: bool) {
|
||||
}
|
||||
|
||||
fn main() -> std::process::ExitCode {
|
||||
// The launch profile first: a nightly build without one is refused here, before the update
|
||||
// helper, the logger, fonts or any saved state, and `--version` is answered here too.
|
||||
// The launch profile first: a nightly build self-isolates or uses the Launcher's profile here,
|
||||
// before the update helper, the logger, fonts or any saved state, and `--version` is answered
|
||||
// here too.
|
||||
let Some(arguments) = prepare_launch() else { return std::process::ExitCode::SUCCESS };
|
||||
let nightly = launch_profile::current().is_nightly();
|
||||
#[cfg(windows)]
|
||||
@@ -571,6 +598,10 @@ fn main() -> std::process::ExitCode {
|
||||
mac_fonts::install();
|
||||
// VectorCraft's own Fonts folder, which text.addFontFiles copies fonts into.
|
||||
prefs_dir::install_fonts();
|
||||
// Language packs: installs and index fetches run on their own threads, so the window keeps
|
||||
// working while a pack downloads.
|
||||
prefs_dir::use_language_packs();
|
||||
vectorcraft_engine::packs::run_in_background(true);
|
||||
// The log file lives in the settings directory, next to the preferences; opened after the
|
||||
// arguments, so `--version` leaves no file behind. Records logged until now are written to it
|
||||
// first. Runs without preferences (agents' test runs) log to standard error only, so they
|
||||
@@ -787,9 +818,13 @@ fn main() -> std::process::ExitCode {
|
||||
Box::new(move |cc| {
|
||||
let ctx = &cc.egui_ctx;
|
||||
let winit_window = cc.winit_window().cloned();
|
||||
let placement = placement_store();
|
||||
if let Some(window) = &winit_window {
|
||||
restore_main_window(window, &placement, settings.lock().get().ui.legacy_window, wayland);
|
||||
}
|
||||
let spec = InstallSpec::new(shell_info, Arc::new(SystemWindows))
|
||||
.app_id(vectorcraft_ui_egui::os_window::app_id())
|
||||
.placement(Arc::new(Mutex::new(placement_store())))
|
||||
.placement(Arc::new(Mutex::new(placement)))
|
||||
.frame(decision);
|
||||
let spec = match start_pen(&winit_window) {
|
||||
Some(pen) => spec.pen(pen),
|
||||
@@ -804,7 +839,7 @@ fn main() -> std::process::ExitCode {
|
||||
};
|
||||
let (files, file_panels) = file_service(wake, folders);
|
||||
let files = Arc::new(files);
|
||||
craft::host::Host::builder(AppInfo {
|
||||
let host = craft::host::Host::builder(AppInfo {
|
||||
id: vectorcraft_ui_egui::os_window::SETTINGS_APP_ID,
|
||||
name: vectorcraft_ui_egui::os_window::name(),
|
||||
version: vectorcraft_ui_egui::os_window::version(),
|
||||
@@ -812,7 +847,8 @@ fn main() -> std::process::ExitCode {
|
||||
.i18n(vectorcraft_ui_egui::i18n::shared())
|
||||
.settings(Arc::new(settings.clone()))
|
||||
.files(files.clone())
|
||||
.install(ctx);
|
||||
.build();
|
||||
host.clone().install(ctx);
|
||||
let mut session = Session::new();
|
||||
// The profiles loaded before come back before the preferences name any of them.
|
||||
prefs_dir::attach_profile_store(&mut session);
|
||||
@@ -837,6 +873,7 @@ fn main() -> std::process::ExitCode {
|
||||
prefs_dir::attach_proof_setups(&mut session);
|
||||
prefs_dir::attach_script_data(&mut session);
|
||||
let mut app = VectorcraftApp::new(session, services(winit_window.clone()));
|
||||
app.host = Arc::new(host);
|
||||
app.adopt_context(&cc.egui_ctx);
|
||||
// A nightly is updated by the Launcher: it never checks for a stable release, which
|
||||
// would install this program's own updater over the nightly build.
|
||||
|
||||
@@ -24,6 +24,14 @@ pub fn install_fonts() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Have spelling and hyphenation read the Language packs installed in the Craft apps' shared font
|
||||
/// store (`proof.installPack`, or another Craft app), and install new ones there (#4936). Like the
|
||||
/// Fonts folder, whether or not `VECTORCRAFT_NO_PREFS` is set: the packs are the store's, not
|
||||
/// VectorCraft's preferences.
|
||||
pub fn use_language_packs() {
|
||||
vectorcraft_engine::packs::use_font_store();
|
||||
}
|
||||
|
||||
/// The folder `name` next to the settings, for what the user keeps: none in a run without
|
||||
/// preferences (`VECTORCRAFT_NO_PREFS`), which keeps nothing.
|
||||
fn store_dir(name: &str) -> Option<PathBuf> {
|
||||
|
||||
@@ -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));
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 235 KiB After Width: | Height: | Size: 121 KiB |
@@ -2626,6 +2626,83 @@ fn pattern_brush_scale_from_the_pen_fits_start_and_end_tiles_where_the_scale_fal
|
||||
}
|
||||
}
|
||||
|
||||
/// How far from y = 0 the outlines under `nodes` reach where they cross the vertical line at `x`.
|
||||
fn reach_at(nodes: &[Node], x: f64) -> f64 {
|
||||
let mut reach = 0.0f64;
|
||||
for n in nodes {
|
||||
n.walk(&mut |c| {
|
||||
for sp in c.path_data().into_iter().flat_map(|p| &p.subpaths) {
|
||||
for i in 0..sp.segment_count() {
|
||||
let s = sp.segment(i);
|
||||
let (a, b, c, d) = (s.p0.x, s.p1.x, s.p2.x, s.p3.x);
|
||||
let roots = kurbo::common::solve_cubic(a - x, 3.0 * (b - a), 3.0 * (c - 2.0 * b + a), d - 3.0 * c + 3.0 * b - a);
|
||||
for t in roots.into_iter().filter(|t| (-1e-9..=1.0 + 1e-9).contains(t)) {
|
||||
reach = reach.max(kurbo::ParamCurve::eval(&s, t.clamp(0.0, 1.0)).y.abs());
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
reach
|
||||
}
|
||||
|
||||
/// A pattern tile whose scale follows the pen is as tall as the scale at a short peak of the
|
||||
/// pressure, even where the peak falls between the positions the bent outline is checked at.
|
||||
#[test]
|
||||
fn pattern_brush_scale_from_the_pen_keeps_a_short_peak() {
|
||||
let doc = Document::new(1.0, 1.0);
|
||||
let b = scaled_pattern(PatternFit::Stretch, false, 100.0, Some(Variation::Pressure), Some(300.0));
|
||||
// One 10 × 4 pt tile on a 10 pt path: 100 % (2 pt either side) but for a peak at 2.2 pt, where
|
||||
// the scale reaches 300 % (6 pt either side).
|
||||
let peak = pressed(vec![(0.0, 0.0), (0.21, 0.0), (0.22, 1.0), (0.23, 0.0), (1.0, 0.0)]);
|
||||
let out = stroke_pieces(&doc, &b, &line(0.0, 0.0, 10.0, 0.0), &peak);
|
||||
// At the peak 300 %, half way up it 200 %, and 100 % on either side of it.
|
||||
for (x, want) in [(2.2, 6.0), (2.15, 4.0), (2.25, 4.0), (1.0, 2.0), (2.05, 2.0), (2.4, 2.0), (8.0, 2.0)] {
|
||||
assert!(near(reach_at(&out, x), want, 0.05), "at {x} pt: {} pt either side, not {want}", reach_at(&out, x));
|
||||
}
|
||||
}
|
||||
|
||||
/// An art brush whose width follows the pen is as wide as the pen gives at a short peak of the
|
||||
/// pressure, even where the peak falls between the positions the bent outline is checked at.
|
||||
#[test]
|
||||
fn art_brush_width_from_the_pen_keeps_a_short_peak() {
|
||||
let mut b = art_brush(rect_art(10.0, 4.0), ArtScale::Stretch);
|
||||
if let BrushKind::Art(a) = &mut b.kind {
|
||||
(a.width, a.width_mode, a.width_max) = (100.0, Some(Variation::Pressure), Some(300.0));
|
||||
}
|
||||
// 4 pt art on a 100 pt path: 2 pt either side but for a peak at 22 pt, where it is 6 pt.
|
||||
let peak = pressed(vec![(0.0, 0.0), (0.21, 0.0), (0.22, 1.0), (0.23, 0.0), (1.0, 0.0)]);
|
||||
let out = stroke_pieces(&Document::new(1.0, 1.0), &b, &line(0.0, 0.0, 100.0, 0.0), &peak);
|
||||
for (x, want) in [(22.0, 6.0), (21.5, 4.0), (22.5, 4.0), (10.0, 2.0), (20.5, 2.0), (24.0, 2.0), (80.0, 2.0)] {
|
||||
assert!(near(reach_at(&out, x), want, 0.05), "at {x} pt: {} pt either side, not {want}", reach_at(&out, x));
|
||||
}
|
||||
}
|
||||
|
||||
/// A pen recording sampled many times along a straight ramp draws as many anchors as the ramp's
|
||||
/// two ends do: samples that leave the scale on the same straight course are not split at.
|
||||
#[test]
|
||||
fn pen_samples_on_a_straight_ramp_add_no_anchors() {
|
||||
let doc = Document::new(1.0, 1.0);
|
||||
let bp = line(0.0, 0.0, 1000.0, 0.0);
|
||||
let ramp = |n: usize| pressed((0..=n).map(|i| (i as f64 / n as f64, i as f64 / n as f64)).collect());
|
||||
let anchors = |out: &[Node]| {
|
||||
let mut count = 0;
|
||||
for n in out {
|
||||
n.walk(&mut |c| count += c.path_data().map_or(0, |p| p.subpaths.iter().map(|s| s.anchors.len()).sum::<usize>()));
|
||||
}
|
||||
count
|
||||
};
|
||||
let pattern = scaled_pattern(PatternFit::Stretch, false, 50.0, Some(Variation::Pressure), Some(300.0));
|
||||
let mut art = art_brush(rect_art(10.0, 4.0), ArtScale::Stretch);
|
||||
if let BrushKind::Art(a) = &mut art.kind {
|
||||
(a.width, a.width_mode, a.width_max) = (50.0, Some(Variation::Pressure), Some(300.0));
|
||||
}
|
||||
for b in [&pattern, &art] {
|
||||
let (few, many) = (stroke_pieces(&doc, b, &bp, &ramp(1)), stroke_pieces(&doc, b, &bp, &ramp(2000)));
|
||||
assert_eq!(anchors(&many), anchors(&few), "{}", b.name);
|
||||
}
|
||||
}
|
||||
|
||||
/// On a closed path, a tile that Approximate Path starts before the path's start takes the scale
|
||||
/// recorded at the end of the stroke there, where the tile is drawn.
|
||||
#[test]
|
||||
|
||||
+152
-30
@@ -40,23 +40,32 @@ const MASK_STEPS: usize = 32;
|
||||
/// through the bend to within [`fit_tol`] of `doc_tol`, the flattening tolerance in document
|
||||
/// space, so the art keeps its curves (#3926). Where that cannot be done in no more anchors than
|
||||
/// chords would take, the path is flattened with `flat_tol` (art space) and subdivided so no chord
|
||||
/// is longer than `max_du` along x, as it always was. Stroke widths scale by `width_scale`.
|
||||
/// Text, images and symbol instances can't bend and are dropped. The art of a linked opacity mask
|
||||
/// bends with the object it masks.
|
||||
pub(crate) fn warp_node(n: &Node, f: &dyn Fn(Point) -> Point, flat_tol: f64, max_du: f64, doc_tol: f64, width_scale: f64) -> Option<Node> {
|
||||
/// is longer than `max_du` along x, as it always was. Both routes also split the art where it
|
||||
/// crosses each of `breaks` (art x, in order), so a turn of the map there is not stepped over.
|
||||
/// Stroke widths scale by `width_scale`. Text, images and symbol instances can't bend and are
|
||||
/// dropped. The art of a linked opacity mask bends with the object it masks.
|
||||
pub(crate) fn warp_node(
|
||||
n: &Node,
|
||||
f: &dyn Fn(Point) -> Point,
|
||||
flat_tol: f64,
|
||||
max_du: f64,
|
||||
doc_tol: f64,
|
||||
width_scale: f64,
|
||||
breaks: &[f64],
|
||||
) -> Option<Node> {
|
||||
let mut out = n.clone();
|
||||
out.appearance.scale_strokes(width_scale);
|
||||
match &mut out.kind {
|
||||
NodeKind::Path { path, live, .. } => {
|
||||
*live = None;
|
||||
*path = warp_path(path, f, flat_tol, max_du, fit_tol(doc_tol));
|
||||
*path = warp_path(path, f, flat_tol, max_du, fit_tol(doc_tol), breaks);
|
||||
if path.is_empty() {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } | NodeKind::Compound { children, .. } => {
|
||||
let kids: Vec<Arc<Node>> =
|
||||
children.iter().filter_map(|c| warp_node(c, f, flat_tol, max_du, doc_tol, width_scale)).map(Arc::new).collect();
|
||||
children.iter().filter_map(|c| warp_node(c, f, flat_tol, max_du, doc_tol, width_scale, breaks)).map(Arc::new).collect();
|
||||
if kids.is_empty() {
|
||||
return None;
|
||||
}
|
||||
@@ -64,7 +73,7 @@ pub(crate) fn warp_node(n: &Node, f: &dyn Fn(Point) -> Point, flat_tol: f64, max
|
||||
}
|
||||
_ => return None,
|
||||
}
|
||||
map_mask(&mut out, |art| warp_node(art, f, flat_tol, max_du, doc_tol, width_scale));
|
||||
map_mask(&mut out, |art| warp_node(art, f, flat_tol, max_du, doc_tol, width_scale, breaks));
|
||||
Some(out)
|
||||
}
|
||||
|
||||
@@ -80,12 +89,13 @@ fn map_mask(n: &mut Node, map: impl FnOnce(&Node) -> Option<Node>) {
|
||||
}
|
||||
|
||||
/// Each subpath of `p` through `f`: fitted cubics when they take no more anchors than the chords
|
||||
/// would, else the chords. Points `f` cannot place (not finite) are left out of the chords.
|
||||
fn warp_path(p: &PathData, f: &dyn Fn(Point) -> Point, flat_tol: f64, max_du: f64, fit_tol: f64) -> PathData {
|
||||
/// would, else the chords, both split at `breaks` ([`warp_node`]). Points `f` cannot place (not
|
||||
/// finite) are left out of the chords.
|
||||
fn warp_path(p: &PathData, f: &dyn Fn(Point) -> Point, flat_tol: f64, max_du: f64, fit_tol: f64, breaks: &[f64]) -> PathData {
|
||||
let mut subs = vec![];
|
||||
for sp in &p.subpaths {
|
||||
let Some(dense) = densified(sp, flat_tol, max_du) else { continue };
|
||||
if let Some(fit) = fitted(sp, f, fit_tol, dense.len()) {
|
||||
let Some(dense) = densified(sp, flat_tol, max_du, breaks) else { continue };
|
||||
if let Some(fit) = fitted(sp, f, fit_tol, dense.len(), breaks) {
|
||||
subs.push(fit);
|
||||
continue;
|
||||
}
|
||||
@@ -98,8 +108,9 @@ fn warp_path(p: &PathData, f: &dyn Fn(Point) -> Point, flat_tol: f64, max_du: f6
|
||||
}
|
||||
|
||||
/// `sp` flattened with `flat_tol` and its chords subdivided so none is longer than `max_du` along
|
||||
/// x, in art space: the points the chord route maps. `None` below two points.
|
||||
fn densified(sp: &SubPath, flat_tol: f64, max_du: f64) -> Option<Vec<Point>> {
|
||||
/// x, in art space, with a point where a chord crosses each of `breaks` (art x, in order): the
|
||||
/// points the chord route maps. `None` below two points.
|
||||
fn densified(sp: &SubPath, flat_tol: f64, max_du: f64, breaks: &[f64]) -> Option<Vec<Point>> {
|
||||
let mut bp = BezPath::new();
|
||||
sp.to_bezpath_into(&mut bp);
|
||||
let mut pts = vec![];
|
||||
@@ -118,16 +129,57 @@ fn densified(sp: &SubPath, flat_tol: f64, max_du: f64) -> Option<Vec<Point>> {
|
||||
let mut dense = vec![*pts.first()?];
|
||||
for (i, (&a, &b)) in pts.iter().zip(pts.iter().cycle().skip(1)).take(segs).enumerate() {
|
||||
let k = (((b.x - a.x).abs() / max_du).ceil() as usize).clamp(1, MAX_SUB);
|
||||
// The breaks the chord crosses, as parameters along it in order, go in among the even ones.
|
||||
let mut cuts: Vec<f64> = crossed(breaks, a.x, b.x).iter().map(|&x| (x - a.x) / (b.x - a.x)).collect();
|
||||
cuts.sort_by(f64::total_cmp);
|
||||
let mut cuts = cuts.into_iter().peekable();
|
||||
for j in 1..=k {
|
||||
let even = j as f64 / k as f64;
|
||||
while let Some(t) = cuts.next_if(|&t| t < even) {
|
||||
dense.push(a.lerp(b, t));
|
||||
}
|
||||
if sp.closed && i == segs - 1 && j == k {
|
||||
break;
|
||||
}
|
||||
dense.push(a.lerp(b, j as f64 / k as f64));
|
||||
dense.push(a.lerp(b, even));
|
||||
}
|
||||
}
|
||||
Some(dense)
|
||||
}
|
||||
|
||||
/// The values of `breaks` (in order) strictly between `a` and `b`, either way round.
|
||||
fn crossed(breaks: &[f64], a: f64, b: f64) -> &[f64] {
|
||||
let (lo, hi) = (a.min(b), a.max(b));
|
||||
let from = breaks.partition_point(|&x| x <= lo);
|
||||
let to = from + breaks[from..].partition_point(|&x| x < hi);
|
||||
&breaks[from..to]
|
||||
}
|
||||
|
||||
/// The parameters of `c` (in order, strictly between its ends) where its x is one of `breaks`;
|
||||
/// `line` when `c` is a line with its handles at thirds, whose x runs evenly.
|
||||
fn crossings(c: &CubicBez, line: bool, breaks: &[f64]) -> Vec<f64> {
|
||||
let xs = [c.p0.x, c.p1.x, c.p2.x, c.p3.x];
|
||||
let (lo, hi) = xs.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), &x| (lo.min(x), hi.max(x)));
|
||||
let inside = crossed(breaks, lo, hi);
|
||||
if inside.is_empty() {
|
||||
return vec![];
|
||||
}
|
||||
let [a, b, cc, d] = xs;
|
||||
let mut ts: Vec<f64> = vec![];
|
||||
for &x in inside {
|
||||
if line {
|
||||
ts.push((x - a) / (d - a));
|
||||
} else {
|
||||
ts.extend(kurbo::common::solve_cubic(a - x, 3.0 * (b - a), 3.0 * (cc - 2.0 * b + a), d - 3.0 * cc + 3.0 * b - a));
|
||||
}
|
||||
}
|
||||
// Pieces are no shorter than the step the fit reads their ends' directions over.
|
||||
ts.retain(|t| t.is_finite() && *t > FIT_DT && *t < 1.0 - FIT_DT);
|
||||
ts.sort_by(f64::total_cmp);
|
||||
ts.dedup_by(|t, prev| *t - *prev <= FIT_DT);
|
||||
ts
|
||||
}
|
||||
|
||||
/// Times an art segment is halved at most while looking for cubics that fit it.
|
||||
const FIT_DEPTH: u32 = 12;
|
||||
/// Parameter step of the finite differences that stand in for the bend's derivative.
|
||||
@@ -156,7 +208,10 @@ fn fit_tol(doc_tol: f64) -> f64 {
|
||||
/// bend at the same parameters, so the distance measured is never less than the true one. The
|
||||
/// halving is our own rather than kurbo's `fit_to_bezpath`, which halves until the floats run out
|
||||
/// on a map that never fits; the depth and the anchor count bound this one.
|
||||
fn fitted(sp: &SubPath, f: &dyn Fn(Point) -> Point, tol: f64, most: usize) -> Option<SubPath> {
|
||||
///
|
||||
/// A segment is first split where its x crosses one of `breaks` (art x, in order), so a turn of
|
||||
/// the map there lands on an anchor rather than between the checked positions.
|
||||
fn fitted(sp: &SubPath, f: &dyn Fn(Point) -> Point, tol: f64, most: usize, breaks: &[f64]) -> Option<SubPath> {
|
||||
if !(tol.is_finite() && tol > 0.0) {
|
||||
return None;
|
||||
}
|
||||
@@ -174,7 +229,11 @@ fn fitted(sp: &SubPath, f: &dyn Fn(Point) -> Point, tol: f64, most: usize) -> Op
|
||||
// A line's handles sit on its ends, which stalls its parameter there; thirds keep it even.
|
||||
let c = if line { CubicBez::new(c.p0, c.p0.lerp(c.p3, 1.0 / 3.0), c.p0.lerp(c.p3, 2.0 / 3.0), c.p3) } else { c };
|
||||
let at = |t: f64| Some(f(c.eval(t))).filter(|q| q.is_finite());
|
||||
fit_into(&at, (0.0, 1.0), line, tol, FIT_DEPTH, &mut bp, &mut room)?;
|
||||
let mut t0 = 0.0;
|
||||
for t1 in crossings(&c, line, breaks).into_iter().chain([1.0]) {
|
||||
fit_into(&at, (t0, t1), line, tol, FIT_DEPTH, &mut bp, &mut room)?;
|
||||
t0 = t1;
|
||||
}
|
||||
}
|
||||
if sp.closed {
|
||||
bp.close_path();
|
||||
@@ -316,6 +375,16 @@ impl AlongMap {
|
||||
fn max_scale(&self) -> f64 {
|
||||
(0..3).map(|i| self.slope(i).abs()).fold(1e-6, f64::max)
|
||||
}
|
||||
|
||||
/// The art x (offset from the art's left edge) that [`AlongMap::at`] takes to arc length `s`,
|
||||
/// when a piece with width spans it.
|
||||
fn x_at(&self, s: f64) -> Option<f64> {
|
||||
(0..3).find_map(|i| {
|
||||
let ((x0, x1), (s0, s1)) = ((self.xs[i], self.xs[i + 1]), (self.ss[i], self.ss[i + 1]));
|
||||
let spans = x1 - x0 > 1e-12 && (s1 - s0).abs() > 1e-12 && s0.min(s1) <= s && s <= s0.max(s1);
|
||||
spans.then(|| x0 + (s - s0) / (s1 - s0) * (x1 - x0))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The affine that reproduces `f` over `b` to within `tol`, if one does.
|
||||
@@ -414,12 +483,14 @@ fn bend(t: &Track, art: &Node, b: Rect, along: AlongMap, cross: f64) -> Option<N
|
||||
{
|
||||
return affine_node(art, a, cross.abs());
|
||||
}
|
||||
warp_node(art, &f, flat_tol, MAX_SEG / along.max_scale(), flat_tol * scale, cross.abs())
|
||||
warp_node(art, &f, flat_tol, MAX_SEG / along.max_scale(), flat_tol * scale, cross.abs(), &[])
|
||||
}
|
||||
|
||||
/// [`bend`], with the cross scale at arc length `s` multiplied by `widen(s)` (0..=1). The strokes
|
||||
/// of each object in the art take the factor at the middle of the object.
|
||||
fn bend_widened(t: &Track, art: &Node, b: Rect, along: AlongMap, cross: f64, widen: &dyn Fn(f64) -> f64) -> Option<Node> {
|
||||
/// of each object in the art take the factor at the middle of the object. `marks` are the arc
|
||||
/// lengths (in order) of the recorded pen samples `widen` runs in a straight line between; the art
|
||||
/// is split where `widen` turns at one by more than the bent outline's tolerance ([`pen_breaks`]).
|
||||
fn bend_widened(t: &Track, art: &Node, b: Rect, along: AlongMap, cross: f64, widen: &dyn Fn(f64) -> f64, marks: &[f64]) -> Option<Node> {
|
||||
let cy = b.center().y;
|
||||
let x0 = b.x0;
|
||||
let f = move |p: Point| {
|
||||
@@ -430,7 +501,45 @@ fn bend_widened(t: &Track, art: &Node, b: Rect, along: AlongMap, cross: f64, wid
|
||||
let art = widen_strokes(art, &factor);
|
||||
let scale = along.max_scale().max(cross.abs()).max(1e-6);
|
||||
let flat_tol = tolerance(b.height().max(b.width()) * scale) / scale;
|
||||
warp_node(&art, &f, flat_tol, MAX_SEG / along.max_scale(), flat_tol * scale, cross.abs())
|
||||
// A change of `dw` in `widen` moves the art's top and bottom edges `dw × reach` across.
|
||||
let reach = b.height() / 2.0 * cross.abs();
|
||||
let mut breaks: Vec<f64> =
|
||||
pen_breaks(marks, along.span(), widen, fit_tol(flat_tol * scale) / reach).into_iter().filter_map(|s| along.x_at(s)).map(|x| x + x0).collect();
|
||||
breaks.sort_by(f64::total_cmp);
|
||||
breaks.dedup();
|
||||
warp_node(&art, &f, flat_tol, MAX_SEG / along.max_scale(), flat_tol * scale, cross.abs(), &breaks)
|
||||
}
|
||||
|
||||
/// The arc lengths among `marks` (in order) strictly within `(s0, s1)` at which the art is split:
|
||||
/// those where `widen` is more than `tol` from the straight line between the ones kept on either
|
||||
/// side (the span's ends to begin with), chosen by splitting at the farthest one until every
|
||||
/// sample left out is within `tol` of that line. `widen` runs straight between samples, so it
|
||||
/// is then within `tol` of the line between kept samples all along, and samples on a straight
|
||||
/// course add no splits.
|
||||
fn pen_breaks(marks: &[f64], (s0, s1): (f64, f64), widen: &dyn Fn(f64) -> f64, tol: f64) -> Vec<f64> {
|
||||
if !(s1 > s0 && tol > 0.0) {
|
||||
return vec![];
|
||||
}
|
||||
let inside = {
|
||||
let from = marks.partition_point(|&s| s <= s0);
|
||||
&marks[from..from + marks[from..].partition_point(|&s| s < s1)]
|
||||
};
|
||||
if inside.is_empty() {
|
||||
return vec![];
|
||||
}
|
||||
let pts: Vec<(f64, f64)> = std::iter::once(s0).chain(inside.iter().copied()).chain([s1]).map(|s| (s, widen(s))).collect();
|
||||
let mut keep = vec![false; pts.len()];
|
||||
let mut spans = vec![(0, pts.len() - 1)];
|
||||
while let Some((i, j)) = spans.pop() {
|
||||
let ((sa, wa), (sb, wb)) = (pts[i], pts[j]);
|
||||
let off = |&(s, w): &(f64, f64)| (w - if sb > sa { wa + (wb - wa) * (s - sa) / (sb - sa) } else { wa }).abs();
|
||||
let far = (i + 1..j).map(|k| (k, off(&pts[k]))).filter(|&(_, d)| d > tol).max_by(|a, b| a.1.total_cmp(&b.1));
|
||||
if let Some((k, _)) = far {
|
||||
keep[k] = true;
|
||||
spans.extend([(i, k), (k, j)]);
|
||||
}
|
||||
}
|
||||
pts.iter().zip(keep).filter(|&(_, k)| k).map(|(p, _)| p.0).collect()
|
||||
}
|
||||
|
||||
/// `n` with the strokes of it and of everything inside it scaled by `factor` of the object they
|
||||
@@ -465,8 +574,17 @@ fn art_runs(t: &Track) -> Vec<(f64, f64)> {
|
||||
bounds.windows(2).map(|w| (w[0], w[1])).collect()
|
||||
}
|
||||
|
||||
/// The art on [s0, s1] of `t`, `cross` across where `widen` (0..=1, by arc length) is 1.
|
||||
fn art_on_run(t: &Track, (s0, s1): (f64, f64), a: &ArtBrush, (art, b): (&Node, Rect), cross: f64, widen: &dyn Fn(f64) -> f64) -> Option<Node> {
|
||||
/// The art on [s0, s1] of `t`, `cross` across where `widen` (0..=1, by arc length) is 1 (`marks`
|
||||
/// as [`bend_widened`] takes them).
|
||||
fn art_on_run(
|
||||
t: &Track,
|
||||
(s0, s1): (f64, f64),
|
||||
a: &ArtBrush,
|
||||
(art, b): (&Node, Rect),
|
||||
cross: f64,
|
||||
widen: &dyn Fn(f64) -> f64,
|
||||
marks: &[f64],
|
||||
) -> Option<Node> {
|
||||
let l = s1 - s0;
|
||||
if l <= 1e-9 {
|
||||
return None;
|
||||
@@ -489,7 +607,7 @@ fn art_on_run(t: &Track, (s0, s1): (f64, f64), a: &ArtBrush, (art, b): (&Node, R
|
||||
}
|
||||
}
|
||||
};
|
||||
bend_widened(t, art, b, along, cross, widen)
|
||||
bend_widened(t, art, b, along, cross, widen, marks)
|
||||
}
|
||||
|
||||
/// An art brush's art along `bp`. With a width that follows the pen (its pressure, tilt, bearing
|
||||
@@ -515,9 +633,13 @@ pub(crate) fn art(a: &ArtBrush, bp: &BezPath, weight: f64, stroke: &StrokeLayer)
|
||||
let p = a.width_mode.and_then(|m| PenAt::of(stroke, at / l).control(m)).unwrap_or(0.5);
|
||||
(light + (heavy - light) * p) / width
|
||||
};
|
||||
let marks = match a.width_mode {
|
||||
Some(m) if light != heavy && width > 0.0 => pen_marks(stroke, m, l),
|
||||
_ => vec![],
|
||||
};
|
||||
let runs = if a.overlap { art_runs(&t) } else { vec![(0.0, l)] };
|
||||
for run in runs {
|
||||
if let Some(n) = art_on_run(&t, run, a, (&art, b), cross, &widen) {
|
||||
if let Some(n) = art_on_run(&t, run, a, (&art, b), cross, &widen, &marks) {
|
||||
out.push(n);
|
||||
}
|
||||
}
|
||||
@@ -671,7 +793,7 @@ fn tile_scaled(t: &Track, tile: &(Node, Rect), s0: f64, s1: f64, k: &dyn Fn(f64)
|
||||
if mid <= 0.0 || marks.is_none_or(even) {
|
||||
return tile_on(t, tile, s0, s1, mid);
|
||||
}
|
||||
bend_widened(t, &tile.0, tile.1, AlongMap::linear(tile.1.width(), s0, s1), mid, &|s| k(s) / mid)
|
||||
bend_widened(t, &tile.0, tile.1, AlongMap::linear(tile.1.width(), s0, s1), mid, &|s| k(s) / mid, marks.unwrap_or_default())
|
||||
}
|
||||
|
||||
/// The most side tiles a run of a pattern brush places.
|
||||
@@ -966,7 +1088,7 @@ fn auto_corner(t: &Track, i: usize, source: CornerSource, side: &(Node, Rect), k
|
||||
}
|
||||
let s = if tw > 1e-9 { len / tw } else { 1.0 };
|
||||
let max_du = MAX_SEG / (2.0 * k * s.max(1.0));
|
||||
let warp = |f: &dyn Fn(Point) -> Point| warp_node(art, f, flat_tol, max_du, flat_tol * k, k);
|
||||
let warp = |f: &dyn Fn(Point) -> Point| warp_node(art, f, flat_tol, max_du, flat_tol * k, k, &[]);
|
||||
// Art point → (distance along from the left edge, stretched to `len`, and offset across).
|
||||
let along = move |q: Point| {
|
||||
let (x, y) = local(q);
|
||||
@@ -1393,7 +1515,7 @@ mod tests {
|
||||
let f = |p: Point| t.map(along.at(p.x - x0), p.y - cy);
|
||||
let tol = tolerance(b.height().max(b.width()));
|
||||
let exact = traced(art, &f, 1000);
|
||||
let chords: Vec<Point> = densified(art, tol, MAX_SEG).expect("the tile flattens").into_iter().map(f).collect();
|
||||
let chords: Vec<Point> = densified(art, tol, MAX_SEG, &[]).expect("the tile flattens").into_iter().map(f).collect();
|
||||
let curves = traced(sp, &|p| p, 200);
|
||||
let (e_curves, e_chords) = (apart(&curves, &exact), apart(&chords, &exact));
|
||||
// Checked at eight points a piece, so a little room between them.
|
||||
@@ -1419,7 +1541,7 @@ mod tests {
|
||||
let allowed: usize = path
|
||||
.subpaths
|
||||
.iter()
|
||||
.filter_map(|sp| densified(sp, 0.25, 1.5))
|
||||
.filter_map(|sp| densified(sp, 0.25, 1.5, &[]))
|
||||
.map(|dense| 1 + (FIT_CHECKS + 3) * (2 * dense.len() + FIT_DEPTH as usize + 1) + dense.len())
|
||||
.sum();
|
||||
let finite = |n: &Node| match &n.kind {
|
||||
@@ -1441,7 +1563,7 @@ mod tests {
|
||||
calls.set(calls.get() + 1);
|
||||
if calls.get() > allowed { Point::new(f64::NAN, f64::NAN) } else { f(p) }
|
||||
};
|
||||
let out = warp_node(&tile, &counted, 0.25, 1.5, 0.25, 1.0);
|
||||
let out = warp_node(&tile, &counted, 0.25, 1.5, 0.25, 1.0, &[]);
|
||||
assert!(calls.get() <= allowed, "map {i} was called {} times, {allowed} allowed", calls.get());
|
||||
match (i, &out) {
|
||||
(3, out) => assert!(out.is_none(), "a map that places nothing draws nothing"),
|
||||
@@ -1491,7 +1613,7 @@ mod tests {
|
||||
let mask = out.extras().mask.as_ref().expect("the mask is kept");
|
||||
assert_eq!(*mask.art, stroked(1), "{name} run: an unlinked mask stays where it was");
|
||||
|
||||
let out = bend_widened(t, &masked(true), b, along, 2.0, &|_| 0.5).expect("the art is drawn");
|
||||
let out = bend_widened(t, &masked(true), b, along, 2.0, &|_| 0.5, &[]).expect("the art is drawn");
|
||||
let mask = out.extras().mask.as_ref().expect("the mask is kept");
|
||||
assert_eq!(mask.art.kind, out.kind, "{name} run, widened: the mask's art bends with the art");
|
||||
assert_eq!(mask.art.appearance, out.appearance, "{name} run, widened: the mask's strokes narrow with the art's");
|
||||
|
||||
+159
-1
@@ -6,7 +6,7 @@
|
||||
//! space-separated form with an optional `/ alpha`, and `rgb()`, `rgba()`, `hsl()` and `hsla()` also
|
||||
//! take the comma-separated legacy form (<https://www.w3.org/TR/css-color-4/#legacy-color-syntax>).
|
||||
//! Hues take the angle units of CSS Values 4 (<https://www.w3.org/TR/css-values-4/#angles>). A hex
|
||||
//! color may leave out its `#`.
|
||||
//! color may leave out its `#`. [`format`] writes a color in these forms.
|
||||
//!
|
||||
//! The module reads a subset of CSS. A function's arguments are literal numbers, percentages,
|
||||
//! angles and `none`. A parenthesis inside the arguments makes the text invalid, so `calc()`,
|
||||
@@ -89,6 +89,126 @@ fn byte(v: f32) -> u8 {
|
||||
(v.clamp(0.0, 1.0) * 255.0).round() as u8
|
||||
}
|
||||
|
||||
/// The forms [`format`] writes a color in.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Notation {
|
||||
/// `#rrggbb`.
|
||||
Hex,
|
||||
/// `#rrggbbaa`, `ff` for a color without an alpha.
|
||||
HexAlpha,
|
||||
/// `rgb(51 102 153)`.
|
||||
Rgb,
|
||||
/// `hsl(210 50% 40%)`.
|
||||
Hsl,
|
||||
/// `oklch(49.93% 0.0987 250.43)`.
|
||||
Oklch,
|
||||
}
|
||||
|
||||
/// `rgb` (red, green and blue from 0 to 1) and the alpha `alpha` (0 to 1) as text of `notation`
|
||||
/// that [`parse`] reads back to the same `#rrggbb`. Each channel is first rounded to the nearest of
|
||||
/// 256 steps, as [`hex_of`] rounds it. `rgb()`, `hsl()` and `oklch()` use the space-separated form
|
||||
/// and add the alpha as a percentage after a `/` when it rounds to less than 100 %; `hsl()` and
|
||||
/// `oklch()` give their numbers to two places (chroma to four), without trailing zeros, and
|
||||
/// `oklch()` takes one or two more places where fewer would read back to other bytes. The hue of a
|
||||
/// gray is 0. [`Notation::Hex`] leaves the alpha out.
|
||||
pub fn format(rgb: [f32; 3], alpha: Option<f32>, notation: Notation) -> String {
|
||||
// A NaN alpha reads as none.
|
||||
let alpha = alpha.filter(|a| !a.is_nan());
|
||||
let bytes = rgb.map(byte);
|
||||
let units = bytes.map(|v| f64::from(v) / 255.0);
|
||||
let [r, g, b] = bytes;
|
||||
match notation {
|
||||
Notation::Hex => hex_of(rgb),
|
||||
Notation::HexAlpha => format!("{}{:02x}", hex_of(rgb), byte(alpha.unwrap_or(1.0))),
|
||||
Notation::Rgb => format!("rgb({r} {g} {b}{})", alpha_part(alpha)),
|
||||
Notation::Hsl => {
|
||||
let [h, s, l] = rgb_to_hsl(units);
|
||||
format!("hsl({} {}% {}%{})", hue_text(h), number(s * 100.0, 2), number(l * 100.0, 2), alpha_part(alpha))
|
||||
}
|
||||
Notation::Oklch => {
|
||||
let lch = oklab::to_oklch(units.map(|v| v as f32));
|
||||
// The fewest places that read back to the same bytes, from two (four for chroma).
|
||||
let fits = |p: i32| oklch_rounded(lch, p).filter(|&[l, c, h]| oklab::from_oklch(l, c, h).0.map(byte) == bytes);
|
||||
let (p, [l, c, h]) = (0..3).find_map(|extra| fits(extra).map(|v| (extra, v))).unwrap_or((2, oklch_rounded(lch, 2).unwrap_or(lch)));
|
||||
let places = |base: i32| usize::try_from(base + p).unwrap_or(2);
|
||||
let c = number(c, places(4));
|
||||
// A chroma that rounds to 0 is a gray, whose hue is 0.
|
||||
let h = if c == "0" { "0".to_string() } else { hue_text_to(h, places(2)) };
|
||||
format!("oklch({}% {c} {h}{})", number(l * 100.0, places(2)), alpha_part(alpha))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// OKLCH `lch` rounded as [`format`] writes it with `extra` more places than two for the
|
||||
/// lightness percentage and the hue and four for the chroma, or `None` when no chroma at or under
|
||||
/// the rounded one within [`OKLCH_CHROMA_STEPS`] steps lies inside sRGB. A color on the edge of
|
||||
/// sRGB can round to a point just outside it, where [`parse`] would lower the chroma to the edge at
|
||||
/// the rounded lightness and hue; the chroma is lowered a step at a time instead.
|
||||
fn oklch_rounded([l, c, h]: [f64; 3], extra: i32) -> Option<[f64; 3]> {
|
||||
let (l, h) = (rounded(l, 4 + extra), rounded(h, 2 + extra));
|
||||
let step = 10f64.powi(-(4 + extra));
|
||||
let mut c = rounded(c, 4 + extra);
|
||||
for _ in 0..OKLCH_CHROMA_STEPS {
|
||||
if c <= 0.0 || oklab::in_srgb(oklab::oklch_to_srgb(l, c, h)) {
|
||||
return Some([l, c.max(0.0), h]);
|
||||
}
|
||||
c = rounded(c - step, 4 + extra);
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// The most steps [`oklch_rounded`] lowers a chroma by to bring it inside sRGB.
|
||||
const OKLCH_CHROMA_STEPS: usize = 50;
|
||||
|
||||
/// `v` rounded to `places` decimal places.
|
||||
fn rounded(v: f64, places: i32) -> f64 {
|
||||
let f = 10f64.powi(places);
|
||||
(v * f).round() / f
|
||||
}
|
||||
|
||||
/// ` / 50%` for an alpha that rounds to less than 100 %, else nothing.
|
||||
fn alpha_part(alpha: Option<f32>) -> String {
|
||||
let percent = number(f64::from(alpha.unwrap_or(1.0).clamp(0.0, 1.0)) * 100.0, 2);
|
||||
if percent == "100" { String::new() } else { format!(" / {percent}%") }
|
||||
}
|
||||
|
||||
/// A hue in degrees to two places, 360 written as 0.
|
||||
fn hue_text(h: f64) -> String {
|
||||
hue_text_to(h, 2)
|
||||
}
|
||||
|
||||
/// A hue in degrees to `places` places, 360 written as 0.
|
||||
fn hue_text_to(h: f64, places: usize) -> String {
|
||||
let text = number(h, places);
|
||||
if text == "360" { "0".to_string() } else { text }
|
||||
}
|
||||
|
||||
/// `v` to `places` decimal places, without trailing zeros or a sign on zero.
|
||||
fn number(v: f64, places: usize) -> String {
|
||||
let text = format!("{v:.places$}");
|
||||
let text = if text.contains('.') { text.trim_end_matches('0').trim_end_matches('.') } else { text.as_str() };
|
||||
if text == "-0" { "0".to_string() } else { text.to_string() }
|
||||
}
|
||||
|
||||
/// Hue in degrees (0 to 360), saturation and lightness (0 to 1) of `rgb`, by CSS Color 4's
|
||||
/// rgbToHsl (<https://www.w3.org/TR/css-color-4/#rgb-to-hsl>); the hue of a gray is 0.
|
||||
fn rgb_to_hsl([r, g, b]: [f64; 3]) -> [f64; 3] {
|
||||
let (max, min) = (r.max(g).max(b), r.min(g).min(b));
|
||||
let (d, l) = (max - min, (max + min) / 2.0);
|
||||
if d == 0.0 {
|
||||
return [0.0, 0.0, l];
|
||||
}
|
||||
let s = if l == 0.0 || l == 1.0 { 0.0 } else { (max - l) / l.min(1.0 - l) };
|
||||
let h = if max == r {
|
||||
(g - b) / d + if g < b { 6.0 } else { 0.0 }
|
||||
} else if max == g {
|
||||
(b - r) / d + 2.0
|
||||
} else {
|
||||
(r - g) / d + 4.0
|
||||
};
|
||||
[h * 60.0, s, l]
|
||||
}
|
||||
|
||||
/// A hex color of 3, 4, 6 or 8 digits, with or without `#`.
|
||||
fn hex(text: &str) -> Option<CssColor> {
|
||||
let digits = text.strip_prefix('#').unwrap_or(text);
|
||||
@@ -412,6 +532,26 @@ mod tests {
|
||||
assert_eq!(hex_of([-1.0, 2.0, f32::NAN]), "#00ff00");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn format_writes_each_notation_with_the_alpha_where_it_belongs() {
|
||||
let rgb = [0.2, 0.4, 0.6];
|
||||
let half = Some(0.5);
|
||||
assert_eq!(format(rgb, half, Notation::Hex), "#336699");
|
||||
assert_eq!(format(rgb, half, Notation::HexAlpha), "#33669980");
|
||||
assert_eq!(format(rgb, None, Notation::HexAlpha), "#336699ff");
|
||||
assert_eq!(format(rgb, Some(1.0), Notation::HexAlpha), "#336699ff");
|
||||
assert_eq!(format(rgb, half, Notation::Rgb), "rgb(51 102 153 / 50%)");
|
||||
assert_eq!(format(rgb, None, Notation::Rgb), "rgb(51 102 153)");
|
||||
assert_eq!(format(rgb, Some(0.99999), Notation::Rgb), "rgb(51 102 153)", "an alpha that rounds to 100 % is left out");
|
||||
assert_eq!(format(rgb, Some(0.125), Notation::Hsl), "hsl(210 50% 40% / 12.5%)");
|
||||
assert_eq!(format(rgb, None, Notation::Oklch), "oklch(49.93% 0.0987 250.43)");
|
||||
assert_eq!(format([0.5; 3], None, Notation::Hsl), "hsl(0 0% 50.2%)");
|
||||
assert_eq!(format([1.0; 3], None, Notation::Oklch), "oklch(100% 0 0)");
|
||||
assert_eq!(format([0.0; 3], Some(0.0), Notation::Oklch), "oklch(0% 0 0 / 0%)");
|
||||
assert_eq!(format([1.0, 0.0, 0.0], None, Notation::Hsl), "hsl(0 100% 50%)");
|
||||
assert_eq!(format([-1.0, 2.0, f32::NAN], Some(f32::NAN), Notation::Rgb), "rgb(0 255 0)");
|
||||
}
|
||||
|
||||
proptest! {
|
||||
#[test]
|
||||
fn random_text_never_panics(text in "\\PC{0,60}") {
|
||||
@@ -439,5 +579,23 @@ mod tests {
|
||||
prop_assert_eq!(c.alpha.map(|v| (v * 255.0).round() as u8), Some(a));
|
||||
prop_assert_eq!(hex_of(c.rgb), format!("#{r:02x}{g:02x}{b:02x}"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_notation_reads_back_to_the_same_color(r: u8, g: u8, b: u8, a: u8) {
|
||||
let rgb = [r, g, b].map(|v| f32::from(v) / 255.0);
|
||||
let alpha = f32::from(a) / 255.0;
|
||||
for notation in [Notation::Hex, Notation::HexAlpha, Notation::Rgb, Notation::Hsl, Notation::Oklch] {
|
||||
let text = format(rgb, Some(alpha), notation);
|
||||
let c = parse(&text).unwrap_or_else(|| panic!("{text} should parse"));
|
||||
prop_assert_eq!(hex_of(c.rgb), hex_of(rgb), "{}", text);
|
||||
let read = c.alpha.unwrap_or(1.0);
|
||||
match notation {
|
||||
Notation::Hex => prop_assert_eq!(c.alpha, None),
|
||||
Notation::HexAlpha => prop_assert_eq!(byte(read), a),
|
||||
// A percentage to two places, left out when it rounds to 100.
|
||||
_ => prop_assert!((read - alpha).abs() <= 0.00006, "{} gives {}", text, read),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
//! the relative luminance of display sRGB with the 0.04045 threshold, the ratio
|
||||
//! (L1 + 0.05) / (L2 + 0.05) from 1 to 21, and the minimum ratios of success criteria 1.4.3
|
||||
//! (Contrast (Minimum), AA), 1.4.6 (Contrast (Enhanced), AAA) and 1.4.11 (Non-text Contrast, AA).
|
||||
//! [`closest_passing`] finds the color of the same hue nearest in lightness that meets a minimum.
|
||||
|
||||
/// What the content in front is, which sets the ratio it needs.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
@@ -87,6 +88,82 @@ pub fn ratio_text(ratio: f64) -> String {
|
||||
format!("{:.2}:1", (r * 100.0).floor() / 100.0)
|
||||
}
|
||||
|
||||
/// The lightnesses [`closest_passing`] tests on each side before it narrows down the first that
|
||||
/// passes.
|
||||
const LIGHTNESS_SAMPLES: usize = 16;
|
||||
/// The halvings [`closest_passing`] makes of the lightness step, which leave it within 1e-9.
|
||||
const LIGHTNESS_STEPS: usize = 32;
|
||||
/// The golden-section steps [`closest_passing`] takes to find the highest ratio between samples,
|
||||
/// which leave it within 1e-7 of the step.
|
||||
const PEAK_STEPS: usize = 32;
|
||||
/// Where between `lo` and `hi` `f` is highest, by golden-section search, which finds the top of a
|
||||
/// single peak between them. `f` is called 34 times.
|
||||
pub fn peak_between(mut lo: f64, mut hi: f64, f: &dyn Fn(f64) -> f64) -> f64 {
|
||||
let g = (5f64.sqrt() - 1.0) / 2.0;
|
||||
let (mut a, mut b) = (hi - g * (hi - lo), lo + g * (hi - lo));
|
||||
let (mut fa, mut fb) = (f(a), f(b));
|
||||
for _ in 0..PEAK_STEPS {
|
||||
if fa < fb {
|
||||
(lo, a, fa) = (a, b, fb);
|
||||
b = lo + g * (hi - lo);
|
||||
fb = f(b);
|
||||
} else {
|
||||
(hi, b, fb) = (b, a, fa);
|
||||
a = hi - g * (hi - lo);
|
||||
fa = f(a);
|
||||
}
|
||||
}
|
||||
if fa > fb { a } else { b }
|
||||
}
|
||||
|
||||
/// The display sRGB color closest to `srgb` whose `ratio` is at least `minimum`: the same OKLCH hue
|
||||
/// (<https://bottosson.github.io/posts/oklab/>) with the lightness raised or lowered, whichever
|
||||
/// takes the smaller step, and the chroma lowered where sRGB cannot show it, to the largest chroma
|
||||
/// below it that fits ([`crate::oklab::from_oklch`]). Each side is tested at
|
||||
/// 16 even steps up to white or black, and the step before the first that passes is narrowed down.
|
||||
/// When no step passes, the highest ratio between the neighbors of the highest step is looked for,
|
||||
/// so a color that passes only in a narrow band between white and black (as under a Difference
|
||||
/// blend) is found too. `srgb` itself when it passes, and None when nothing passes. The work is
|
||||
/// bounded: at most 167 colors are tested. The answer is the nearest passing color when the colors
|
||||
/// that pass on each side form one stretch up to white or black, as for a plain contrast ratio.
|
||||
/// When `ratio` lets colors pass in more than one stretch, a stretch that lies between two tested
|
||||
/// steps before the first passing one is missed, and a farther color can be returned.
|
||||
pub fn closest_passing(srgb: [f32; 3], minimum: f64, ratio: &dyn Fn([f32; 3]) -> f64) -> Option<[f32; 3]> {
|
||||
let passes = |c: [f32; 3]| ratio(c) >= minimum;
|
||||
let srgb = srgb.map(|v| if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 });
|
||||
if passes(srgb) {
|
||||
return Some(srgb);
|
||||
}
|
||||
let [l, c, h] = crate::oklab::to_oklch(srgb);
|
||||
let mut best: Option<(f64, [f32; 3])> = None;
|
||||
for end in [1.0, 0.0] {
|
||||
let at = |t: f64| crate::oklab::from_oklch(l + (end - l) * t, c, h).0;
|
||||
let step = |k: usize| k as f64 / LIGHTNESS_SAMPLES as f64;
|
||||
let ratios: Vec<f64> = (1..=LIGHTNESS_SAMPLES).map(|k| ratio(at(step(k)))).collect();
|
||||
// `lo` fails and `hi` passes, the step before the first sample that passes.
|
||||
let found = match ratios.iter().position(|r| *r >= minimum) {
|
||||
Some(i) => Some((step(i), step(i + 1))),
|
||||
None => {
|
||||
// Every sample fails: look for a higher ratio around the highest one.
|
||||
let top = ratios.iter().enumerate().fold((0, f64::NEG_INFINITY), |m, (i, r)| if *r > m.1 { (i, *r) } else { m }).0;
|
||||
let (lo, hi) = (step(top), step((top + 2).min(LIGHTNESS_SAMPLES)));
|
||||
let peak = peak_between(lo, hi, &|t| ratio(at(t)));
|
||||
passes(at(peak)).then_some((lo, peak))
|
||||
}
|
||||
};
|
||||
let Some((mut lo, mut hi)) = found else { continue };
|
||||
for _ in 0..LIGHTNESS_STEPS {
|
||||
let mid = (lo + hi) / 2.0;
|
||||
if passes(at(mid)) { hi = mid } else { lo = mid }
|
||||
}
|
||||
let step = (end - l).abs() * hi;
|
||||
if best.is_none_or(|(d, _)| step < d) {
|
||||
best = Some((step, at(hi)));
|
||||
}
|
||||
}
|
||||
best.map(|(_, c)| c)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -137,6 +214,80 @@ mod tests {
|
||||
assert_eq!(Category::parse("NormalText"), None);
|
||||
}
|
||||
|
||||
fn hue(srgb: [f32; 3]) -> f64 {
|
||||
let [_, a, b] = crate::libraries::srgb_to_oklab(srgb);
|
||||
b.atan2(a).to_degrees()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_closest_passing_color_keeps_the_hue_and_just_passes() {
|
||||
let (fg, bg) = (hex("fdc96e"), hex("355f78"));
|
||||
let fix = closest_passing(fg, 4.5, &|c| contrast_ratio(c, bg)).unwrap();
|
||||
let r = contrast_ratio(fix, bg);
|
||||
assert!((4.5..4.501).contains(&r), "{r}");
|
||||
assert!((hue(fix) - hue(fg)).abs() < 1.0, "{} {}", hue(fix), hue(fg));
|
||||
// A color lighter than the background gets lighter.
|
||||
assert!(relative_luminance(fix) > relative_luminance(fg));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_closest_passing_gray_on_white_is_a_darker_gray() {
|
||||
let white = [1.0; 3];
|
||||
let fix = closest_passing(hex("777777"), 4.5, &|c| contrast_ratio(c, white)).unwrap();
|
||||
let r = contrast_ratio(fix, white);
|
||||
assert!((4.5..4.501).contains(&r), "{r}");
|
||||
assert!((fix[0] - fix[1]).abs() < 1e-4 && (fix[1] - fix[2]).abs() < 1e-4, "{fix:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_color_that_passes_only_between_white_and_black_is_found() {
|
||||
// White drawn with Difference over mid gray: white and black both draw mid gray (1:1), and
|
||||
// mid gray draws black, 5.3:1.
|
||||
let gray = [0.5; 3];
|
||||
let difference = |c: [f32; 3]| -> [f32; 3] { std::array::from_fn(|i| (c[i] - gray[i]).abs()) };
|
||||
let fix = closest_passing([1.0; 3], 4.5, &|c| contrast_ratio(difference(c), gray)).unwrap();
|
||||
let r = contrast_ratio(difference(fix), gray);
|
||||
assert!((4.5..4.51).contains(&r), "{fix:?}: {r}");
|
||||
assert!(fix[0] > 0.5, "the nearest side of mid gray from white: {fix:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_narrow_band_between_the_samples_is_found() {
|
||||
// Over #5A5A5A only colors within a few hundredths of it draw dark enough with Difference
|
||||
// for 3:1 (black reaches 3.04:1), and no even step from white lands there.
|
||||
let gray = hex("5a5a5a");
|
||||
let difference = |c: [f32; 3]| -> [f32; 3] { std::array::from_fn(|i| (c[i] - gray[i]).abs()) };
|
||||
let ratio = |c: [f32; 3]| contrast_ratio(difference(c), gray);
|
||||
let fix = closest_passing([1.0; 3], 3.0, &ratio).unwrap();
|
||||
let r = ratio(fix);
|
||||
assert!((3.0..3.01).contains(&r), "{fix:?}: {r}");
|
||||
}
|
||||
|
||||
/// Just below blue's lightness the chromas sRGB holds at blue's hue come in two stretches, so a
|
||||
/// blue that needs a little more contrast keeps nearly all of its chroma.
|
||||
#[test]
|
||||
fn a_blue_that_darkens_a_little_keeps_its_chroma() {
|
||||
let gray = hex("b8b8b8");
|
||||
let ratio = |c: [f32; 3]| contrast_ratio(c, gray);
|
||||
let blue = [0.0, 0.0, 1.0];
|
||||
assert!(ratio(blue) < 4.5, "{}", ratio(blue));
|
||||
let fix = closest_passing(blue, 4.5, &ratio).unwrap();
|
||||
let ([_, c, h], [_, blue_c, blue_h]) = (crate::oklab::to_oklch(fix), crate::oklab::to_oklch(blue));
|
||||
assert!(ratio(fix) >= 4.5 && (h - blue_h).abs() < 1.0, "{fix:?}");
|
||||
assert!(c > blue_c - 0.02, "{fix:?}: chroma {c}, blue's {blue_c}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_passing_color_is_its_own_closest_and_nothing_passing_is_none() {
|
||||
let white = [1.0; 3];
|
||||
assert_eq!(closest_passing([0.0; 3], 7.0, &|c| contrast_ratio(c, white)), Some([0.0; 3]));
|
||||
assert_eq!(closest_passing(hex("808080"), 4.5, &|_| 1.0), None);
|
||||
// Mid gray: AAA for normal text needs 7:1, which neither white nor black reaches.
|
||||
let mid = hex("777777");
|
||||
assert_eq!(closest_passing(mid, 7.0, &|c| contrast_ratio(c, mid)), None);
|
||||
assert_eq!(closest_passing([f32::NAN; 3], 4.5, &|c| contrast_ratio(c, white)).map(|c| c.map(|v| v.is_finite())), Some([true; 3]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn half_opaque_black_over_white_is_mid_gray() {
|
||||
assert_eq!(over([0.0; 3], 0.5, [1.0; 3]), [0.5; 3]);
|
||||
|
||||
@@ -314,8 +314,14 @@ impl Document {
|
||||
self.renumber_stored_duplicates();
|
||||
}
|
||||
|
||||
/// Find a node anywhere in the tree.
|
||||
/// Find a node anywhere in the tree. With the lookup cache built, the node comes from the place the cache has for
|
||||
/// it, read once and without copying its index path; otherwise, and when that place no longer holds it, as
|
||||
/// [`Document::index_path`] finds it.
|
||||
pub fn node(&self, id: NodeId) -> Option<&Node> {
|
||||
if let Some(n) = self.index.get().and_then(|cached| cached.node_in(&self.layers, id)) {
|
||||
crate::id_index::note_path_lookup();
|
||||
return Some(n);
|
||||
}
|
||||
self.index_path(id).and_then(|p| self.node_at(&p))
|
||||
}
|
||||
|
||||
|
||||
+94
-19
@@ -2,6 +2,7 @@
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::ops::ControlFlow;
|
||||
use std::rc::Rc;
|
||||
use std::sync::{Arc, OnceLock};
|
||||
|
||||
@@ -403,6 +404,8 @@ thread_local! {
|
||||
thread_local! {
|
||||
/// How many objects' drawn art [`drawn`] evaluated on this thread.
|
||||
static DRAWN_EVALUATED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
/// How many times [`has_own_effects`] read an object's effects on this thread.
|
||||
static OWN_EFFECTS_READ: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// While a guard lives, [`drawn`] gives no art: the art it gave already has every geometry effect
|
||||
@@ -446,6 +449,66 @@ impl Drop for InMask {
|
||||
}
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
/// While an [`InteriorProbe`] lives, whether a leaf tested without
|
||||
/// [`HitOptions::unfilled_interiors`] would have been hit inside an unfilled closed path with
|
||||
/// it; `None` outside a probe.
|
||||
static INTERIOR_SEEN: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) };
|
||||
}
|
||||
|
||||
/// While a guard lives, the leaves tested without [`HitOptions::unfilled_interiors`] note whether
|
||||
/// they would be hit inside an unfilled closed path with it ([`unfilled_inside`]). A walk that hits
|
||||
/// nothing then looks inside the unfilled closed paths with a second walk only when one of them
|
||||
/// holds the point.
|
||||
struct InteriorProbe {
|
||||
was: Option<bool>,
|
||||
}
|
||||
|
||||
impl InteriorProbe {
|
||||
/// A probe when `wanted`, the walk that follows a miss looking inside unfilled closed paths.
|
||||
/// Otherwise the guard leaves things as they are, and no leaf measures an interior for it.
|
||||
fn open(wanted: bool) -> Self {
|
||||
Self { was: if wanted { INTERIOR_SEEN.replace(Some(false)) } else { INTERIOR_SEEN.get() } }
|
||||
}
|
||||
|
||||
/// Did a leaf tested since [`Self::open`] have an unfilled closed path holding the point?
|
||||
fn seen(&self) -> bool {
|
||||
INTERIOR_SEEN.get() == Some(true)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for InteriorProbe {
|
||||
fn drop(&mut self) {
|
||||
// A probe opened inside another passes what it saw on to it.
|
||||
let seen = INTERIOR_SEEN.get() == Some(true);
|
||||
INTERIOR_SEEN.set(self.was.map(|was| was || seen));
|
||||
}
|
||||
}
|
||||
|
||||
/// The hit inside path or compound path `n`'s closed subpaths, which have no visible fill, when
|
||||
/// `n` takes one there ([`takes_interior`]) and `contains` says they hold the point. Without
|
||||
/// [`HitOptions::unfilled_interiors`], under an [`InteriorProbe`], notes whether `n` would take
|
||||
/// one with it, and hits nothing.
|
||||
fn unfilled_inside(n: &Node, opt: HitOptions, contains: impl FnOnce() -> bool) -> Option<HitKind> {
|
||||
if takes_interior(n, opt) {
|
||||
return contains().then_some(HitKind::Fill);
|
||||
}
|
||||
if INTERIOR_SEEN.get() == Some(false) && takes_interior(n, HitOptions { unfilled_interiors: true, ..opt }) {
|
||||
#[cfg(test)]
|
||||
INTERIORS_PROBED.with(|c| c.set(c.get() + 1));
|
||||
if contains() {
|
||||
INTERIOR_SEEN.set(Some(true));
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// How many interiors [`unfilled_inside`] measured for an [`InteriorProbe`] on this thread.
|
||||
static INTERIORS_PROBED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// `f()`, with `mask` under a [`DrawnOff`] guard: the clipping path of a clip group or of a
|
||||
/// clipping layer is clicked and touched by its own geometry, whatever its geometry effects do to
|
||||
/// the region it clips to. It is also under an [`InMask`] guard.
|
||||
@@ -467,7 +530,7 @@ fn plain<T>(mask: bool, f: impl FnOnce() -> T) -> T {
|
||||
/// kept alone.
|
||||
fn drawn(symbols: &SymbolBoxes, n: &Node) -> Option<(Rc<Vec<Node>>, Option<Rect>)> {
|
||||
let f = DRAWN_ART.get()?;
|
||||
if DRAWN_OFF.get() || !evaluates(n) || !(has_own_effects(n) || draws_effects(symbols, n)) {
|
||||
if DRAWN_OFF.get() || !evaluates(n) || !draws_effects(symbols, n) {
|
||||
return None;
|
||||
}
|
||||
let doc = symbols.document();
|
||||
@@ -508,7 +571,7 @@ fn evaluates(n: &Node) -> bool {
|
||||
match &n.kind {
|
||||
NodeKind::Path { guide, .. } => !guide,
|
||||
NodeKind::Compound { .. } => true,
|
||||
NodeKind::Group { .. } | NodeKind::Layer { .. } => has_own_effects(n) || !n.appearance.items.is_empty(),
|
||||
NodeKind::Group { .. } | NodeKind::Layer { .. } => !n.appearance.items.is_empty() || has_own_effects(n),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
@@ -667,10 +730,15 @@ pub fn objects_at(doc: &Document, p: Point, opt: HitOptions, scope: Option<NodeI
|
||||
let locks = doc.locked_artboards_kept();
|
||||
let symbols = doc.kept_symbol_boxes().keeping(&locks.symbols);
|
||||
// As [`hit_test`] does: the objects hit by what they paint first, then those hit only inside
|
||||
// an unfilled closed path ([`HitOptions::unfilled_interiors`]).
|
||||
// an unfilled closed path ([`HitOptions::unfilled_interiors`]), when the first pass passes one
|
||||
// holding `p` ([`InteriorProbe`]).
|
||||
let painted = HitOptions { unfilled_interiors: false, ..opt };
|
||||
let interiors = opt.unfilled_interiors && !opt.path_only && !opt.outline;
|
||||
let mut probe = Some(InteriorProbe::open(interiors));
|
||||
'passes: for pass in [Some(painted), interiors.then_some(opt)].into_iter().flatten() {
|
||||
if pass.unfilled_interiors && !probe.take().is_some_and(|probe| probe.seen()) {
|
||||
break;
|
||||
}
|
||||
for layer in doc.layers.iter().rev() {
|
||||
if !layer.visible || layer.locked || layer.is_template() || doc.pattern_edit.as_ref().is_some_and(|e| e.layer != layer.id) {
|
||||
continue;
|
||||
@@ -1017,12 +1085,15 @@ fn object_hit(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes, editab
|
||||
/// an isolated group on one ([`crate::LockedArtboards::holds`]). Symbol instances are measured by their art
|
||||
/// ([`Node::geometric_bounds_with`]), and are also hit outside that box where their art paints.
|
||||
/// With [`HitOptions::unfilled_interiors`], a second walk looks inside the unfilled closed paths
|
||||
/// only when the first, without it, hits nothing.
|
||||
/// only when the first, without it, hits nothing and passes an unfilled closed path holding `p`
|
||||
/// ([`InteriorProbe`]).
|
||||
fn hit_test_skipping(doc: &Document, p: Point, opt: HitOptions, skip: &dyn Fn(NodeId) -> bool, editable_only: bool) -> Option<Hit> {
|
||||
let probe = InteriorProbe::open(opt.unfilled_interiors && !opt.path_only && !opt.outline);
|
||||
let painted = hit_test_walk(doc, p, HitOptions { unfilled_interiors: false, ..opt }, skip, editable_only);
|
||||
if painted.is_some() || !opt.unfilled_interiors || opt.path_only || opt.outline {
|
||||
if painted.is_some() || !opt.unfilled_interiors || opt.path_only || opt.outline || !probe.seen() {
|
||||
return painted;
|
||||
}
|
||||
drop(probe);
|
||||
hit_test_walk(doc, p, opt, skip, editable_only)
|
||||
}
|
||||
|
||||
@@ -1120,23 +1191,24 @@ pub(crate) fn clip_region_inputs() -> (u64, bool) {
|
||||
/// Does `clip`, or anything it holds, have a visible effect of its own or on a fill or stroke? Only
|
||||
/// then can the registered [`ClipRegion`] find a geometry effect in it.
|
||||
fn has_effects(clip: &Node) -> bool {
|
||||
let mut found = false;
|
||||
clip.walk(&mut |n| found |= has_own_effects(n));
|
||||
found
|
||||
clip.try_walk(&mut |n| if has_own_effects(n) { ControlFlow::Break(()) } else { ControlFlow::Continue(()) }).is_break()
|
||||
}
|
||||
|
||||
/// Does `n`, anything it holds, or the art of a symbol an instance in it shows have a visible
|
||||
/// effect? Only then can the registered [`DrawnArt`] find a geometry effect in it.
|
||||
/// effect? Only then can the registered [`DrawnArt`] find a geometry effect in it. The walk starts
|
||||
/// at `n`, so its own effects are read once, here, and it ends at the first object with an effect.
|
||||
fn draws_effects(symbols: &SymbolBoxes, n: &Node) -> bool {
|
||||
let mut found = false;
|
||||
n.walk(&mut |c| {
|
||||
found = found || has_own_effects(c) || matches!(&c.kind, NodeKind::SymbolInstance { symbol, .. } if symbols.has_effects(symbol));
|
||||
});
|
||||
found
|
||||
n.try_walk(&mut |c| {
|
||||
let has = has_own_effects(c) || matches!(&c.kind, NodeKind::SymbolInstance { symbol, .. } if symbols.has_effects(symbol));
|
||||
if has { ControlFlow::Break(()) } else { ControlFlow::Continue(()) }
|
||||
})
|
||||
.is_break()
|
||||
}
|
||||
|
||||
/// Does `n` itself have a visible effect, of its own or on one of its own fills or strokes?
|
||||
fn has_own_effects(n: &Node) -> bool {
|
||||
#[cfg(test)]
|
||||
OWN_EFFECTS_READ.with(|c| c.set(c.get() + 1));
|
||||
let visible = |e: &crate::Effect| e.visible;
|
||||
n.appearance.effects.iter().any(visible) || n.appearance.items.iter().any(|i| i.effects().iter().any(visible))
|
||||
}
|
||||
@@ -1672,8 +1744,8 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio
|
||||
match &n.kind {
|
||||
NodeKind::Path { path, rule, .. } => {
|
||||
let has_fill = n.appearance.has_visible_fill();
|
||||
let interior = !has_fill && path.subpaths.iter().any(|sp| sp.closed) && takes_interior(n, opt);
|
||||
let inside = || (interior && fill_contains(&closed_subpaths_at([path], p), *rule, p)).then_some(HitKind::Fill);
|
||||
let interior = !has_fill && path.subpaths.iter().any(|sp| sp.closed);
|
||||
let inside = || interior.then(|| unfilled_inside(n, opt, || fill_contains(&closed_subpaths_at([path], p), *rule, p))).flatten();
|
||||
if opt.outline
|
||||
&& let Some((hit, needs_full_check)) = near_path_body(path, p, opt.tol, 0.0)
|
||||
{
|
||||
@@ -1740,7 +1812,7 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio
|
||||
return (!opt.outline && !opt.path_only && fill_contains(&near, *rule, p)).then_some(HitKind::Fill);
|
||||
}
|
||||
let closed = || closed_subpaths_at(children.iter().filter_map(|m| m.path_data()), p);
|
||||
(takes_interior(n, opt) && fill_contains(&closed(), *rule, p)).then_some(HitKind::Fill)
|
||||
unfilled_inside(n, opt, || fill_contains(&closed(), *rule, p))
|
||||
}
|
||||
// The type path lies within the bounds: they rule out the rest before it is measured.
|
||||
NodeKind::Text(t) if opt.type_path_only => {
|
||||
@@ -2121,11 +2193,14 @@ pub fn symbol_part_at(doc: &Document, inst: &Node, p: Point, opt: HitOptions) ->
|
||||
let find = FindPart { art: &art, p, opt, symbols: &symbols, whole_instance: false, drawn: true };
|
||||
find.find(&art.art, &mut path, None, outline).map(|_| path)
|
||||
};
|
||||
// As [`hit_test`] does: inside an unfilled closed path only where nothing else is hit.
|
||||
// As [`hit_test`] does: inside an unfilled closed path only where nothing else is hit, and only
|
||||
// when the first walk passes one holding `p` ([`InteriorProbe`]).
|
||||
let probe = InteriorProbe::open(opt.unfilled_interiors && !opt.path_only && !outline);
|
||||
pick(HitOptions { unfilled_interiors: false, ..opt }).or_else(|| {
|
||||
if !opt.unfilled_interiors || opt.path_only || outline {
|
||||
if !opt.unfilled_interiors || opt.path_only || outline || !probe.seen() {
|
||||
return None;
|
||||
}
|
||||
drop(probe);
|
||||
walk.restart();
|
||||
pick(opt)
|
||||
})
|
||||
|
||||
@@ -200,6 +200,88 @@ fn symbol_art_parts_are_picked_inside_unfilled_frames_after_what_paints() {
|
||||
assert_eq!(at(220.0), None, "inside the clipping path where no art paints");
|
||||
}
|
||||
|
||||
/// An open path with a black stroke and no fill, from (`o`, 0) to (100, `o`) to (100, 100): its box
|
||||
/// holds (50, 50), and it is drawn nowhere near that point.
|
||||
fn open_corner(d: &mut Document, o: f64) -> Node {
|
||||
let pts = [Point::new(o, 0.0), Point::new(100.0, o), Point::new(100.0, 100.0)];
|
||||
let path = vectorcraft_geom::PathData::single(vectorcraft_geom::SubPath::polyline(&pts, false));
|
||||
Node::path(d.alloc_id(), path, Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0))
|
||||
}
|
||||
|
||||
/// How many leaves [`hit_leaf`] tested while `f` ran, with its result.
|
||||
fn leaves_tested<R>(f: impl FnOnce() -> R) -> (R, usize) {
|
||||
LEAVES_TESTED.with(|c| c.set(0));
|
||||
let r = f();
|
||||
(r, LEAVES_TESTED.with(std::cell::Cell::get))
|
||||
}
|
||||
|
||||
/// A selection click that hits nothing, where no unfilled closed path holds the point, walks the
|
||||
/// document once: looking inside unfilled closed paths tests no more leaves than a click without
|
||||
/// it. An unfilled closed path that holds the point is still hit inside.
|
||||
#[test]
|
||||
fn a_selection_click_that_hits_nothing_walks_the_document_once() {
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
for i in 0..10 {
|
||||
let corner = open_corner(&mut d, f64::from(i));
|
||||
d.insert(Some(l), 99, corner).unwrap();
|
||||
}
|
||||
let p = Point::new(50.0, 50.0);
|
||||
let (hit, without) = leaves_tested(|| hit_test(&d, p, SELECTING));
|
||||
assert_eq!(hit, None);
|
||||
assert_eq!(without, 10);
|
||||
let (hit, with) = leaves_tested(|| hit_test(&d, p, INTERIORS));
|
||||
assert_eq!(hit, None);
|
||||
assert_eq!(with, without, "hit_test");
|
||||
let (tops, with) = leaves_tested(|| objects_at(&d, p, INTERIORS, None));
|
||||
assert!(tops.is_empty());
|
||||
assert_eq!(with, without, "objects_at");
|
||||
// An unfilled frame below them that holds the point: the second walk finds it.
|
||||
let frame = d.alloc_id();
|
||||
let look = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0);
|
||||
d.insert(Some(l), 0, Node::path(frame, shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), look)).unwrap();
|
||||
assert_eq!(hit_test(&d, p, INTERIORS).map(|h| h.leaf), Some(frame));
|
||||
assert_eq!(objects_at(&d, p, INTERIORS, None), vec![frame]);
|
||||
}
|
||||
|
||||
/// A hit test that does not look inside unfilled closed paths measures none of their interiors.
|
||||
#[test]
|
||||
fn a_hit_test_without_unfilled_interiors_measures_no_interior() {
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
stroked(&mut d, &FRAME, true);
|
||||
let p = Point::new(50.0, 50.0);
|
||||
let probed = |f: &dyn Fn()| {
|
||||
INTERIORS_PROBED.with(|c| c.set(0));
|
||||
f();
|
||||
INTERIORS_PROBED.with(std::cell::Cell::get)
|
||||
};
|
||||
assert_eq!(probed(&|| assert_eq!(hit_test(&d, p, SELECTING), None)), 0, "hit_test");
|
||||
assert_eq!(probed(&|| assert!(objects_at(&d, p, SELECTING, None).is_empty())), 0, "objects_at");
|
||||
assert_eq!(probed(&|| assert_eq!(hit_test(&d, p, HitOptions { path_only: true, ..INTERIORS }), None)), 0, "by path only");
|
||||
assert_eq!(probed(&|| assert!(hit_test(&d, p, INTERIORS).is_some())), 1, "looking inside");
|
||||
}
|
||||
|
||||
/// Direct Selection on a dynamic symbol's instance that picks no part of its art, where no
|
||||
/// unfilled closed path of the art holds the point, walks the art once.
|
||||
#[test]
|
||||
fn a_symbol_part_pick_that_hits_nothing_walks_the_art_once() {
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
let corners: Vec<Arc<Node>> = (0..10).map(|i| Arc::new(open_corner(&mut d, f64::from(i)))).collect();
|
||||
let root = Node::group(d.alloc_id(), corners);
|
||||
d.symbols.push(crate::Symbol { dynamic: true, name: "Corners".into(), art: Arc::new(root) });
|
||||
let l = d.layers[0].id;
|
||||
let inst = d.alloc_id();
|
||||
d.insert(Some(l), 0, Node::new(inst, NodeKind::SymbolInstance { symbol: "Corners".into(), xf: vectorcraft_geom::Affine::IDENTITY })).unwrap();
|
||||
let n = d.node(inst).unwrap();
|
||||
let p = Point::new(50.0, 50.0);
|
||||
let (part, without) = leaves_tested(|| symbol_part_at(&d, n, p, SELECTING));
|
||||
assert_eq!(part, None);
|
||||
assert!(without >= 10, "{without} leaves tested");
|
||||
let (part, with) = leaves_tested(|| symbol_part_at(&d, n, p, INTERIORS));
|
||||
assert_eq!(part, None);
|
||||
assert_eq!(with, without);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn long_plain_stroke_hits_its_middle_and_curved_end() {
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
@@ -3569,3 +3651,68 @@ fn a_shaper_groups_original_shapes_in_symbol_art_are_not_picked() {
|
||||
assert_eq!(symbol_part_at(&d, n, Point::new(130.0, 50.0), opt), None, "over the erased original shape");
|
||||
assert_eq!(symbol_part_at(&d, n, Point::new(50.0, 50.0), opt), Some(vec![0, 1]), "over the shown face");
|
||||
}
|
||||
|
||||
/// A hover over empty canvas past many plain paths reads each path's effects once, and the layer's
|
||||
/// once.
|
||||
#[test]
|
||||
fn hovers_past_plain_paths_read_each_paths_effects_once() {
|
||||
set_drawn_art(shifted_art);
|
||||
let mut d = Document::new(1000.0, 1000.0);
|
||||
let l = d.layers[0].id;
|
||||
let paths = 100;
|
||||
for i in 0..paths {
|
||||
let n = square(&mut d, (i % 10) as f64 * 60.0, (i / 10) as f64 * 60.0);
|
||||
d.insert(Some(l), 0, n).unwrap();
|
||||
}
|
||||
let reads = || OWN_EFFECTS_READ.with(std::cell::Cell::get);
|
||||
let before = reads();
|
||||
assert!(hit_test(&d, Point::new(900.0, 900.0), HitOptions::default()).is_none());
|
||||
let read = reads() - before;
|
||||
assert_eq!(read, paths + 1, "each path's effects and the layer's are read once");
|
||||
assert!(hit_at(&d, 25.0, 25.0, HitOptions::default()).is_some(), "a square is still hit");
|
||||
}
|
||||
|
||||
/// Whether a compound clipping path, or a compound path, has a live effect is settled by the first
|
||||
/// object found with one: the members after it are not read.
|
||||
#[test]
|
||||
fn an_effect_on_a_compound_path_is_found_without_reading_its_members() {
|
||||
set_clip_region(moved_clip_region);
|
||||
set_drawn_art(shifted_art);
|
||||
let mut d = Document::new(1000.0, 1000.0);
|
||||
let members: Vec<_> = (0..100)
|
||||
.map(|i| Arc::new(Node::path(d.alloc_id(), shapes::rectangle(Rect::new(i as f64, 0.0, i as f64 + 5.0, 5.0)), Default::default())))
|
||||
.collect();
|
||||
let mut mask = Node::new(d.alloc_id(), NodeKind::Compound { children: members, rule: FillRule::NonZero });
|
||||
mask.appearance.effects.push(test_move());
|
||||
let reads = || OWN_EFFECTS_READ.with(std::cell::Cell::get);
|
||||
let before = reads();
|
||||
assert!(has_effects(&mask));
|
||||
assert_eq!(reads() - before, 1, "the clipping path's own effect ends the search");
|
||||
let symbols = d.symbol_boxes();
|
||||
let before = reads();
|
||||
assert!(draws_effects(&symbols, &mask));
|
||||
assert_eq!(reads() - before, 1, "the compound path's own effect ends the search");
|
||||
}
|
||||
|
||||
/// The pointer resting over empty canvas past many paths reads their anchors for their culling
|
||||
/// boxes on the first hover only: the next hovers use the boxes the paths keep.
|
||||
#[test]
|
||||
fn hovers_past_many_paths_read_their_anchors_once() {
|
||||
use vectorcraft_geom::anchors::measured_control_anchors;
|
||||
let mut d = Document::new(1000.0, 1000.0);
|
||||
let l = d.layers[0].id;
|
||||
for i in 0..100 {
|
||||
let n = square(&mut d, (i % 10) as f64 * 60.0, (i / 10) as f64 * 60.0);
|
||||
d.insert(Some(l), 0, n).unwrap();
|
||||
}
|
||||
let empty = Point::new(900.0, 900.0);
|
||||
let before = measured_control_anchors();
|
||||
assert!(hit_test(&d, empty, HitOptions::default()).is_none());
|
||||
let first = measured_control_anchors() - before;
|
||||
assert!(first >= 400, "the first hover reads every square's anchors: {first}");
|
||||
for _ in 0..3 {
|
||||
assert!(hit_test(&d, empty, HitOptions::default()).is_none());
|
||||
}
|
||||
assert_eq!(measured_control_anchors() - before, first, "later hovers read no anchor");
|
||||
assert!(hit_at(&d, 25.0, 25.0, HitOptions::default()).is_some(), "a square is still hit");
|
||||
}
|
||||
@@ -82,6 +82,7 @@ impl Paths {
|
||||
/// isn't in the table or it, or a node it is in, was removed.
|
||||
pub(crate) fn get(&self, id: &NodeId) -> Option<Option<Vec<usize>>> {
|
||||
let e = (*self.table.ids.get(id)?)?;
|
||||
note_path_copy();
|
||||
let mut path = Vec::new();
|
||||
let mut cur = e;
|
||||
// Each step goes to a parent entry, made before its children: at most `at.len()` steps.
|
||||
@@ -96,6 +97,29 @@ impl Paths {
|
||||
}
|
||||
Some(None)
|
||||
}
|
||||
/// The node with `id` in `layers` at the place the table has for it, found without copying its index path: `None`
|
||||
/// when the table does not have one place for `id`, its path is deeper than [`NODE_IN_DEPTH`], or the node there
|
||||
/// does not have the id (the tree changed). The caller then looks it up as [`crate::Document::index_path`] does.
|
||||
pub(crate) fn node_in<'a>(&self, layers: &'a [Arc<Node>], id: NodeId) -> Option<&'a Node> {
|
||||
let mut cur = (*self.table.ids.get(&id)?)?;
|
||||
let mut steps = [0u32; NODE_IN_DEPTH];
|
||||
let mut depth = 0;
|
||||
loop {
|
||||
let &(parent, i) = self.table.at.get(cur as usize)?;
|
||||
*steps.get_mut(depth)? = self.shifted(parent, i)?;
|
||||
depth += 1;
|
||||
if parent == u32::MAX {
|
||||
break;
|
||||
}
|
||||
cur = parent;
|
||||
}
|
||||
let mut path = steps[..depth].iter().rev();
|
||||
let mut node: &Node = layers.get(*path.next()? as usize)?;
|
||||
for &i in path {
|
||||
node = node.children()?.get(i as usize)?;
|
||||
}
|
||||
(node.id == id).then_some(node)
|
||||
}
|
||||
/// Where the table has `id` as it was built: its parent's entry and its index among its
|
||||
/// siblings then; `None` when the id isn't in the table or appears more than once.
|
||||
pub(crate) fn table_place(&self, id: &NodeId) -> Option<(u32, u32)> {
|
||||
@@ -170,6 +194,25 @@ pub(crate) fn note_path_lookup() {
|
||||
PATH_LOOKUPS.set(PATH_LOOKUPS.get().saturating_add(1));
|
||||
}
|
||||
|
||||
/// The deepest index path [`Paths::node_in`] follows without copying it.
|
||||
const NODE_IN_DEPTH: usize = 32;
|
||||
|
||||
thread_local! {
|
||||
/// [`path_copies`] of this thread.
|
||||
static PATH_COPIES: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// How many index paths the lookup cache has copied out on this thread, one for each [`crate::Document::index_path`]
|
||||
/// that it answered. [`crate::Document::node`] reads the node from the cache without one.
|
||||
pub fn path_copies() -> u64 {
|
||||
PATH_COPIES.get()
|
||||
}
|
||||
|
||||
/// Adds one to [`path_copies`].
|
||||
fn note_path_copy() {
|
||||
PATH_COPIES.set(PATH_COPIES.get().saturating_add(1));
|
||||
}
|
||||
|
||||
/// The cache, shared by clones of a document (each checks every path it uses against its own tree),
|
||||
/// the lookups that missed it, and the nodes removed from the tree since it was built.
|
||||
#[derive(Default)]
|
||||
|
||||
@@ -308,16 +308,8 @@ fn resolve_kids(
|
||||
layout: &mut dyn FnMut(&mut TextObject),
|
||||
changed: &mut Vec<NodeId>,
|
||||
) -> Vec<(usize, Arc<Node>)> {
|
||||
let mut by_id: Option<HashMap<NodeId, &Arc<Node>>> = None;
|
||||
let mut out = vec![];
|
||||
for (i, c) in kids.iter().enumerate() {
|
||||
let o = old.and_then(|old| match old.get(i) {
|
||||
Some(b) if b.id == c.id => Some(b),
|
||||
_ => by_id.get_or_insert_with(|| old.iter().map(|b| (b.id, b)).collect()).get(&c.id).copied(),
|
||||
});
|
||||
if o.is_some_and(|o| Arc::ptr_eq(o, c)) {
|
||||
continue;
|
||||
}
|
||||
for (i, c, o) in crate::changed_nodes(old.unwrap_or_default(), kids) {
|
||||
let mut c = c.clone();
|
||||
if resolve_since(o.map(|o| &**o), &mut c, bounds, layout, changed) {
|
||||
out.push((i, c));
|
||||
|
||||
@@ -24,7 +24,7 @@ mod halftone_radii;
|
||||
pub mod hit;
|
||||
mod id_index;
|
||||
pub mod image_quad;
|
||||
pub use id_index::{path_lookups, tree_walks};
|
||||
pub use id_index::{path_copies, path_lookups, tree_walks};
|
||||
pub mod inks;
|
||||
mod inline;
|
||||
pub mod intertwine;
|
||||
@@ -116,6 +116,7 @@ pub use live_paint::{GapOptions, GapSize};
|
||||
pub use metadata::{CopyrightStatus, DocMetadata};
|
||||
pub use node::Knockout;
|
||||
pub use node::Scaling;
|
||||
pub use node::changed_nodes;
|
||||
pub use node::{Extras, ExtrasMut, ImageObject, LAYER_COLORS, LayerColor, LiveShape, Node, NodeExtras, NodeId, NodeKind, OpacityMask};
|
||||
pub use node::{ForeignAttribute, ImageMap, MAX_SVG_SCRIPTS, MAX_TAG_TEXT, MAX_TAGS, ObjectAttributes, ObjectTag, SVG_EVENTS};
|
||||
pub use orient::OrientedBox;
|
||||
|
||||
@@ -15,6 +15,7 @@ use crate::symbols::{SYMBOL_SQUARE, SymbolBoxes};
|
||||
use crate::text::TextObject;
|
||||
|
||||
mod attributes;
|
||||
mod changed;
|
||||
mod clip;
|
||||
mod extras;
|
||||
mod ids;
|
||||
@@ -25,6 +26,9 @@ mod ops;
|
||||
mod wire;
|
||||
|
||||
pub use attributes::{ForeignAttribute, ImageMap, MAX_SVG_SCRIPTS, MAX_TAG_TEXT, MAX_TAGS, ObjectAttributes, ObjectTag, SVG_EVENTS};
|
||||
#[cfg(test)]
|
||||
pub(crate) use changed::COUNTERPART_LOOKUPS;
|
||||
pub use changed::changed_nodes;
|
||||
pub use clip::{ClipPaint, Uniter};
|
||||
pub use extras::{Extras, ExtrasMut, NodeExtras};
|
||||
pub use ids::{LAYER_COLORS, LayerColor, NodeId};
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
use super::{Arc, Node, NodeId};
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// Tests: how many nodes [`changed_nodes`] looked up a counterpart for on this thread.
|
||||
pub(crate) static COUNTERPART_LOOKUPS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// The nodes of `after` that are not the same nodes as their counterparts in `before` (the same
|
||||
/// list before an edit), with their positions in `after`. A node's counterpart is the node at the
|
||||
/// same position when it has the same id, else the node in `before` with its id, else `None` (the
|
||||
/// node is new). A node that is the same node as the one at its position in `before` is skipped
|
||||
/// without reading it, so a list of many unchanged nodes costs one pointer comparison per node.
|
||||
pub fn changed_nodes<'a>(before: &'a [Arc<Node>], after: &'a [Arc<Node>]) -> impl Iterator<Item = (usize, &'a Arc<Node>, Option<&'a Arc<Node>>)> {
|
||||
let mut by_id: Option<HashMap<NodeId, &'a Arc<Node>>> = None;
|
||||
after.iter().enumerate().filter_map(move |(i, a)| {
|
||||
if before.get(i).is_some_and(|b| Arc::ptr_eq(b, a)) {
|
||||
return None;
|
||||
}
|
||||
#[cfg(test)]
|
||||
COUNTERPART_LOOKUPS.with(|c| c.set(c.get() + 1));
|
||||
let b = match before.get(i) {
|
||||
Some(b) if b.id == a.id => Some(b),
|
||||
_ => by_id.get_or_insert_with(|| before.iter().map(|b| (b.id, b)).collect()).get(&a.id).copied(),
|
||||
};
|
||||
if b.is_some_and(|b| Arc::ptr_eq(b, a)) {
|
||||
return None;
|
||||
}
|
||||
Some((i, a, b))
|
||||
})
|
||||
}
|
||||
@@ -947,3 +947,37 @@ fn try_walk_ends_at_the_break() {
|
||||
assert_eq!(flow, ControlFlow::Break(NodeId(3)));
|
||||
assert_eq!(seen, [NodeId(1), NodeId(2), NodeId(3)]);
|
||||
}
|
||||
|
||||
/// After an edit of one node in a list of 1,000, `changed_nodes` gives that node and a new one
|
||||
/// with their counterparts, and looks a counterpart up for those two only: the 999 nodes that are
|
||||
/// the same nodes in the same places are passed over by their pointers.
|
||||
#[test]
|
||||
fn changed_nodes_looks_up_only_the_nodes_that_changed() {
|
||||
let leaf = |id| Arc::new(Node::group(NodeId(id), vec![]));
|
||||
let before: Vec<Arc<Node>> = (0..1000).map(leaf).collect();
|
||||
let mut after = before.clone();
|
||||
let mut edited = (*after[500]).clone();
|
||||
edited.name = Some("edited".into());
|
||||
after[500] = Arc::new(edited);
|
||||
after.push(leaf(5000));
|
||||
COUNTERPART_LOOKUPS.with(|c| c.set(0));
|
||||
let changed: Vec<_> = changed_nodes(&before, &after).map(|(i, a, b)| (i, a.id, b.map(|b| b.id))).collect();
|
||||
assert_eq!(changed, [(500, NodeId(500), Some(NodeId(500))), (1000, NodeId(5000), None)]);
|
||||
assert_eq!(COUNTERPART_LOOKUPS.with(|c| c.get()), 2);
|
||||
}
|
||||
|
||||
/// A node that moved to another place in the list is paired with itself by its id and left out
|
||||
/// when it is the same node; a changed node that moved is paired with its old node, and a node
|
||||
/// that is gone from the list gives nothing.
|
||||
#[test]
|
||||
fn changed_nodes_pairs_moved_nodes_by_id() {
|
||||
let leaf = |id| Arc::new(Node::group(NodeId(id), vec![]));
|
||||
let before = vec![leaf(1), leaf(2), leaf(3), leaf(4)];
|
||||
let mut edited = (*before[0]).clone();
|
||||
edited.locked = true;
|
||||
let after = vec![Arc::clone(&before[2]), Arc::clone(&before[1]), Arc::new(edited)];
|
||||
let changed: Vec<_> = changed_nodes(&before, &after).map(|(i, a, b)| (i, a.id, b.map(|b| b.id))).collect();
|
||||
assert_eq!(changed, [(2, NodeId(1), Some(NodeId(1)))]);
|
||||
assert!(changed_nodes(&[], &after).map(|(_, _, b)| b).all(|b| b.is_none()), "every node is new against an empty list");
|
||||
assert_eq!(changed_nodes(&[], &after).count(), 3);
|
||||
}
|
||||
@@ -579,3 +579,32 @@ fn nearest_finder_reads_one_path_per_object() {
|
||||
assert_eq!(path_lookups() - lookups, 0, "lookups by id");
|
||||
assert_eq!(tree_walks() - walks, 0, "walks of the tree");
|
||||
}
|
||||
|
||||
/// `Document::node` reads a node from the lookup cache without copying its index path, in nested groups and after
|
||||
/// objects were removed, and finds what a walk finds: 10,000 objects looked up one at a time copy no path.
|
||||
#[test]
|
||||
fn node_lookups_copy_no_index_path() {
|
||||
let (mut d, ids) = squares(10_000);
|
||||
let layer = d.layers[0].id;
|
||||
let mut nested = vec![];
|
||||
for g in 0..50 {
|
||||
let kids: Vec<Arc<Node>> = (0..4)
|
||||
.map(|_| {
|
||||
let id = d.alloc_id();
|
||||
nested.push(id);
|
||||
Arc::new(Node::path(id, shapes::rectangle(Rect::new(0.0, 0.0, 5.0, 5.0)), Appearance::default_art()))
|
||||
})
|
||||
.collect();
|
||||
let (gid, inner) = (d.alloc_id(), d.alloc_id());
|
||||
d.insert(Some(layer), g, Node::group(gid, vec![Arc::new(Node::group(inner, kids))])).unwrap();
|
||||
}
|
||||
d.remove_many(&ids[..100]).unwrap();
|
||||
d.node(layer);
|
||||
let copies = path_copies();
|
||||
let found = ids[100..].iter().chain(&nested).filter(|id| d.node(**id).is_some_and(|n| n.id == **id)).count();
|
||||
assert_eq!(found, ids.len() - 100 + nested.len());
|
||||
assert_eq!(path_copies() - copies, 0, "index paths copied");
|
||||
assert!(ids[..100].iter().all(|id| d.node(*id).is_none()), "removed objects are not found");
|
||||
agree(&d, &ids[..200], "after remove_many");
|
||||
agree(&d, &nested, "nested");
|
||||
}
|
||||
@@ -1780,6 +1780,44 @@ fn perspective_projects_the_masks_in_a_symbols_art() {
|
||||
assert_eq!(mask, path, "and so is its mask");
|
||||
}
|
||||
|
||||
/// The images in the art of a symbol instance drawn through a projection have their corners where
|
||||
/// the projection takes them, beside a path, in a group and in the art of a linked mask, and an
|
||||
/// image's own linked mask is projected with it.
|
||||
#[test]
|
||||
fn a_projection_puts_the_corners_of_the_images_in_a_symbols_art_where_it_takes_them() {
|
||||
let masked = masked_by(white_square(22), image_node(23), true);
|
||||
let art = Node::group(NodeId(20), vec![Arc::new(image_node(21)), Arc::new(Node::group(NodeId(24), vec![Arc::new(masked)]))]);
|
||||
// An image with a linked mask of its own, whose path has a linked mask too.
|
||||
let inner = masked_by(white_square(32), white_square(33), true);
|
||||
let own = Node::group(NodeId(30), vec![Arc::new(masked_by(image_node(31), inner, true))]);
|
||||
let at = vectorcraft_doc::PerspectiveAttachment { projection: Some([1.0, 0.2, 3.0, 0.1, 1.0, 2.0, 0.01, 0.02, 1.0]), ..Default::default() };
|
||||
let h = at.homography().unwrap();
|
||||
let mut instance = Node::new(NodeId(2), NodeKind::SymbolInstance { symbol: "t".into(), xf: vectorcraft_geom::Affine::IDENTITY });
|
||||
instance.extras_mut().perspective = Some(Box::new(at.clone()));
|
||||
let out = crate::reshape::reshape(None, &instance, Some(&own)).unwrap();
|
||||
let mut masks = vec![];
|
||||
out.walk(&mut |c| masks.extend(c.image_corners().and(c.extras().mask.as_deref()).map(|m| m.art.clone())));
|
||||
let [mask] = masks.as_slice() else { panic!("one masked image: {out:?}") };
|
||||
assert!(mask.path_data() != white_square(32).path_data(), "the image's mask is projected");
|
||||
let inner = mask.extras().mask.as_deref().map(|m| m.art.path_data().cloned());
|
||||
assert_eq!(inner, Some(mask.path_data().cloned()), "and so is the mask on that mask's path");
|
||||
let mut instance = Node::new(NodeId(1), NodeKind::SymbolInstance { symbol: "s".into(), xf: vectorcraft_geom::Affine::IDENTITY });
|
||||
instance.extras_mut().perspective = Some(Box::new(at));
|
||||
let out = crate::reshape::reshape(None, &instance, Some(&art)).unwrap();
|
||||
let want = [(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)].map(|(x, y)| h.apply(vectorcraft_geom::Point::new(x, y)).unwrap());
|
||||
let mut images = vec![];
|
||||
out.walk(&mut |c| {
|
||||
images.extend(c.image_corners());
|
||||
images.extend(c.extras().mask.as_deref().and_then(|m| m.art.image_corners()));
|
||||
});
|
||||
assert_eq!(images.len(), 2, "{out:?}");
|
||||
for q in images {
|
||||
for (got, want) in q.iter().zip(want) {
|
||||
assert!(got.distance(want) < 1e-9, "{q:?} against {want:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A group with `effect` holding `n` vertical then `n` horizontal bars, 2 wide on a 4-unit
|
||||
/// pitch, each crossing every bar of the other direction: n² crossings.
|
||||
fn crossing_bars(n: usize, effect: &str) -> Node {
|
||||
|
||||
@@ -1544,11 +1544,40 @@ pub(crate) fn own_effects_art(doc: Option<&Document>, n: &Node) -> Option<Node>
|
||||
/// follow it. The type and live objects in the art of those masks are outlined and evaluated
|
||||
/// first ([`outlined_members`], with the symbols of `doc`).
|
||||
fn project_leaves(art: &mut Node, h: &vectorcraft_geom::Homography, doc: Option<&Document>) {
|
||||
project_art(art, h, doc, false);
|
||||
}
|
||||
|
||||
/// [`project_leaves`], the linked opacity mask of `art` itself included when `own`.
|
||||
fn project_art(art: &mut Node, h: &vectorcraft_geom::Homography, doc: Option<&Document>, own: bool) {
|
||||
project_paths(art, h);
|
||||
each_linked_mask_mut(art, false, 0, &mut |m| {
|
||||
each_linked_mask_mut(art, own, 0, &mut |m| {
|
||||
*m = outlined_mask_art(doc, m);
|
||||
project_paths(m, h);
|
||||
project_image_masks(m, h, doc);
|
||||
});
|
||||
project_image_masks(art, h, doc);
|
||||
}
|
||||
|
||||
/// The art of the linked opacity masks of the images under `art` (`art` itself, and in groups and
|
||||
/// layers, as [`project_images`] reaches them) projected through `h` as [`project_leaves`]
|
||||
/// projects art, the linked mask of that art's own root included, so that each mask stays on the
|
||||
/// object it masks. Unlinked masks stay where they are.
|
||||
fn project_image_masks(art: &mut Node, h: &vectorcraft_geom::Homography, doc: Option<&Document>) {
|
||||
match &mut art.kind {
|
||||
NodeKind::Image(_) => {
|
||||
if let Some(m) = art.extras_if_any().and_then(|e| e.mask.as_mut()).filter(|m| m.linked) {
|
||||
let a = Arc::make_mut(&mut m.art);
|
||||
*a = outlined_mask_art(doc, a);
|
||||
project_art(a, h, doc, true);
|
||||
}
|
||||
}
|
||||
NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => {
|
||||
for c in children.iter_mut() {
|
||||
project_image_masks(Arc::make_mut(c), h, doc);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// `art`, the art of an opacity mask, with type and live objects in it outlined and evaluated
|
||||
@@ -1584,6 +1613,27 @@ fn project_paths(art: &mut Node, h: &vectorcraft_geom::Homography) {
|
||||
_ => {}
|
||||
}
|
||||
});
|
||||
project_images(art, h);
|
||||
}
|
||||
|
||||
/// Place the corners of every image under `art` (in groups and layers, as [`for_each_leaf`] reaches
|
||||
/// paths) where the projective map `h` takes them, so that its pixels are drawn in perspective
|
||||
/// between them ([`Node::set_image_corners`]). An image with a corner that `h` sends past its
|
||||
/// horizon keeps its place, as the points of a path there do.
|
||||
fn project_images(n: &mut Node, h: &vectorcraft_geom::Homography) {
|
||||
match &mut n.kind {
|
||||
NodeKind::Image(_) => {
|
||||
if let Some([Some(a), Some(b), Some(c), Some(d)]) = n.image_corners().map(|q| q.map(|p| h.apply(p))) {
|
||||
let _ = n.set_image_corners([a, b, c, d]);
|
||||
}
|
||||
}
|
||||
NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => {
|
||||
for c in children.iter_mut() {
|
||||
project_images(Arc::make_mut(c), h);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// The visible geometry effects of `n`'s own effect list, in order.
|
||||
|
||||
+324
-25
@@ -1180,8 +1180,11 @@ impl Placed {
|
||||
}
|
||||
}
|
||||
|
||||
/// The most pairs of faces [`local_order`] compares, and the most [`cut_stroke_faces`] compares;
|
||||
/// the pairs they have not reached by then keep the order of their depths.
|
||||
/// The most pairs of faces [`local_order`] compares, together with the steps it takes to break
|
||||
/// rings of them ([`drawn_in_pairs_order`]), and the most pairs [`cut_stroke_faces`] compares. A
|
||||
/// pair not compared by then adds no constraint on the order (the pairs that were compared can
|
||||
/// still move its faces), and once the steps run out the first face left by depth goes next only
|
||||
/// when no face can.
|
||||
const MAX_LOCAL_CHECKS: usize = 4_000_000;
|
||||
|
||||
/// The polygon of `f` and the sign of its turns, when `f` is a face turned toward the viewer other
|
||||
@@ -1412,11 +1415,11 @@ fn half(p: &[Point], values: &[f64], sign: f64) -> Vec<Point> {
|
||||
/// their depths where they overlap: the face nearer the viewer there goes after the other. A fill
|
||||
/// wall and a face of the same shape's covering stroke ([`Paints::Stroke`]) keep their order. Each
|
||||
/// face otherwise keeps its place in `order`, so a fill wall in the gap between two dashes stays
|
||||
/// where its depth puts it. A cycle of such pairs is broken at the face that comes first in `order`.
|
||||
/// where its depth puts it. A cycle of such pairs is broken at one of its own faces
|
||||
/// ([`drawn_in_pairs_order`]).
|
||||
/// A face drawn last (a planar end turned toward the viewer, at depth `f64::MAX`) keeps its place:
|
||||
/// no face moves across it. Otherwise `order` as it is.
|
||||
fn local_order(faces: &[Placed], order: Vec<usize>) -> Vec<usize> {
|
||||
use std::cmp::Reverse;
|
||||
// The faces of each shape that take part, from left to right for a sweep along x.
|
||||
let mut shapes: Vec<Vec<usize>> = vec![];
|
||||
for (k, f) in faces.iter().enumerate() {
|
||||
@@ -1428,7 +1431,7 @@ fn local_order(faces: &[Placed], order: Vec<usize>) -> Vec<usize> {
|
||||
}
|
||||
shapes[f.member].push(k);
|
||||
}
|
||||
if !shapes.iter().any(|list| list.iter().any(|&k| faces[k].paints != Paints::Fill)) {
|
||||
if !shapes.iter().any(|list| list.iter().any(|&k| faces[k].paints != Paints::Fill)) || u32::try_from(faces.len()).is_err() {
|
||||
return order;
|
||||
}
|
||||
for list in &mut shapes {
|
||||
@@ -1471,9 +1474,9 @@ fn local_order(faces: &[Placed], order: Vec<usize>) -> Vec<usize> {
|
||||
// faces with a polygon and a plane that overlap goes in the order of their depths there.
|
||||
let mut sweep: Vec<usize> = (0..faces.len()).filter(|&k| faces[k].outline.len() >= 3 && faces[k].plane.is_some()).collect();
|
||||
sweep.sort_by(|&a, &b| faces[a].bounds.x0.total_cmp(&faces[b].bounds.x0));
|
||||
// For each face, the faces drawn after it, and for each, how many go before it.
|
||||
let mut after: Vec<Vec<usize>> = vec![vec![]; faces.len()];
|
||||
let mut waits = vec![0usize; faces.len()];
|
||||
// Each pair in its order: a face, and a face drawn after it (as `u32`: there are fewer faces
|
||||
// than that, which is checked above).
|
||||
let mut pairs: Vec<(u32, u32)> = vec![];
|
||||
'pairs: for (i, &k) in sweep.iter().enumerate() {
|
||||
let a = &faces[k];
|
||||
for &j in sweep.iter().skip(i + 1).take_while(|&&j| faces[j].bounds.x0 < a.bounds.x1) {
|
||||
@@ -1491,38 +1494,117 @@ fn local_order(faces: &[Placed], order: Vec<usize>) -> Vec<usize> {
|
||||
let Some(a_nearer) = nearer_where_overlapping(a, b) else { continue };
|
||||
a_nearer
|
||||
};
|
||||
let (back, front) = if a_later { (j, k) } else { (k, j) };
|
||||
after[back].push(front);
|
||||
waits[front] += 1;
|
||||
pairs.push(if a_later { (j as u32, k as u32) } else { (k as u32, j as u32) });
|
||||
}
|
||||
}
|
||||
// Each step draws the face that comes first in `order` of those whose faces before are drawn.
|
||||
// Breaking rings has what is left of the limit.
|
||||
let last: Vec<bool> = faces.iter().map(|f| f.depth >= f64::MAX).collect();
|
||||
let mut room = MAX_LOCAL_CHECKS.saturating_sub(checks);
|
||||
drawn_in_pairs_order(order, &position, &last, pairs, &mut room)
|
||||
}
|
||||
|
||||
/// `order` with each face after the faces that go before it: each of `pairs` is a face and a face
|
||||
/// drawn after it, `position` is each face's place in `order`, and `last` says of each face
|
||||
/// whether it is drawn last. Each step draws the face that comes first in `order` of those whose
|
||||
/// faces before are drawn. A face drawn last goes only after every face before it in `order`, so
|
||||
/// a face before it never waits for it or for a face after it: those pairs, with the face drawn
|
||||
/// last itself or with a face that follows it, are drawn the wrong way round.
|
||||
///
|
||||
/// When no face can go next, some of the faces left go before each other in a ring, or wait for a
|
||||
/// face drawn last or one that follows it. The faces that go before the first face left in `order`
|
||||
/// are followed back, among the faces that come before the next face drawn last, to the first
|
||||
/// group found that waits for no other of them ([`RingFinder::behind`]): a ring, or one face. That
|
||||
/// group gives up its face that comes first in `order`. So when the first face left is in the
|
||||
/// group, it goes next, as it would with no ring looked for; when it only waits for the group, a
|
||||
/// face of the group goes instead, and the only other pairs drawn the wrong way round are pairs of
|
||||
/// a ring.
|
||||
///
|
||||
/// Every face and pair looked at takes one from `room`. The search is kept from one stop to the
|
||||
/// next and goes on from where it stopped, and a face that is drawn is dropped from a list the
|
||||
/// next time the list is looked at, so rings of a few faces take a few steps a face whether they
|
||||
/// stand apart, all lie behind one face or lie one behind the other. Two costs are not in
|
||||
/// proportion to the faces. A ring that is still a ring after it gives up a face is walked again
|
||||
/// from the face the search reached it by, so a large ring can cost about its pairs for each face
|
||||
/// it gives up: the square of its faces, even when each waits for few others (3,200 faces with
|
||||
/// four pairs each at random take about 3,000,000 steps). And a face at or
|
||||
/// after the next face drawn last is passed over again each time a face that waits for it is
|
||||
/// looked at. Once `room` runs out the first face left in `order` goes next, ring or not.
|
||||
/// A first face left that waits only for the next face drawn last or faces after it goes next
|
||||
/// with no search, at no cost.
|
||||
///
|
||||
/// An `order` and `position` that do not agree, or a pair of a face that is not in them, give
|
||||
/// `order` back.
|
||||
///
|
||||
/// The pairs come at 8 bytes each and are dropped once the lists of the faces after each face
|
||||
/// are made, 4 bytes a pair; the lists of the faces before each face, as many again, are made
|
||||
/// when a ring is first looked for, a step a pair not taken from `room`, and only when the room
|
||||
/// left is at least a quarter of the pairs: with less, no ring is looked for and the first face
|
||||
/// left goes next. So a solid whose comparing of pairs leaves less than a quarter of its pairs
|
||||
/// of the limit breaks its rings as before rings were looked for.
|
||||
fn drawn_in_pairs_order(order: Vec<usize>, position: &[usize], last: &[bool], pairs: Vec<(u32, u32)>, room: &mut usize) -> Vec<usize> {
|
||||
use std::cmp::Reverse;
|
||||
let n = order.len();
|
||||
// `order` holds each face once when each face's place in it is the place `position` gives.
|
||||
let agree = position.len() == n && last.len() == n && order.iter().enumerate().all(|(at, &k)| position.get(k) == Some(&at));
|
||||
if !agree || u32::try_from(pairs.len()).is_err() || pairs.iter().any(|&(back, front)| back as usize >= n || front as usize >= n) {
|
||||
return order;
|
||||
}
|
||||
// For each face, how many faces not drawn yet go before it, and the faces drawn after it.
|
||||
let mut waits = vec![0usize; n];
|
||||
for &(_, front) in &pairs {
|
||||
waits[front as usize] += 1;
|
||||
}
|
||||
let after = Lists::from_pairs(n, pairs.iter().map(|&(back, front)| (back as usize, front as usize)));
|
||||
drop(pairs);
|
||||
let mut ready: std::collections::BinaryHeap<Reverse<(usize, usize)>> =
|
||||
(0..faces.len()).filter(|&k| waits[k] == 0).map(|k| Reverse((position[k], k))).collect();
|
||||
(0..n).filter(|&k| waits[k] == 0).map(|k| Reverse((position[k], k))).collect();
|
||||
// The faces drawn last, in `order`: each goes only after every face before it in `order`.
|
||||
let last: Vec<usize> = order.iter().copied().filter(|&k| faces[k].depth >= f64::MAX).collect();
|
||||
let lasts: Vec<usize> = order.iter().copied().filter(|&k| last[k]).collect();
|
||||
let mut next_last = 0usize;
|
||||
let mut drawn = vec![false; faces.len()];
|
||||
let mut out = Vec::with_capacity(order.len());
|
||||
let mut drawn = vec![false; n];
|
||||
let mut out = Vec::with_capacity(n);
|
||||
let mut first = 0usize;
|
||||
while out.len() < order.len() {
|
||||
while last.get(next_last).is_some_and(|&k| drawn[k]) {
|
||||
let mut rings: Option<RingFinder> = None;
|
||||
// For each face, how many faces not drawn yet go before it among the first `counted` of
|
||||
// `order`, which keeps up with the next face drawn last.
|
||||
let mut early = vec![0u32; n];
|
||||
let mut counted = 0usize;
|
||||
while out.len() < n {
|
||||
while lasts.get(next_last).is_some_and(|&k| drawn[k]) {
|
||||
next_last += 1;
|
||||
}
|
||||
let limit = last.get(next_last).map_or(usize::MAX, |&k| position[k]);
|
||||
let limit = lasts.get(next_last).map_or(usize::MAX, |&k| position[k]);
|
||||
while counted < limit.min(n) {
|
||||
if let Some(&back) = order.get(counted).filter(|&&back| !drawn[back]) {
|
||||
for &j in after.list(back) {
|
||||
early[j as usize] += 1;
|
||||
}
|
||||
}
|
||||
counted += 1;
|
||||
}
|
||||
let k = match ready.peek() {
|
||||
Some(&Reverse((at, k))) if at < limit => {
|
||||
ready.pop();
|
||||
k
|
||||
}
|
||||
_ => {
|
||||
// A cycle, or the faces left to draw before a face drawn last wait for faces after
|
||||
// it: the first face in `order` not drawn yet goes next.
|
||||
while order.get(first).is_some_and(|&k| drawn[k]) {
|
||||
first += 1;
|
||||
}
|
||||
let Some(&k) = order.get(first) else { break };
|
||||
k
|
||||
let Some(&next) = order.get(first) else { break };
|
||||
// The face drawn last goes in its turn, and so does a face that waits only for it or
|
||||
// faces after it: no face it waits for can go first. Any other face waits for a
|
||||
// face before the face drawn last: the group behind it gives up a face, while there
|
||||
// is room to look for one. The lists of the faces before each face take a step a
|
||||
// pair to make, which is not taken from `room`: they are made only when the room
|
||||
// left is at least a quarter of the pairs, so making them costs no more than four
|
||||
// times the room left.
|
||||
let mut released = None;
|
||||
let room_for_lists = rings.is_some() || room.saturating_mul(4) >= after.faces.len();
|
||||
if *room > 0 && position[next] < limit && early[next] > 0 && room_for_lists {
|
||||
released = rings.get_or_insert_with(|| RingFinder::new(&after)).behind(next, &drawn, position, limit, room);
|
||||
}
|
||||
released.unwrap_or(next)
|
||||
}
|
||||
};
|
||||
if drawn[k] {
|
||||
@@ -1530,8 +1612,13 @@ fn local_order(faces: &[Placed], order: Vec<usize>) -> Vec<usize> {
|
||||
}
|
||||
drawn[k] = true;
|
||||
out.push(k);
|
||||
for &j in &after[k] {
|
||||
let was_counted = position[k] < counted;
|
||||
for &j in after.list(k) {
|
||||
let j = j as usize;
|
||||
waits[j] = waits[j].saturating_sub(1);
|
||||
if was_counted {
|
||||
early[j] = early[j].saturating_sub(1);
|
||||
}
|
||||
if waits[j] == 0 && !drawn[j] {
|
||||
ready.push(Reverse((position[j], j)));
|
||||
}
|
||||
@@ -1540,6 +1627,217 @@ fn local_order(faces: &[Placed], order: Vec<usize>) -> Vec<usize> {
|
||||
out
|
||||
}
|
||||
|
||||
/// A list of faces for each of some faces, all in one array: the faces after each face, or the
|
||||
/// faces before it.
|
||||
struct Lists {
|
||||
/// The list of face `k` is `faces[starts[k]..starts[k + 1]]`.
|
||||
starts: Vec<u32>,
|
||||
faces: Vec<u32>,
|
||||
}
|
||||
|
||||
impl Lists {
|
||||
/// For each of `n` faces, the second faces of the `pairs` it is first in, in the order of
|
||||
/// `pairs`. There are fewer than 2^32 faces and pairs ([`drawn_in_pairs_order`] checks this);
|
||||
/// a pair with a face that is not one of the `n` is left out.
|
||||
fn from_pairs(n: usize, pairs: impl Iterator<Item = (usize, usize)> + Clone) -> Self {
|
||||
let pairs = pairs.filter(move |&(first, second)| first < n && second < n);
|
||||
let mut starts = vec![0u32; n + 1];
|
||||
for (first, _) in pairs.clone() {
|
||||
if let Some(count) = starts.get_mut(first + 1) {
|
||||
*count += 1;
|
||||
}
|
||||
}
|
||||
for k in 1..starts.len() {
|
||||
starts[k] += starts[k - 1];
|
||||
}
|
||||
let mut filled = starts.clone();
|
||||
let mut faces = vec![0u32; starts.last().map_or(0, |&end| end as usize)];
|
||||
for (first, second) in pairs {
|
||||
if let Some(at) = filled.get_mut(first) {
|
||||
if let Some(slot) = faces.get_mut(*at as usize) {
|
||||
*slot = second as u32;
|
||||
}
|
||||
*at += 1;
|
||||
}
|
||||
}
|
||||
Lists { starts, faces }
|
||||
}
|
||||
|
||||
/// The list of face `k`; none for a face that is not one of them.
|
||||
fn list(&self, k: usize) -> &[u32] {
|
||||
let (Some(&start), Some(&end)) = (self.starts.get(k), self.starts.get(k + 1)) else { return &[] };
|
||||
self.faces.get(start as usize..end as usize).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Each list's faces and the face it is the list of, as pairs.
|
||||
fn pairs(&self) -> impl Iterator<Item = (usize, usize)> + Clone + '_ {
|
||||
(0..self.starts.len().saturating_sub(1)).flat_map(move |k| self.list(k).iter().map(move |&j| (k, j as usize)))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// The entries of the lists of faces before each face that [`RingFinder`] has read, counted
|
||||
/// where they are read, for tests to hold the reading to the room.
|
||||
pub(super) static LIST_ENTRIES_READ: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// No place among the faces reached, in [`RingFinder`].
|
||||
const NONE: usize = usize::MAX;
|
||||
|
||||
/// Finds the ring behind a face for [`drawn_in_pairs_order`], and keeps its search from one stop to
|
||||
/// the next.
|
||||
///
|
||||
/// Every index it holds is in range: the faces of its lists are faces of the pairs
|
||||
/// [`drawn_in_pairs_order`] checked against the number of faces, which is the length of the
|
||||
/// `drawn` and `position` it is given, and the places it keeps are places in its own lists.
|
||||
struct RingFinder {
|
||||
/// For each face, the faces that go before it, lowest first.
|
||||
before: Lists,
|
||||
/// For each face, where its list in `before` now ends: the faces found drawn are dropped
|
||||
/// from it, and those left moved up.
|
||||
ends: Vec<u32>,
|
||||
/// For each face, its place in `reached`; [`NONE`] for a face not reached.
|
||||
marks: Vec<usize>,
|
||||
/// The faces reached, in the order reached. Every one is in a group not completed yet.
|
||||
reached: Vec<usize>,
|
||||
/// For each face reached, the earliest place in `reached` it leads back to.
|
||||
low: Vec<usize>,
|
||||
/// The path from the first face reached to the one being looked at.
|
||||
path: Vec<Step>,
|
||||
/// The `limit` the faces reached were reached under; `None` with none reached yet.
|
||||
limit: Option<usize>,
|
||||
}
|
||||
|
||||
/// A face on the path of [`RingFinder`]: its place in `reached`, and the entry of its list being
|
||||
/// looked at.
|
||||
struct Step {
|
||||
place: usize,
|
||||
entry: usize,
|
||||
}
|
||||
|
||||
impl RingFinder {
|
||||
/// A finder for the faces of `after`, the faces drawn after each face.
|
||||
fn new(after: &Lists) -> Self {
|
||||
let n = after.starts.len() - 1;
|
||||
let before = Lists::from_pairs(n, after.pairs().map(|(back, front)| (front, back)));
|
||||
let ends = before.starts.get(1..).unwrap_or_default().to_vec();
|
||||
RingFinder { before, ends, marks: vec![NONE; n], reached: vec![], low: vec![], path: vec![], limit: None }
|
||||
}
|
||||
|
||||
/// The face to draw next when `start`, the first face not `drawn`, whose `position` is before
|
||||
/// `limit`, waits for a face. Of the faces that are not drawn and come before `limit`, those
|
||||
/// that go before `start` are followed back to the first group found whose faces wait for no
|
||||
/// other such face: a ring of faces that go before each other, or one face. The answer is the
|
||||
/// face of that group with the lowest `position`. Every face and every pair looked at takes
|
||||
/// one from `room`; `None` when it runs out.
|
||||
///
|
||||
/// The faces are followed depth first, each face's faces before it lowest first, and the first
|
||||
/// strongly connected component completed is the group (Tarjan's algorithm, stopped there):
|
||||
/// it leads to no other component. The search is kept, less that group, and the next call
|
||||
/// goes on with it: the faces drawn since are the group's own and faces that waited for
|
||||
/// nothing else, and none of those is in a group with a face still on the path, so what the
|
||||
/// search knows of the faces left still holds. It starts afresh when `limit` moves, which
|
||||
/// brings in faces it passed over.
|
||||
fn behind(&mut self, start: usize, drawn: &[bool], position: &[usize], limit: usize, room: &mut usize) -> Option<usize> {
|
||||
if self.limit != Some(limit) {
|
||||
self.forget(0);
|
||||
self.limit = Some(limit);
|
||||
}
|
||||
// The end of the path may be drawn: faces that only waited for the last group.
|
||||
while let Some(place) = self.path.last().map(|step| step.place).filter(|&place| drawn[self.reached[place]]) {
|
||||
self.forget(place);
|
||||
}
|
||||
if self.reached.first() != Some(&start) {
|
||||
self.forget(0);
|
||||
if !self.reach(start, drawn, room) {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
while let Some(step) = self.path.last_mut() {
|
||||
if *room == 0 {
|
||||
return None;
|
||||
}
|
||||
*room -= 1;
|
||||
let place = step.place;
|
||||
let face = self.reached[place];
|
||||
if step.entry < self.ends[face] as usize {
|
||||
let earlier = self.before.faces[step.entry] as usize;
|
||||
if drawn[earlier] || position[earlier] >= limit {
|
||||
step.entry += 1;
|
||||
} else if self.marks[earlier] != NONE {
|
||||
self.low[place] = self.low[place].min(self.marks[earlier]);
|
||||
step.entry += 1;
|
||||
} else {
|
||||
// The entry is passed once the faces behind it are looked at.
|
||||
if !self.reach(earlier, drawn, room) {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
// Every face before this one is looked at: it ends a group when it leads no further
|
||||
// back than itself.
|
||||
let leads = self.low[place];
|
||||
if leads == place {
|
||||
let found = self.reached[place..].iter().copied().min_by_key(|&face| position[face]);
|
||||
// The face before it on the path keeps its entry for this one, to look at what is
|
||||
// left of the group next time.
|
||||
self.forget(place);
|
||||
return found;
|
||||
}
|
||||
self.path.pop();
|
||||
if let Some(parent) = self.path.last_mut() {
|
||||
self.low[parent.place] = self.low[parent.place].min(leads);
|
||||
parent.entry += 1;
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Adds `face` to the faces reached and to the end of the path, at the start of its list, with
|
||||
/// the faces now `drawn` dropped from the list: a step from `room` for each face the list held,
|
||||
/// taken before the list is read. `false`, with `room` emptied and nothing read, when the list
|
||||
/// is longer than the room left.
|
||||
fn reach(&mut self, face: usize, drawn: &[bool], room: &mut usize) -> bool {
|
||||
let (start, end) = (self.before.starts[face] as usize, self.ends[face] as usize);
|
||||
let Some(left) = room.checked_sub(end - start) else {
|
||||
*room = 0;
|
||||
return false;
|
||||
};
|
||||
*room = left;
|
||||
let mut kept = start;
|
||||
for entry in start..end {
|
||||
let earlier = self.before.faces[entry];
|
||||
#[cfg(test)]
|
||||
LIST_ENTRIES_READ.with(|read| read.set(read.get() + 1));
|
||||
if !drawn[earlier as usize] {
|
||||
self.before.faces[kept] = earlier;
|
||||
kept += 1;
|
||||
}
|
||||
}
|
||||
// `kept` is no more than the end it replaces.
|
||||
self.ends[face] = kept as u32;
|
||||
let place = self.reached.len();
|
||||
self.marks[face] = place;
|
||||
self.path.push(Step { place, entry: start });
|
||||
self.low.push(place);
|
||||
self.reached.push(face);
|
||||
true
|
||||
}
|
||||
|
||||
/// Takes out the faces reached from `place` on, and their part of the path.
|
||||
fn forget(&mut self, place: usize) {
|
||||
for face in self.reached.drain(place.min(self.reached.len())..) {
|
||||
self.marks[face] = NONE;
|
||||
}
|
||||
self.low.truncate(place);
|
||||
while self.path.last().is_some_and(|step| step.place >= place) {
|
||||
self.path.pop();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether face `a` is nearer the viewer than face `b` where their polygons overlap on the drawing,
|
||||
/// measured at the middle of the overlap. `None` when they do not overlap, when either polygon is
|
||||
/// not convex, or when they are at the same depth there.
|
||||
@@ -1673,7 +1971,8 @@ fn draw_order(faces: &[Placed], sealed: bool) -> Vec<usize> {
|
||||
/// of overlapping faces with a convex polygon and a plane goes in the order of its depths there,
|
||||
/// the face nearer the viewer after the other ([`local_order`]), and each step draws the face that
|
||||
/// comes first in the given order of those whose faces before are drawn, so a face without a plane
|
||||
/// or a convex polygon can also move. Otherwise the order given.
|
||||
/// or a convex polygon can also move. Faces that lie in front of one another in a ring give up one
|
||||
/// of the ring's own faces ([`drawn_in_pairs_order`]). Otherwise the order given.
|
||||
pub(crate) fn surface_order<'a>(faces: impl IntoIterator<Item = (&'a [Point], Option<DepthPlane>, f64)>) -> Vec<usize> {
|
||||
let placed: Vec<Placed> = faces
|
||||
.into_iter()
|
||||
|
||||
@@ -933,10 +933,10 @@ fn local_order_puts_overlapping_fill_walls_and_stroke_faces_in_depth_order() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A cycle of overlapping stroke faces is broken at the face that comes first by depth, and a cap
|
||||
/// drawn last stays after every wall: 0 at x 0 to 10, flat at z 0; 1 at x 4 to 14, z = x - 8; 2 at
|
||||
/// x 8 to 18, flat at z 1. Where they overlap, 0 is nearer than 1, 1 nearer than 2 and 2 nearer
|
||||
/// than 0. 3 is the cap.
|
||||
/// A cycle of overlapping stroke faces is broken at its own face that comes first by depth, and a
|
||||
/// cap drawn last stays after every wall: 0 at x 0 to 10, flat at z 0; 1 at x 4 to 14, z = x - 8;
|
||||
/// 2 at x 8 to 18, flat at z 1. Where they overlap, 0 is nearer than 1, 1 nearer than 2 and 2
|
||||
/// nearer than 0. 3 is the cap.
|
||||
#[test]
|
||||
fn a_depth_cycle_keeps_the_cap_last() {
|
||||
let square = |x: f64| vec![Point::new(x, 0.0), Point::new(x + 10.0, 0.0), Point::new(x + 10.0, 10.0), Point::new(x, 10.0)];
|
||||
@@ -964,6 +964,450 @@ fn a_depth_cycle_keeps_the_cap_last() {
|
||||
assert_eq!(draw_order(&faces, true), [0, 2, 1, 3]);
|
||||
}
|
||||
|
||||
/// A face that lies in front of a face of a cycle, without being part of the cycle, waits for that
|
||||
/// face. 0, 1 and 2 overlap in a cycle (as in `a_depth_cycle_keeps_the_cap_last`); 3, at x 16 to
|
||||
/// 26 and flat at z 2, is nearer than 2 where they overlap, but its center is the farthest of all,
|
||||
/// so it comes first by depth. The cycle is broken at 0, its first face by depth, and 3 follows 2.
|
||||
/// Breaking it at the first face by depth of all the faces left drew 3 first, under 2.
|
||||
#[test]
|
||||
fn a_face_in_front_of_a_cycle_waits_for_it() {
|
||||
let square = |x: f64| vec![Point::new(x, 0.0), Point::new(x + 10.0, 0.0), Point::new(x + 10.0, 10.0), Point::new(x, 10.0)];
|
||||
let at = |depth: f64, x: f64, normal: [f64; 3], offset: f64| Placed {
|
||||
depth,
|
||||
side: true,
|
||||
away: false,
|
||||
bounds: Rect::new(x, 0.0, x + 10.0, 10.0),
|
||||
member: 0,
|
||||
paints: Paints::Other,
|
||||
outline: square(x),
|
||||
plane: Some(DepthPlane { normal, offset, center: Point::ZERO, eye: None }),
|
||||
};
|
||||
let flat = [0.0, 0.0, 1.0];
|
||||
let walls = || [at(1.0, 0.0, flat, 0.0), at(2.0, 4.0, [-1.0, 0.0, 1.0], -8.0), at(3.0, 8.0, flat, 1.0), at(-5.0, 16.0, flat, 2.0)];
|
||||
assert_eq!(draw_order(&walls(), true), [0, 2, 3, 1]);
|
||||
// With the cap of `a_depth_cycle_keeps_the_cap_last` as well, it still goes last.
|
||||
let cap =
|
||||
Placed { depth: f64::MAX, side: false, bounds: Rect::new(0.0, 0.0, 26.0, 10.0), outline: vec![], plane: None, ..at(0.0, 0.0, flat, 0.0) };
|
||||
let capped: Vec<Placed> = walls().into_iter().chain([cap]).collect();
|
||||
assert_eq!(draw_order(&capped, true), [0, 2, 3, 1, 4]);
|
||||
}
|
||||
|
||||
/// `order` with the pairs `before` (each first face drawn before the second) in their own order
|
||||
/// ([`drawn_in_pairs_order`]), within `room` steps of looking for rings, and the steps taken; the
|
||||
/// faces of `last` are drawn last.
|
||||
fn in_pairs_order(order: &[usize], before: &[(usize, usize)], last: &[usize], room: usize) -> (Vec<usize>, usize) {
|
||||
let n = order.len();
|
||||
let mut position = vec![0; n];
|
||||
for (at, &k) in order.iter().enumerate() {
|
||||
position[k] = at;
|
||||
}
|
||||
let last: Vec<bool> = (0..n).map(|k| last.contains(&k)).collect();
|
||||
let mut left = room;
|
||||
let drawn = drawn_in_pairs_order(order.to_vec(), &position, &last, narrow(before), &mut left);
|
||||
(drawn, room - left)
|
||||
}
|
||||
|
||||
/// What [`drawn_in_pairs_order`] is to give with room enough, worked out plainly: at every stop
|
||||
/// the faces behind the first face left are followed afresh, with nothing kept and no face taken
|
||||
/// out of a list.
|
||||
fn in_pairs_order_plainly(order: &[usize], before: &[(usize, usize)], last: &[usize]) -> Vec<usize> {
|
||||
/// The first group completed behind `face`, among the faces `open`: its faces, or `None` while
|
||||
/// its group goes on. `earlier` lists the faces before each face, lowest first.
|
||||
fn group(face: usize, open: &[bool], earlier: &[Vec<usize>], reached: &mut Vec<usize>, low: &mut Vec<usize>) -> Option<Vec<usize>> {
|
||||
let place = reached.len();
|
||||
reached.push(face);
|
||||
low.push(place);
|
||||
for &e in earlier[face].iter().filter(|&&e| open[e]) {
|
||||
match reached.iter().position(|&f| f == e) {
|
||||
Some(at) => low[place] = low[place].min(at),
|
||||
None => {
|
||||
let found = group(e, open, earlier, reached, low);
|
||||
if found.is_some() {
|
||||
return found;
|
||||
}
|
||||
low[place] = low[place].min(low[reached.iter().position(|&f| f == e).unwrap()]);
|
||||
}
|
||||
}
|
||||
}
|
||||
(low[place] == place).then(|| reached[place..].to_vec())
|
||||
}
|
||||
let n = order.len();
|
||||
let mut at = vec![0; n];
|
||||
for (place, &k) in order.iter().enumerate() {
|
||||
at[k] = place;
|
||||
}
|
||||
let mut earlier = vec![vec![]; n];
|
||||
for &(first, then) in before {
|
||||
earlier[then].push(first);
|
||||
}
|
||||
earlier.iter_mut().for_each(|list| list.sort_unstable());
|
||||
let mut drawn = vec![false; n];
|
||||
let mut out: Vec<usize> = vec![];
|
||||
while out.len() < n {
|
||||
let left: Vec<usize> = order.iter().copied().filter(|&k| !drawn[k]).collect();
|
||||
let limit = left.iter().find(|k| last.contains(k)).map_or(usize::MAX, |&k| at[k]);
|
||||
let waits = |k: usize| earlier[k].iter().any(|&e| !drawn[e]);
|
||||
let next = match left.iter().copied().find(|&k| at[k] < limit && !waits(k)) {
|
||||
Some(ready) => ready,
|
||||
None if at[left[0]] >= limit => left[0],
|
||||
None => {
|
||||
let open: Vec<bool> = (0..n).map(|k| !drawn[k] && at[k] < limit).collect();
|
||||
let found = group(left[0], &open, &earlier, &mut vec![], &mut vec![]).unwrap();
|
||||
found.into_iter().min_by_key(|&k| at[k]).unwrap()
|
||||
}
|
||||
};
|
||||
drawn[next] = true;
|
||||
out.push(next);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// `pairs` as [`drawn_in_pairs_order`] takes them.
|
||||
fn narrow(pairs: &[(usize, usize)]) -> Vec<(u32, u32)> {
|
||||
pairs.iter().map(|&(first, then)| (first as u32, then as u32)).collect()
|
||||
}
|
||||
|
||||
/// The pairs of `before` that `drawn` draws the wrong way round.
|
||||
fn broken(drawn: &[usize], before: &[(usize, usize)]) -> Vec<(usize, usize)> {
|
||||
let mut at = vec![0; drawn.len()];
|
||||
for (place, &k) in drawn.iter().enumerate() {
|
||||
at[k] = place;
|
||||
}
|
||||
before.iter().copied().filter(|&(first, then)| at[first] > at[then]).collect()
|
||||
}
|
||||
|
||||
/// After a ring's face is released, the faces left are looked at afresh: they may be a smaller
|
||||
/// ring and faces in none. Two rings share face 1: 0 before 1 before 4 before 0, and 1 before 2
|
||||
/// before 3 before 1. By depth the order is 3, 2, 0, 4, 1. The five wait for no other face, so the
|
||||
/// first stop releases 3, the first of them by depth. That leaves the one ring 0, 1, 4 and face
|
||||
/// 2, which only waits for 1: 0 is released, and 2 follows 1. Only pairs of a ring are drawn the
|
||||
/// wrong way round. Taking the first face left by depth at each stop drew 2 before 1 as well.
|
||||
#[test]
|
||||
fn the_faces_left_are_looked_at_afresh_after_each_face_released() {
|
||||
let before = [(0, 1), (1, 4), (4, 0), (1, 2), (2, 3), (3, 1)];
|
||||
let (drawn, _) = in_pairs_order(&[3, 2, 0, 4, 1], &before, &[], usize::MAX);
|
||||
assert_eq!(drawn, [3, 0, 1, 2, 4]);
|
||||
assert_eq!(broken(&drawn, &before), [(4, 0), (2, 3)]);
|
||||
assert_eq!(broken(&in_pairs_order(&[3, 2, 0, 4, 1], &before, &[], 0).0, &before), [(4, 0), (1, 2), (2, 3)]);
|
||||
}
|
||||
|
||||
/// A ring is the one behind the first face left by depth that waits for no face outside it: 0
|
||||
/// comes first by depth and waits for the ring 1, 2, 3, which waits for the ring 4, 5, 6. The far
|
||||
/// ring is broken first (at 4) and drawn, then the near one (at 1), and 0 follows 1; one pair of
|
||||
/// each ring is drawn the wrong way round, and no pair between them. Taking the first face left by
|
||||
/// depth drew 0 first, under 1.
|
||||
#[test]
|
||||
fn the_ring_released_waits_for_no_face_outside_it() {
|
||||
let before = [(1, 0), (1, 2), (2, 3), (3, 1), (4, 1), (4, 5), (5, 6), (6, 4)];
|
||||
let (drawn, _) = in_pairs_order(&[0, 1, 2, 3, 4, 5, 6], &before, &[], usize::MAX);
|
||||
assert_eq!(drawn, [4, 5, 6, 1, 0, 2, 3]);
|
||||
assert_eq!(broken(&drawn, &before), [(3, 1), (6, 4)]);
|
||||
assert_eq!(broken(&in_pairs_order(&[0, 1, 2, 3, 4, 5, 6], &before, &[], 0).0, &before), [(1, 0), (3, 1), (4, 1), (6, 4)]);
|
||||
}
|
||||
|
||||
/// A ring is looked for among the faces that come before the next face drawn last: 1 comes first
|
||||
/// by depth and waits for 4, a face of the ring 2, 3, 4, and for 0, which is drawn last. 0 waits
|
||||
/// for no face, so it is a group of its own behind 1, but no face before it by depth can wait for
|
||||
/// it. The ring gives up 2, and 1 follows 4; the pair of 1 and 0 cannot be kept. Stopping at 0
|
||||
/// drew 1 first, under 4.
|
||||
#[test]
|
||||
fn a_ring_is_looked_for_before_the_next_face_drawn_last() {
|
||||
let before = [(2, 3), (3, 4), (4, 2), (4, 1), (0, 1)];
|
||||
let (drawn, _) = in_pairs_order(&[1, 2, 3, 4, 0], &before, &[0], usize::MAX);
|
||||
assert_eq!(drawn, [2, 3, 4, 1, 0]);
|
||||
assert_eq!(broken(&drawn, &before), [(4, 2), (0, 1)]);
|
||||
assert_eq!(broken(&in_pairs_order(&[1, 2, 3, 4, 0], &before, &[0], 0).0, &before), [(4, 2), (4, 1), (0, 1)]);
|
||||
// A face that waits only for a face after the one drawn last goes before the faces that wait
|
||||
// for it: 0 waits for 1, 1 for 3, and 2 is drawn last.
|
||||
let before = [(1, 0), (3, 1)];
|
||||
assert_eq!(in_pairs_order(&[0, 1, 2, 3], &before, &[2], usize::MAX).0, [1, 0, 2, 3]);
|
||||
assert_eq!(in_pairs_order(&[0, 1, 2, 3], &before, &[2], 0).0, [0, 1, 2, 3]);
|
||||
}
|
||||
|
||||
/// Looking for rings is counted, and past the room given the first face not drawn yet goes next,
|
||||
/// as before rings were looked for: the pairs of `a_face_in_front_of_a_cycle_waits_for_it`. A
|
||||
/// face drawn last keeps every face before it by depth before it, ring or not. An order and
|
||||
/// places in it that do not agree (an order that is not each face once), or a pair of a face that
|
||||
/// is not in them, give the order back.
|
||||
#[test]
|
||||
fn breaking_rings_stops_at_its_room() {
|
||||
let before = [(1, 0), (0, 2), (2, 1), (2, 3)];
|
||||
let order = [3, 0, 1, 2];
|
||||
let (drawn, steps) = in_pairs_order(&order, &before, &[], usize::MAX);
|
||||
assert_eq!(drawn, [0, 2, 3, 1]);
|
||||
// The faces and pairs behind 3.
|
||||
assert!((4..=16).contains(&steps), "{steps} steps");
|
||||
assert_eq!(in_pairs_order(&order, &before, &[], steps), (vec![0, 2, 3, 1], steps));
|
||||
for room in [0, 1, steps - 1] {
|
||||
let (drawn, taken) = in_pairs_order(&order, &before, &[], room);
|
||||
assert_eq!(drawn, [3, 0, 2, 1], "{room}");
|
||||
assert!(taken <= room, "{room}");
|
||||
}
|
||||
// 0 is drawn last: 3, before it by depth, goes before it, and the ring's other faces after.
|
||||
assert_eq!(in_pairs_order(&order, &before, &[0], usize::MAX).0, [3, 0, 2, 1]);
|
||||
// 2 is drawn last: every other face is before it by depth, so 3 and 1, which wait only for
|
||||
// it, go when they come first of the faces behind the first face left, and 0 follows 1.
|
||||
assert_eq!(in_pairs_order(&order, &before, &[2], usize::MAX).0, [3, 1, 0, 2]);
|
||||
assert_eq!(in_pairs_order(&order, &before, &[2], 0).0, [3, 0, 1, 2]);
|
||||
let mut room = usize::MAX;
|
||||
let position = [1, 2, 3, 0];
|
||||
assert_eq!(drawn_in_pairs_order(order.to_vec(), &position, &[false; 3], narrow(&before), &mut room), order);
|
||||
assert_eq!(drawn_in_pairs_order(order.to_vec(), &position, &[false; 4], vec![(9, 0)], &mut room), order);
|
||||
assert_eq!(drawn_in_pairs_order(order.to_vec(), &position, &[false; 4], vec![(0, 4)], &mut room), order);
|
||||
assert_eq!(drawn_in_pairs_order(order[..3].to_vec(), &position, &[false; 4], narrow(&before), &mut room), order[..3]);
|
||||
assert_eq!(drawn_in_pairs_order(order.to_vec(), &position[..3], &[false; 4], narrow(&before), &mut room), order);
|
||||
assert_eq!(drawn_in_pairs_order(order.to_vec(), &[1, 2, 0, 3], &[false; 4], narrow(&before), &mut room), order);
|
||||
assert_eq!(drawn_in_pairs_order(vec![0, 0, 1, 2], &[0, 2, 3, 0], &[false; 4], narrow(&before), &mut room), [0, 0, 1, 2]);
|
||||
assert_eq!(drawn_in_pairs_order(vec![0, 1, 2, 4], &[0, 1, 2, 3], &[false; 4], narrow(&before), &mut room), [0, 1, 2, 4]);
|
||||
assert_eq!(room, usize::MAX);
|
||||
}
|
||||
|
||||
/// A first face left that waits only for the face drawn last goes next with no search: 1,000
|
||||
/// such faces before a ring cost nothing, and the ring behind them still has its room. Each face
|
||||
/// i < 1,000 waits for 1,004, which is drawn last; 1,000 to 1,003 are the pairs of
|
||||
/// `breaking_rings_stops_at_its_room`, where 1,003 comes first by depth and waits for the ring.
|
||||
#[test]
|
||||
fn a_face_that_waits_only_for_the_face_drawn_last_costs_no_search() {
|
||||
let waiting = 1000usize;
|
||||
let (r, last) = (waiting, waiting + 4);
|
||||
let mut before: Vec<(usize, usize)> = (0..waiting).map(|f| (last, f)).collect();
|
||||
before.extend([(r + 1, r), (r, r + 2), (r + 2, r + 1), (r + 2, r + 3)]);
|
||||
let order: Vec<usize> = (0..waiting).chain([r + 3, r, r + 1, r + 2, last]).collect();
|
||||
let (drawn, steps) = in_pairs_order(&order, &before, &[last], usize::MAX);
|
||||
let expected: Vec<usize> = (0..waiting).chain([r, r + 2, r + 3, r + 1, last]).collect();
|
||||
assert_eq!(drawn, expected);
|
||||
assert!(steps < 20, "{steps} steps");
|
||||
// The room the ring takes is enough, whatever waits before it.
|
||||
assert_eq!(in_pairs_order(&order, &before, &[last], before.len().div_ceil(4).max(steps)).0, expected);
|
||||
}
|
||||
|
||||
/// The lists of the faces before each face are made only when the room left is at least a
|
||||
/// quarter of the pairs: with less, no ring is looked for, however few steps the ring would take.
|
||||
/// A ring of three behind 3,000 faces in a chain (each before the next).
|
||||
#[test]
|
||||
fn the_lists_for_rings_are_made_only_with_room_for_a_quarter_of_the_pairs() {
|
||||
let chain = 3000usize;
|
||||
let r = chain;
|
||||
let mut before: Vec<(usize, usize)> = (0..chain - 1).map(|f| (f, f + 1)).collect();
|
||||
before.extend([(r + 1, r), (r, r + 2), (r + 2, r + 1), (r + 2, r + 3)]);
|
||||
// As in `breaking_rings_stops_at_its_room`: 3 comes first by depth of the four and waits for
|
||||
// the ring.
|
||||
let order: Vec<usize> = (0..chain).chain([r + 3, r, r + 1, r + 2]).collect();
|
||||
let (drawn, steps) = in_pairs_order(&order, &before, &[], usize::MAX);
|
||||
assert_eq!(drawn[chain..], [r, r + 2, r + 3, r + 1]);
|
||||
assert!(steps < 20, "{steps} steps");
|
||||
let quarter = before.len().div_ceil(4);
|
||||
let (drawn, steps) = in_pairs_order(&order, &before, &[], quarter - 1);
|
||||
assert_eq!(drawn[chain..], [r + 3, r, r + 2, r + 1]);
|
||||
assert_eq!(steps, 0);
|
||||
assert_eq!(in_pairs_order(&order, &before, &[], quarter).0[chain..], [r, r + 2, r + 3, r + 1]);
|
||||
}
|
||||
|
||||
/// A list of the faces before a face is read only when the room left holds it: with less, no
|
||||
/// entry of it is read, and the first face left goes next. Face 0 comes first by depth and waits
|
||||
/// for 1, which waits for 2,000 faces after it in `order`, each waiting for 1: a ring of 1 with
|
||||
/// each of them.
|
||||
#[test]
|
||||
fn a_list_longer_than_the_room_left_is_not_read() {
|
||||
let wide = 2000usize;
|
||||
let mut before = vec![(1, 0)];
|
||||
before.extend((2..2 + wide).flat_map(|f| [(f, 1), (1, f)]));
|
||||
let order: Vec<usize> = (0..2 + wide).collect();
|
||||
// Room for the lists (a quarter of the pairs) but not for 1's list, and room for it.
|
||||
// With too little room only 0's one-entry list is read; with room for both, 1's list as well.
|
||||
for (room, want) in [(before.len().div_ceil(4), 1), (wide - 1, 1), (wide + 3, wide + 1)] {
|
||||
super::LIST_ENTRIES_READ.with(|read| read.set(0));
|
||||
let (drawn, taken) = in_pairs_order(&order, &before, &[], room);
|
||||
let read = super::LIST_ENTRIES_READ.with(|read| read.get());
|
||||
assert_eq!(read, want, "room {room}: {read} entries read, {taken} steps");
|
||||
assert!(read <= taken && taken <= room, "room {room}: {read} entries read, {taken} steps");
|
||||
assert_eq!(drawn.len(), order.len());
|
||||
}
|
||||
}
|
||||
|
||||
/// The steps of breaking rings are counted, not timed, and for rings of a few faces they are a
|
||||
/// few a face however the rings lie: apart, each with a face in front of it that comes first by
|
||||
/// depth; all behind one face, itself in a ring whose other faces come first in its list; and one
|
||||
/// behind the other. The search goes on from where it stopped, and a face drawn is dropped from
|
||||
/// a list the next time the list is looked at. A ring that is still a ring after it gives up a
|
||||
/// face is walked again, so a large ring can take about its pairs for each face it gives up, the
|
||||
/// square of its faces even when each waits for few others. With too little room the rings not
|
||||
/// reached are broken at the first face left by depth, as before.
|
||||
#[test]
|
||||
fn breaking_rings_takes_a_few_steps_a_face_but_for_a_ring_of_many_pairs() {
|
||||
// Ring r: faces 4r, 4r + 1 and 4r + 2 in a ring, and 4r + 3 after 4r + 2.
|
||||
let rings = 2000usize;
|
||||
let mut before = vec![];
|
||||
for r in 0..rings {
|
||||
let f = 4 * r;
|
||||
before.extend([(f + 1, f), (f, f + 2), (f + 2, f + 1), (f + 2, f + 3)]);
|
||||
}
|
||||
// By depth: every fourth face first, then the rings.
|
||||
let order: Vec<usize> = (0..rings).map(|r| 4 * r + 3).chain((0..rings).flat_map(|r| [4 * r, 4 * r + 1, 4 * r + 2])).collect();
|
||||
let (drawn, steps) = in_pairs_order(&order, &before, &[], usize::MAX);
|
||||
assert_eq!(broken(&drawn, &before), (0..rings).map(|r| (4 * r + 1, 4 * r)).collect::<Vec<_>>());
|
||||
assert!(steps <= 4 * order.len(), "{steps} steps for {rings} rings apart");
|
||||
// With no room the fourth faces go first, under the faces they are in front of.
|
||||
assert_eq!(broken(&in_pairs_order(&order, &before, &[], 0).0, &before).len(), 2 * rings);
|
||||
|
||||
// Face 0, first by depth, is in a ring with 1 and 2, which come first in its list, and after a
|
||||
// face of each ring r: faces 3r + 3, 3r + 4 and 3r + 5.
|
||||
let rings = 3000usize;
|
||||
let mut before = vec![(1, 0), (0, 2), (2, 1)];
|
||||
for r in 0..rings {
|
||||
let f = 3 * r + 3;
|
||||
before.extend([(f, f + 1), (f + 1, f + 2), (f + 2, f), (f, 0)]);
|
||||
}
|
||||
let order: Vec<usize> = (0..3 * rings + 3).collect();
|
||||
let (drawn, steps) = in_pairs_order(&order, &before, &[], usize::MAX);
|
||||
// One pair of each ring, face 0's among them, and no pair of face 0 with another ring's face.
|
||||
assert_eq!(broken(&drawn, &before), [(1, 0)].into_iter().chain((0..rings).map(|r| (3 * r + 5, 3 * r + 3))).collect::<Vec<_>>());
|
||||
assert!(steps <= 4 * order.len(), "{steps} steps for {rings} rings behind one face");
|
||||
// The same with a face drawn last that every ring's first face waits for: it is passed over
|
||||
// each time, and nothing after it in a list is looked at twice for that.
|
||||
let cap = 3 * rings + 3;
|
||||
let capped: Vec<(usize, usize)> = (0..rings).map(|r| (cap, 3 * r + 3)).chain(before.iter().copied()).collect();
|
||||
let order: Vec<usize> = (0..=cap).collect();
|
||||
let (drawn, steps) = in_pairs_order(&order, &capped, &[cap], usize::MAX);
|
||||
assert_eq!(broken(&drawn, &capped).len(), 2 * rings + 1);
|
||||
assert!(steps <= 5 * order.len(), "{steps} steps for {rings} rings behind one face, before a face drawn last");
|
||||
|
||||
// Ring r: faces 3r, 3r + 1 and 3r + 2, the first after the last face of ring r + 1.
|
||||
let rings = 3000usize;
|
||||
let mut before = vec![];
|
||||
for r in 0..rings {
|
||||
let f = 3 * r;
|
||||
before.extend([(f, f + 1), (f + 1, f + 2), (f + 2, f)]);
|
||||
if r + 1 < rings {
|
||||
before.push((f + 5, f));
|
||||
}
|
||||
}
|
||||
let order: Vec<usize> = (0..3 * rings).collect();
|
||||
let (drawn, steps) = in_pairs_order(&order, &before, &[], usize::MAX);
|
||||
// One pair of each ring, and no pair between rings.
|
||||
assert_eq!(broken(&drawn, &before).len(), rings);
|
||||
assert!(broken(&drawn, &before).iter().all(|&(first, then)| first / 3 == then / 3));
|
||||
assert!(steps <= 4 * order.len(), "{steps} steps for {rings} rings one behind the other");
|
||||
let (short, taken) = in_pairs_order(&order, &before, &[], steps / 2);
|
||||
assert!(broken(&short, &before).len() > rings && taken <= steps / 2, "{} pairs, {taken} steps", broken(&short, &before).len());
|
||||
assert_eq!(short.len(), order.len());
|
||||
|
||||
// One ring: each of 200 faces before the next 99.
|
||||
let faces = 200usize;
|
||||
let before: Vec<(usize, usize)> = (0..faces).flat_map(|f| (1..100).map(move |d| (f, (f + d) % faces))).collect();
|
||||
let order: Vec<usize> = (0..faces).collect();
|
||||
let (drawn, steps) = in_pairs_order(&order, &before, &[], usize::MAX);
|
||||
assert_eq!(drawn, order);
|
||||
// Each face it gives up walks the ring again, so it takes many times its pairs (the cost the
|
||||
// docs name), but no more than about its pairs for each face.
|
||||
assert!(steps < 2 * faces * before.len(), "{steps} steps for a ring of {} pairs", before.len());
|
||||
|
||||
// Pairs at random, about four a face: one large ring and faces around it.
|
||||
let steps_of = |faces: usize| {
|
||||
let mut next = numbers(faces as u64);
|
||||
let before: Vec<(usize, usize)> = (0..2 * faces)
|
||||
.map(|_| ((next() * faces as f64) as usize, (next() * faces as f64) as usize))
|
||||
.filter(|(first, then)| first != then)
|
||||
.collect();
|
||||
let order: Vec<usize> = (0..faces).collect();
|
||||
let (drawn, steps) = in_pairs_order(&order, &before, &[], usize::MAX);
|
||||
assert_eq!(drawn.len(), faces);
|
||||
steps
|
||||
};
|
||||
// No more than the square of the faces.
|
||||
let (few, more) = (steps_of(800), steps_of(1600));
|
||||
assert!(few < 800 * 800 && more < 1600 * 1600, "{few} steps for 800 faces, {more} for 1,600");
|
||||
}
|
||||
|
||||
/// Numbers from 0 to 1 that are the same on every run.
|
||||
fn numbers(mut seed: u64) -> impl FnMut() -> f64 {
|
||||
move || {
|
||||
seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
|
||||
(seed >> 11) as f64 / (1u64 << 53) as f64
|
||||
}
|
||||
}
|
||||
|
||||
/// A ring gives up its own face that comes first by depth, which draws no more pairs the wrong
|
||||
/// way round than taking the first face left by depth, ring or not, as before: on 6,000 sets of
|
||||
/// pairs at random (4 to 30 faces, sparse and dense, agreeing with the depths mostly or half the
|
||||
/// time, the pairs in any order and some twice, with up to four faces drawn last) none has more, and they have fewer in all. Every face
|
||||
/// is drawn once, a face drawn last follows every face before it by depth, and the order of every
|
||||
/// set is the one that looking afresh at every stop gives. One of them is a
|
||||
/// set where the ring's face that waits for the fewest faces drew 4 pairs wrong against 3.
|
||||
#[test]
|
||||
fn breaking_a_ring_draws_no_more_pairs_wrong_than_the_first_face_by_depth() {
|
||||
let order = [3, 6, 4, 1, 0, 2, 5];
|
||||
let before = [
|
||||
(1, 0),
|
||||
(2, 0),
|
||||
(0, 3),
|
||||
(0, 4),
|
||||
(5, 0),
|
||||
(6, 0),
|
||||
(1, 2),
|
||||
(1, 3),
|
||||
(4, 1),
|
||||
(5, 1),
|
||||
(4, 2),
|
||||
(5, 2),
|
||||
(6, 2),
|
||||
(3, 4),
|
||||
(3, 6),
|
||||
(5, 4),
|
||||
(6, 4),
|
||||
(5, 6),
|
||||
];
|
||||
assert_eq!(broken(&in_pairs_order(&order, &before, &[], 0).0, &before).len(), 3);
|
||||
assert_eq!(broken(&in_pairs_order(&order, &before, &[], usize::MAX).0, &before).len(), 3);
|
||||
|
||||
let mut next = numbers(7023);
|
||||
let (mut with_rings, mut without, mut fewer) = (0usize, 0usize, 0usize);
|
||||
for set in 0..6000 {
|
||||
let n = 4 + (next() * 27.0) as usize;
|
||||
let (dense, agrees) = (0.05 + 0.8 * next() * next(), if set % 2 == 0 { 0.5 } else { 0.85 });
|
||||
// The order by depth: the faces shuffled.
|
||||
let mut order: Vec<usize> = (0..n).collect();
|
||||
for k in (1..n).rev() {
|
||||
order.swap(k, (next() * (k + 1) as f64) as usize);
|
||||
}
|
||||
let mut before = vec![];
|
||||
for a in 0..n {
|
||||
for b in a + 1..n {
|
||||
if next() < dense {
|
||||
before.push(if next() < agrees { (order[a], order[b]) } else { (order[b], order[a]) });
|
||||
}
|
||||
}
|
||||
}
|
||||
// The pairs in any order, and in every fifth set some of them twice.
|
||||
for k in (1..before.len()).rev() {
|
||||
before.swap(k, (next() * (k + 1) as f64) as usize);
|
||||
}
|
||||
if set % 5 == 0 {
|
||||
let again: Vec<(usize, usize)> = before.iter().copied().filter(|_| next() < 0.3).collect();
|
||||
before.extend(again);
|
||||
}
|
||||
// No face drawn last, or up to four.
|
||||
let last: Vec<usize> = (0..set % 5).map(|_| order[(next() * n as f64) as usize]).collect();
|
||||
let (drawn, _) = in_pairs_order(&order, &before, &last, usize::MAX);
|
||||
// Keeping the search from stop to stop gives what looking afresh at every stop gives.
|
||||
assert_eq!(drawn, in_pairs_order_plainly(&order, &before, &last), "set {set}: {order:?} {before:?} {last:?}");
|
||||
let (plainly, _) = in_pairs_order(&order, &before, &last, 0);
|
||||
let mut once = drawn.clone();
|
||||
once.sort_unstable();
|
||||
assert_eq!(once, (0..n).collect::<Vec<_>>(), "set {set}");
|
||||
for &cap in &last {
|
||||
let (at, place) = (order.iter().position(|&f| f == cap).unwrap(), drawn.iter().position(|&f| f == cap).unwrap());
|
||||
assert!(order[..at].iter().all(|f| drawn[..place].contains(f)), "set {set}");
|
||||
}
|
||||
let (rings, plain) = (broken(&drawn, &before).len(), broken(&plainly, &before).len());
|
||||
assert!(rings <= plain, "set {set}: {rings} pairs wrong, {plain} with the first face by depth; {order:?} {before:?} {last:?}");
|
||||
with_rings += rings;
|
||||
without += plain;
|
||||
fewer += usize::from(rings < plain);
|
||||
}
|
||||
assert!(fewer > 500 && with_rings < without, "{with_rings} pairs wrong, {without} with the first face by depth, fewer in {fewer} sets");
|
||||
}
|
||||
|
||||
/// The order keeps depths except where a shape's fill wall turned toward the viewer overlaps a
|
||||
/// face of the same shape's stroke drawn before it: the wall then goes just before that face. A
|
||||
/// cap, a face turned away, another shape's stroke, a stroke face the wall does not overlap and an
|
||||
|
||||
@@ -89,6 +89,10 @@ windows-native-keyring-store = "1.1"
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
||||
heic-rs = { version = "=0.1.4", default-features = false, features = ["std", "parallel"], optional = true }
|
||||
rayon = { version = "1.12", optional = true }
|
||||
# Language packs (packs.rs): the shared font store installs them and finds its folder. Already in
|
||||
# Cargo.lock (craft-font-manager), so this adds no new crate.
|
||||
craft-font-store = { workspace = true }
|
||||
craft-font-catalog = { workspace = true }
|
||||
# The MAC that `grants.json` carries (grant_keys.rs) and the random key it is made with, which the
|
||||
# user's key store keeps: Keychain on macOS, Credential Manager on Windows, the Secret Service on
|
||||
# Linux. All MIT OR Apache-2.0.
|
||||
|
||||
@@ -65,6 +65,8 @@ pub(crate) mod objects_on_path;
|
||||
mod opacitymask;
|
||||
mod overprint;
|
||||
pub mod package;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub mod packs;
|
||||
mod paint;
|
||||
mod panelcmds;
|
||||
pub mod params;
|
||||
@@ -382,6 +384,9 @@ pub fn command_specs() -> &'static [CommandSpec] {
|
||||
v.extend(tags::specs());
|
||||
v.extend(interactivity::specs());
|
||||
v.extend(spelling::specs());
|
||||
// Language packs need a font store, which the web build has none of.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
v.extend(packs::specs());
|
||||
v.extend(svgfilter::specs());
|
||||
v.extend(newart::specs());
|
||||
v.extend(colortheme::specs());
|
||||
@@ -851,11 +856,12 @@ pub(crate) const MAX_IMPORTED_PRESETS: usize = 1000;
|
||||
pub(crate) use addons::{DecodedImages, refresh_color_masks};
|
||||
/// Packaging Tools' blanks and the objects their print leaves out, for the Fold Preview window.
|
||||
pub use addons::{FoldAngles, fold_source, print_hidden, selection_fold_angles, selection_fold_lines};
|
||||
pub use colorcmds::{Backdrop, contrast_measure, contrast_pick_backdrop};
|
||||
/// Document Info's category titles, the Objects category's count labels, and how its image rows
|
||||
/// write a resolution and a number of bytes.
|
||||
pub use docinfo::{CATEGORIES, OBJECT_LABELS, byte_size, ppi_number};
|
||||
pub use docmenu::guide_indexes;
|
||||
pub(crate) use edit::{Unrecorded, settle_interaction, typing_in_progress};
|
||||
pub(crate) use edit::{Unrecorded, artboard_tool_picks, settle_interaction, typing_in_progress};
|
||||
pub(crate) use object::bounds_rewrite;
|
||||
pub(crate) use object::{keep_aligned_in, refresh_pixel_aligned};
|
||||
/// The rules `object.scale`, `object.reflect` and `object.shear` check their params with.
|
||||
@@ -865,11 +871,11 @@ pub use plugin_call::{Location, ParamsPlace, key_location, location_in, location
|
||||
pub use select::SIMILAR;
|
||||
pub(crate) use vectorcraft_doc::range::parse_range;
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) use paint::PAINTS_READ;
|
||||
/// What the fill and stroke proxies read from the selected objects, kept with the selection
|
||||
/// ([`crate::doc_state::SelectionRecord`]).
|
||||
pub(crate) use paint::SelectionPaints;
|
||||
#[cfg(test)]
|
||||
pub(crate) use paint::{PAINTS_READ, WEIGHTS_READ};
|
||||
|
||||
/// A date param in Unix seconds that defaults to the clock: `None` when absent (now, see
|
||||
/// [`clock_date`]), `Some(None)` for null (no date), else `Some(Some(seconds))`.
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
//! Arrange Tools (`addon.arrange.*`), a built-in add-on: Arrange in Grid lays the selected objects
|
||||
//! out in rows and columns, a row or a column; Swap Objects swaps the places (and sizes) of two;
|
||||
//! out in rows and columns, a row or a column; Offset Objects chains them one after another in a
|
||||
//! row or a column with a set gap, the first staying in place; Swap Objects swaps the places (and sizes) of two;
|
||||
//! Replace with Top Object puts a copy of the topmost selected object in place of each of the
|
||||
//! others; and Set Size of Each gives every selected object an exact width and height. Places and
|
||||
//! sizes are measured and set as `object.setBounds` does. Group Overlapping Objects groups the
|
||||
//! sizes are measured and set as `object.setBounds` does. Match Objects gives the other selected
|
||||
//! objects the size, bounding-box angle and stacking place of one of them. Group Overlapping Objects groups the
|
||||
//! objects whose visual bounds overlap, Randomize Opacity gives each selected object a random
|
||||
//! opacity, and Sort Objects sorts the selected objects by one attribute and gives them another in
|
||||
//! that order. Its submenu (Object › Plug-ins › Arrange Tools), its dialogs and Zoom to Selection
|
||||
@@ -17,7 +19,7 @@ use std::sync::Arc;
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::recolor::Rng;
|
||||
use vectorcraft_doc::{Node, NodeId, OrientedBox};
|
||||
use vectorcraft_geom::{Affine, Point, Rect};
|
||||
use vectorcraft_geom::{Affine, Point, Rect, Vec2};
|
||||
use vectorcraft_render::effects;
|
||||
|
||||
use super::super::appearance::series_children_in_paint_order;
|
||||
@@ -52,6 +54,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_selection,
|
||||
grid
|
||||
),
|
||||
cmd!(
|
||||
"addon.arrange.offset",
|
||||
"Offset Objects",
|
||||
["Object", "Plug-ins", "Arrange Tools"],
|
||||
None,
|
||||
"{direction?: \"row\" (left to right) | \"column\" (top to bottom) (\"row\"), gap?: pt −1000000..1000000 (10; negative: the objects overlap), order?: \"stacking\" (stacking order, from the back) | \"position\" (by left edge in a row, by top edge in a column; equal edges keep their stacking order) (\"stacking\"), reverse?: false (true: the order runs the other way)} chain the selected objects (the top-level ones) one after another in that order, as one undo step: the first stays where it is, and each later one moves only along the direction, so that its left (top) edge is `gap` past the right (bottom) edge of the one before it; its place across the direction stays. Everything is measured by visual bounds (strokes and effects as drawn; a clipping group by its mask). A run that moves nothing makes no step → {count}",
|
||||
has_multi,
|
||||
offset
|
||||
),
|
||||
cmd!(
|
||||
"addon.arrange.swap",
|
||||
"Swap Objects",
|
||||
@@ -79,6 +90,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_selection,
|
||||
size
|
||||
),
|
||||
cmd!(
|
||||
"addon.arrange.match",
|
||||
"Match Objects",
|
||||
["Object", "Plug-ins", "Arrange Tools"],
|
||||
None,
|
||||
"{source?: \"key\" (the key object, select.key) | \"top\" (the frontmost selected object) | \"bottom\" (the backmost) (default: the key object when the selection has one, else \"top\"), size?: \"none\" | \"width\" (each target takes the source's width, its height following in proportion) | \"height\" (the source's height, the width following in proportion) | \"both\" (the source's width and height, each on its own) (\"none\"), rotate?: false (true: each target takes the source's bounding-box angle, measured counter-clockwise, turning the shorter way, at most 180°), stacking?: false (true: the targets go directly above the source in the stacking order, in its layer or group, in the order they had), reference?: 0..8 (the 9-point grid row by row from the top-left; 4, the center: the point of each target that stays put as it is sized and turned), scaleStrokes?: the Scale Strokes & Effects preference, patterns?: the Transform Pattern Tiles preference (at least one of size, rotate and stacking)} make the other selected objects (the top-level ones, at most 20000) match the source, which stays as it is, as one undo step (none when nothing changes). Sizes are measured and set as object.setBounds measures them (Use Preview Bounds), each in the object's own bounding-box frame, and a size that a target has no width or height to take is refused, as is a stacking match that would move a clipping path; to match places, use object.align {to: \"key\"} → {source, count}",
|
||||
has_multi,
|
||||
match_objects
|
||||
),
|
||||
cmd!(
|
||||
"addon.arrange.groupOverlapping",
|
||||
"Group Overlapping Objects",
|
||||
@@ -167,6 +187,14 @@ fn transform_each(s: &mut Session, label: &str, strokes: bool, xfs: &[(NodeId, A
|
||||
})
|
||||
}
|
||||
|
||||
/// The `scaleStrokes` param, else the Scale Strokes & Effects preference. The value joins the
|
||||
/// command's journal entry, so replaying it scales the same way whatever the preference is then.
|
||||
fn scale_strokes(s: &mut Session, p: &Value, cmd: &str) -> Result<bool> {
|
||||
let on = switch_or(p, "scaleStrokes", s.prefs.scale_strokes, cmd)?;
|
||||
s.note_journal("scaleStrokes", json!(on));
|
||||
Ok(on)
|
||||
}
|
||||
|
||||
/// The box of object `id` as `object.setBounds` measures it.
|
||||
fn box_of(s: &Session, id: NodeId) -> Result<OrientedBox> {
|
||||
s.transform_box(&[id]).ok_or_else(|| EngineError::Other("no bounds".into()))
|
||||
@@ -228,10 +256,46 @@ fn grid(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "count": n }))
|
||||
}
|
||||
|
||||
fn offset(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "addon.arrange.offset";
|
||||
let row = choice(p, C, "direction", &["row", "column"])?.unwrap_or("row") == "row";
|
||||
let gap = number_in(p, "gap", 10.0, (-LIMIT, LIMIT), C)?;
|
||||
let by_position = choice(p, C, "order", &["stacking", "position"])?.unwrap_or("stacking") == "position";
|
||||
let reverse = switch_or(p, "reverse", false, C)?;
|
||||
let roots = selected_roots(s)?;
|
||||
let d = &s.doc()?.doc;
|
||||
// The objects in stacking order from the back, each with its leading and trailing edge along the direction.
|
||||
let mut items: Vec<(NodeId, f64, f64)> = roots
|
||||
.iter()
|
||||
.filter_map(|id| {
|
||||
let b = effects::preview::bounds_of(d, &[*id], true)?;
|
||||
Some(if row { (*id, b.x0, b.x1) } else { (*id, b.y0, b.y1) })
|
||||
})
|
||||
.collect();
|
||||
if by_position {
|
||||
items.sort_by(|a, b| a.1.total_cmp(&b.1));
|
||||
}
|
||||
if reverse {
|
||||
items.reverse();
|
||||
}
|
||||
// The first stays; each later one starts `gap` past where the one before it now ends.
|
||||
let mut end: Option<f64> = None;
|
||||
let xfs: Vec<(NodeId, Affine)> = items
|
||||
.iter()
|
||||
.map(|&(id, start, finish)| {
|
||||
let shift = end.map_or(0.0, |e| e + gap - start);
|
||||
end = Some(finish + shift);
|
||||
(id, Affine::translate(if row { Vec2::new(shift, 0.0) } else { Vec2::new(0.0, shift) }))
|
||||
})
|
||||
.collect();
|
||||
transform_each(s, "Offset Objects", false, &xfs)?;
|
||||
Ok(json!({ "count": items.len() }))
|
||||
}
|
||||
|
||||
fn swap(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "addon.arrange.swap";
|
||||
let size = switch_or(p, "size", false, C)?;
|
||||
let strokes = switch_or(p, "scaleStrokes", s.prefs.scale_strokes, C)?;
|
||||
let strokes = scale_strokes(s, p, C)?;
|
||||
let roots = selected_roots(s)?;
|
||||
let &[a, b] = roots.as_slice() else { return Err(bad(C, "select exactly two objects")) };
|
||||
let (ba, bb) = (box_of(s, a)?, box_of(s, b)?);
|
||||
@@ -244,7 +308,7 @@ fn swap(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
fn replace(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "addon.arrange.replace";
|
||||
let fit = choice(p, C, "fit", &["keep", "bounds", "proportional"])?.unwrap_or("keep");
|
||||
let strokes = switch_or(p, "scaleStrokes", s.prefs.scale_strokes, C)?;
|
||||
let strokes = scale_strokes(s, p, C)?;
|
||||
let keep = switch_or(p, "keep", false, C)?;
|
||||
let roots = selected_roots(s)?;
|
||||
let Some((&top, others)) = roots.split_last().filter(|(_, others)| !others.is_empty()) else {
|
||||
@@ -295,7 +359,7 @@ fn size(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let proportional = switch_or(p, "proportional", false, C)?;
|
||||
let reference = whole_in(p, "reference", (0, 8), C)?.unwrap_or(4);
|
||||
let strokes = switch_or(p, "scaleStrokes", s.prefs.scale_strokes, C)?;
|
||||
let strokes = scale_strokes(s, p, C)?;
|
||||
let mut q = json!({ "reference": reference, "strokes": strokes, "proportional": proportional && (width.is_none() || height.is_none()) });
|
||||
if let Some(w) = width {
|
||||
q["width"] = json!(w);
|
||||
@@ -313,6 +377,158 @@ fn size(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "count": xfs.len() }))
|
||||
}
|
||||
|
||||
/// The source Match Objects matches `roots` (the selected roots, in stacking order) to, from its
|
||||
/// `source` param: the selected root that is the key object or holds it, the frontmost or the backmost.
|
||||
fn match_source(s: &Session, p: &Value, roots: &[NodeId], cmd: &str) -> Result<NodeId> {
|
||||
let st = s.doc()?;
|
||||
let key = st.selection.key.and_then(|k| st.doc.ancestry(k)).and_then(|up| roots.iter().copied().find(|id| up.contains(id)));
|
||||
let picked = match choice(p, cmd, "source", &["key", "top", "bottom"])? {
|
||||
Some("key") => Some(key.ok_or_else(|| bad(cmd, "no key object: set one with select.key"))?),
|
||||
Some("bottom") => roots.first().copied(),
|
||||
Some(_) => roots.last().copied(),
|
||||
None => key.or_else(|| roots.last().copied()),
|
||||
};
|
||||
picked.ok_or_else(|| bad(cmd, "select at least two objects"))
|
||||
}
|
||||
|
||||
/// Whether `targets` (in stacking order) are directly above `source` in its layer or group, in that order.
|
||||
fn stacked_above(d: &vectorcraft_doc::Document, source: NodeId, targets: &[NodeId]) -> bool {
|
||||
let paths = d.index_paths(targets.iter().copied().chain([source]));
|
||||
let Some((&at, up)) = paths.get(&source).and_then(|p| p.split_last()) else { return false };
|
||||
targets.iter().enumerate().all(|(i, id)| paths.get(id).and_then(|p| p.split_last()) == Some((&(at + 1 + i), up)))
|
||||
}
|
||||
|
||||
fn match_objects(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "addon.arrange.match";
|
||||
let size = choice(p, C, "size", &["none", "width", "height", "both"])?.unwrap_or("none");
|
||||
let rotate = switch_or(p, "rotate", false, C)?;
|
||||
let stacking = switch_or(p, "stacking", false, C)?;
|
||||
let reference = whole_in(p, "reference", (0, 8), C)?.unwrap_or(4);
|
||||
let strokes = scale_strokes(s, p, C)?;
|
||||
let patterns = switch_or(p, "patterns", s.prefs.transform_pattern_tiles, C)?;
|
||||
if size == "none" && !rotate && !stacking {
|
||||
return Err(bad(C, "give `size`, `rotate` or `stacking`"));
|
||||
}
|
||||
let roots = selected_roots(s)?;
|
||||
if roots.len() > MAX_OBJECTS {
|
||||
return Err(bad(C, "too many objects selected (at most 20000)"));
|
||||
}
|
||||
let source = match_source(s, p, &roots, C)?;
|
||||
let targets: Vec<NodeId> = roots.iter().copied().filter(|id| *id != source).collect();
|
||||
if targets.is_empty() {
|
||||
return Err(bad(C, "select at least two objects"));
|
||||
}
|
||||
// Only sizing measures the source; a stacking or rotate match doesn't need its bounds.
|
||||
let (w, h) = if size == "none" {
|
||||
(0.0, 0.0)
|
||||
} else {
|
||||
let sb = box_of(s, source)?;
|
||||
(sb.rect.width(), sb.rect.height())
|
||||
};
|
||||
let wanted = match size {
|
||||
"width" if w < LEAST => return Err(bad(C, "the source object has no width")),
|
||||
"height" if h < LEAST => return Err(bad(C, "the source object has no height")),
|
||||
"both" if w < LEAST || h < LEAST => return Err(bad(C, "the source object has no width or no height")),
|
||||
"width" => Some(json!({ "width": w, "proportional": true })),
|
||||
"height" => Some(json!({ "height": h, "proportional": true })),
|
||||
"both" => Some(json!({ "width": w, "height": h })),
|
||||
_ => None,
|
||||
};
|
||||
let angle = s.doc()?.doc.bbox_angle(&[source]);
|
||||
let mut xfs = Vec::with_capacity(targets.len());
|
||||
for &id in &targets {
|
||||
let turn = if rotate { vectorcraft_geom::normalize_deg(angle - s.doc()?.doc.bbox_angle(&[id])) } else { 0.0 };
|
||||
let Some(b) = s.transform_box(&[id]) else {
|
||||
if wanted.is_some() {
|
||||
return Err(bad(C, format!("object {} has no bounds to size", id.0)));
|
||||
}
|
||||
if turn.abs() > 1e-9 {
|
||||
return Err(bad(C, format!("object {} has no bounds to rotate", id.0)));
|
||||
}
|
||||
continue;
|
||||
};
|
||||
let mut xf = Affine::IDENTITY;
|
||||
if let Some(q) = &wanted {
|
||||
let mut q = q.clone();
|
||||
q["reference"] = json!(reference);
|
||||
q["strokes"] = json!(strokes);
|
||||
xf = object_bounds_transform(s, &q, id)?;
|
||||
}
|
||||
if turn.abs() > 1e-9 {
|
||||
// Rotation uses the reference point that sizing keeps in place.
|
||||
let at = b.to_doc() * vectorcraft_geom::reference_point(b.rect, reference as usize);
|
||||
xf = Affine::rotate_about(-turn.to_radians(), at) * xf;
|
||||
}
|
||||
if wanted.is_some() {
|
||||
let sc = scaling(s, &json!({ "strokes": strokes }));
|
||||
let d = &s.doc()?.doc;
|
||||
let symbols = d.symbol_boxes();
|
||||
let measure = |xf| {
|
||||
d.node(id).and_then(|n| {
|
||||
let mut n = n.clone();
|
||||
transform_node(&mut n, xf, sc, true);
|
||||
let frame = OrientedBox { angle: n.bbox_angle, rect: Rect::ZERO };
|
||||
effects::preview::bounds_in_with(&symbols, &n, frame.to_doc().inverse(), s.bounds_measure())
|
||||
})
|
||||
};
|
||||
let misses = |measured: Option<Rect>| {
|
||||
measured.is_none_or(|r| match size {
|
||||
"width" => (r.width() - w).abs() > 1e-6,
|
||||
"height" => (r.height() - h).abs() > 1e-6,
|
||||
_ => (r.width() - w).abs() > 1e-6 || (r.height() - h).abs() > 1e-6,
|
||||
})
|
||||
};
|
||||
// The sized and turned object, measured in its final frame, must have the size asked for.
|
||||
if misses(measure(xf)) {
|
||||
return Err(bad(C, format!("object {} can't take the requested size", id.0)));
|
||||
}
|
||||
}
|
||||
xfs.push((id, xf));
|
||||
}
|
||||
let still = |xf: &Affine| xf.as_coeffs().iter().zip(Affine::IDENTITY.as_coeffs()).all(|(a, b)| (a - b).abs() <= 1e-9);
|
||||
xfs.retain(|(_, xf)| !still(xf));
|
||||
let restack = stacking && !stacked_above(&s.doc()?.doc, source, &targets);
|
||||
let (mut placed, mut left) = (vec![], vec![]);
|
||||
if restack {
|
||||
let d = &s.doc()?.doc;
|
||||
// In a clip group or a clipping layer the bottom child is the clipping path: it stays there.
|
||||
let is_clip =
|
||||
|id: &NodeId| d.position(*id).is_some_and(|(_, idx, _)| idx == 0) && d.parent_of(*id).and_then(|p| d.node(p)).is_some_and(Node::clips);
|
||||
if targets.iter().any(is_clip) {
|
||||
return Err(bad(C, "a clipping path can't change its place in the stacking order"));
|
||||
}
|
||||
let parent = d.parent_of(source);
|
||||
if let Some(what) = targets.iter().filter_map(|id| d.node(*id)).find_map(|n| crate::cmd::intertwine::refused_in(d, parent, n)) {
|
||||
return Err(bad(C, format!("{what} can't be intertwined")));
|
||||
}
|
||||
placed = targets.iter().map(|i| (*i, d.parent_of(*i))).collect::<Vec<(NodeId, Option<NodeId>)>>();
|
||||
left = crate::cmd::intertwine::groups_of(d, &targets);
|
||||
}
|
||||
let count = json!({ "source": source.0, "count": targets.len() });
|
||||
if xfs.is_empty() && !restack {
|
||||
return Ok(count);
|
||||
}
|
||||
let q = json!({ "strokes": strokes, "patterns": patterns });
|
||||
let ids: Vec<NodeId> = xfs.iter().map(|(id, _)| *id).collect();
|
||||
let mut sc = scaling(s, &q);
|
||||
sc.patterns = transform_patterns(s, &q, &ids)?;
|
||||
s.edit("Match Objects", |d, _| {
|
||||
for (id, xf) in &xfs {
|
||||
if let Some(n) = d.node_mut(*id) {
|
||||
transform_node(n, *xf, sc, true);
|
||||
}
|
||||
}
|
||||
if restack {
|
||||
let moved = d.remove_many(&targets)?;
|
||||
d.insert_beside(vec![(source, moved.into_iter().map(Arc::unwrap_or_clone).collect())], false)?;
|
||||
// Targets moved out of an Intertwine group leave it as ordinary art.
|
||||
crate::cmd::intertwine::settle_members(d, &placed, &left)?;
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(count)
|
||||
}
|
||||
|
||||
/// The sets of two or more of `items` (each in the order given) whose rects overlap or touch,
|
||||
/// chains included, among items of the same key (parent). A sweep along x: only the rects still
|
||||
/// open where each one starts are compared with it.
|
||||
@@ -459,7 +675,7 @@ fn sort(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let order = choice(p, C, "order", &["ascending", "descending", "random"])?.unwrap_or("ascending");
|
||||
let distribute = switch_or(p, "distribute", false, C)?;
|
||||
let mut rng = Rng::new(whole_or(p, "seed", 0, C)?);
|
||||
let strokes = switch_or(p, "scaleStrokes", s.prefs.scale_strokes, C)?;
|
||||
let strokes = scale_strokes(s, p, C)?;
|
||||
let ids = checked_ids_or_selection(s, p, C)?;
|
||||
if ids.len() > MAX_OBJECTS {
|
||||
return Err(bad(C, "too many objects selected (at most 20000)"));
|
||||
|
||||
@@ -106,6 +106,134 @@ fn grid_measures_visual_bounds() {
|
||||
assert!(near(bounds(&s, b), (24.0, 0.0, 20.0, 20.0)), "{:?}", bounds(&s, b));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn offset_chains_a_row_in_stacking_order_from_the_first_in_place() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 100.0, 50.0, 20.0, 10.0);
|
||||
let b = rect(&mut s, 0.0, 200.0, 40.0, 30.0);
|
||||
let c = rect(&mut s, 300.0, 0.0, 10.0, 10.0);
|
||||
select(&mut s, &[c, a, b]);
|
||||
let n = steps(&s);
|
||||
let r = s.execute("addon.arrange.offset", &json!({"gap": 5})).unwrap();
|
||||
assert_eq!(r["count"], json!(3));
|
||||
assert_eq!(steps(&s), n + 1, "one undo step");
|
||||
// From the back: a stays, b starts 5 past a's right edge, c 5 past b's; each keeps its y.
|
||||
assert!(near(bounds(&s, a), (100.0, 50.0, 20.0, 10.0)), "{:?}", bounds(&s, a));
|
||||
assert!(near(bounds(&s, b), (125.0, 200.0, 40.0, 30.0)), "{:?}", bounds(&s, b));
|
||||
assert!(near(bounds(&s, c), (170.0, 0.0, 10.0, 10.0)), "{:?}", bounds(&s, c));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(near(bounds(&s, b), (0.0, 200.0, 40.0, 30.0)));
|
||||
assert!(near(bounds(&s, c), (300.0, 0.0, 10.0, 10.0)));
|
||||
// Reversed: c stays, then b, then a. The gap defaults to 10.
|
||||
s.execute("addon.arrange.offset", &json!({"reverse": true})).unwrap();
|
||||
assert!(near(bounds(&s, c), (300.0, 0.0, 10.0, 10.0)), "{:?}", bounds(&s, c));
|
||||
assert!(near(bounds(&s, b), (320.0, 200.0, 40.0, 30.0)), "{:?}", bounds(&s, b));
|
||||
assert!(near(bounds(&s, a), (370.0, 50.0, 20.0, 10.0)), "{:?}", bounds(&s, a));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn offset_chains_a_column_by_position_either_way_and_overlaps_with_a_negative_gap() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 100.0, 10.0, 20.0);
|
||||
let b = rect(&mut s, 50.0, 0.0, 10.0, 10.0);
|
||||
let c = rect(&mut s, 100.0, 40.0, 10.0, 30.0);
|
||||
select(&mut s, &[a, b, c]);
|
||||
// Top to bottom: b, c, a; each 5 into the one before it, keeping its x.
|
||||
s.execute("addon.arrange.offset", &json!({"direction": "column", "order": "position", "gap": -5})).unwrap();
|
||||
assert!(near(bounds(&s, b), (50.0, 0.0, 10.0, 10.0)), "{:?}", bounds(&s, b));
|
||||
assert!(near(bounds(&s, c), (100.0, 5.0, 10.0, 30.0)), "{:?}", bounds(&s, c));
|
||||
assert!(near(bounds(&s, a), (0.0, 30.0, 10.0, 20.0)), "{:?}", bounds(&s, a));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
// Bottom to top: a stays, then c, then b.
|
||||
s.execute("addon.arrange.offset", &json!({"direction": "column", "order": "position", "reverse": true, "gap": 0})).unwrap();
|
||||
assert!(near(bounds(&s, a), (0.0, 100.0, 10.0, 20.0)), "{:?}", bounds(&s, a));
|
||||
assert!(near(bounds(&s, c), (100.0, 120.0, 10.0, 30.0)), "{:?}", bounds(&s, c));
|
||||
assert!(near(bounds(&s, b), (50.0, 150.0, 10.0, 10.0)), "{:?}", bounds(&s, b));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
// Left to right in a row: a, b, c.
|
||||
s.execute("addon.arrange.offset", &json!({"order": "position", "gap": 1})).unwrap();
|
||||
assert!(near(bounds(&s, a), (0.0, 100.0, 10.0, 20.0)), "{:?}", bounds(&s, a));
|
||||
assert!(near(bounds(&s, b), (11.0, 0.0, 10.0, 10.0)), "{:?}", bounds(&s, b));
|
||||
assert!(near(bounds(&s, c), (22.0, 40.0, 10.0, 30.0)), "{:?}", bounds(&s, c));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn offset_measures_visual_bounds_and_clipping_groups_by_their_mask() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0);
|
||||
let b = rect(&mut s, 100.0, 0.0, 20.0, 20.0);
|
||||
select(&mut s, &[a, b]);
|
||||
s.execute("paint.setStroke", &json!({"color": "#000000"})).unwrap();
|
||||
s.execute("stroke.set", &json!({"weight": 4})).unwrap();
|
||||
s.execute("addon.arrange.offset", &json!({"gap": 0})).unwrap();
|
||||
// Visual boxes 24 wide, touching.
|
||||
assert!(near(bounds(&s, b), (24.0, 0.0, 20.0, 20.0)), "{:?}", bounds(&s, b));
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0);
|
||||
// A 200 wide object clipped to a 30 wide mask at x 100.
|
||||
let clipped = rect(&mut s, 50.0, 50.0, 200.0, 10.0);
|
||||
let mask = rect(&mut s, 100.0, 40.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 c = rect(&mut s, 300.0, 0.0, 10.0, 10.0);
|
||||
select(&mut s, &[a, group, c]);
|
||||
s.execute("addon.arrange.offset", &json!({"gap": 0})).unwrap();
|
||||
// The mask starts at a's right edge, and c at the mask's.
|
||||
assert!(near(bounds(&s, mask), (20.0, 40.0, 30.0, 30.0)), "{:?}", bounds(&s, mask));
|
||||
assert!(near(bounds(&s, clipped), (-30.0, 50.0, 200.0, 10.0)), "{:?}", bounds(&s, clipped));
|
||||
assert!(near(bounds(&s, c), (50.0, 0.0, 10.0, 10.0)), "{:?}", bounds(&s, c));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn offset_makes_no_step_when_nothing_moves_and_skips_locked_objects() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0);
|
||||
let b = rect(&mut s, 30.0, 50.0, 20.0, 20.0);
|
||||
select(&mut s, &[a]);
|
||||
assert!(!enabled(&s, "addon.arrange.offset"), "off with one object");
|
||||
select(&mut s, &[a, b]);
|
||||
assert!(enabled(&s, "addon.arrange.offset"));
|
||||
// Already 10 apart in a row.
|
||||
let n = steps(&s);
|
||||
s.execute("addon.arrange.offset", &json!({})).unwrap();
|
||||
assert_eq!(steps(&s), n, "no step when nothing moves");
|
||||
// Two objects in one group are one object: nothing to chain.
|
||||
s.execute("object.group", &json!({})).unwrap();
|
||||
s.execute("select.all", &json!({})).unwrap();
|
||||
assert!(!enabled(&s, "addon.arrange.offset"), "off with one group");
|
||||
refuses(&mut s, "addon.arrange.offset", &[json!({"gap": 50})]);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
let c = rect(&mut s, 200.0, 200.0, 10.0, 10.0);
|
||||
select(&mut s, &[b]);
|
||||
s.execute("object.lock", &json!({})).unwrap();
|
||||
s.execute("select.all", &json!({})).unwrap();
|
||||
s.execute("addon.arrange.offset", &json!({"gap": 0})).unwrap();
|
||||
assert!(near(bounds(&s, b), (30.0, 50.0, 20.0, 20.0)), "the locked object stays, {:?}", bounds(&s, b));
|
||||
assert!(near(bounds(&s, c), (20.0, 200.0, 10.0, 10.0)), "{:?}", bounds(&s, c));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn offset_refuses_bad_params() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 20.0, 10.0);
|
||||
let b = rect(&mut s, 100.0, 100.0, 40.0, 40.0);
|
||||
select(&mut s, &[a, b]);
|
||||
refuses(
|
||||
&mut s,
|
||||
"addon.arrange.offset",
|
||||
&[
|
||||
json!({"direction": "diagonal"}),
|
||||
json!({"direction": 1}),
|
||||
json!({"gap": 1e7}),
|
||||
json!({"gap": -1e7}),
|
||||
json!({"gap": "10"}),
|
||||
json!({"order": "size"}),
|
||||
json!({"reverse": "yes"}),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn swap_trades_places_and_optionally_sizes() {
|
||||
let mut s = session();
|
||||
@@ -215,6 +343,394 @@ fn size_gives_each_object_a_width_and_height() {
|
||||
assert!(near(bounds(&s, a), (30.0, 8.0, 10.0, 12.0)), "both given: both set, {:?}", bounds(&s, a));
|
||||
}
|
||||
|
||||
/// Three rectangles from the back, all selected: `a` 20 × 10 at the origin, `b` 40 × 40 at
|
||||
/// (100, 100) and `c` 10 × 30 at (200, 0).
|
||||
fn three(s: &mut Session) -> (NodeId, NodeId, NodeId) {
|
||||
let a = rect(s, 0.0, 0.0, 20.0, 10.0);
|
||||
let b = rect(s, 100.0, 100.0, 40.0, 40.0);
|
||||
let c = rect(s, 200.0, 0.0, 10.0, 30.0);
|
||||
select(s, &[a, b, c]);
|
||||
(a, b, c)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_gives_the_others_the_key_objects_size() {
|
||||
let mut s = session();
|
||||
let (a, b, c) = three(&mut s);
|
||||
s.execute("select.key", &json!({"id": b.0})).unwrap();
|
||||
let n = steps(&s);
|
||||
let r = s.execute("addon.arrange.match", &json!({"size": "both"})).unwrap();
|
||||
assert_eq!(r, json!({"source": b.0, "count": 2}));
|
||||
assert_eq!(steps(&s), n + 1, "one undo step");
|
||||
// About each center; the key object stays.
|
||||
assert!(near(bounds(&s, a), (-10.0, -15.0, 40.0, 40.0)), "{:?}", bounds(&s, a));
|
||||
assert!(near(bounds(&s, c), (185.0, -5.0, 40.0, 40.0)), "{:?}", bounds(&s, c));
|
||||
assert!(near(bounds(&s, b), (100.0, 100.0, 40.0, 40.0)), "{:?}", bounds(&s, b));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(near(bounds(&s, a), (0.0, 0.0, 20.0, 10.0)));
|
||||
// The width, with the height in proportion, about the top-left corner.
|
||||
s.execute("addon.arrange.match", &json!({"size": "width", "reference": 0})).unwrap();
|
||||
assert!(near(bounds(&s, a), (0.0, 0.0, 40.0, 20.0)), "{:?}", bounds(&s, a));
|
||||
assert!(near(bounds(&s, c), (200.0, 0.0, 40.0, 120.0)), "{:?}", bounds(&s, c));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("addon.arrange.match", &json!({"size": "height", "reference": 8})).unwrap();
|
||||
assert!(near(bounds(&s, a), (-60.0, -30.0, 80.0, 40.0)), "{:?}", bounds(&s, a));
|
||||
assert!(near(bounds(&s, c), (196.6666666666667, -10.0, 13.333333333333334, 40.0)), "{:?}", bounds(&s, c));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_takes_the_top_or_the_bottom_object_without_a_key() {
|
||||
let mut s = session();
|
||||
let (a, b, c) = three(&mut s);
|
||||
// No key object: the frontmost, c.
|
||||
let r = s.execute("addon.arrange.match", &json!({"size": "both"})).unwrap();
|
||||
assert_eq!(r["source"], json!(c.0));
|
||||
assert!(near(bounds(&s, a), (5.0, -10.0, 10.0, 30.0)), "{:?}", bounds(&s, a));
|
||||
assert!(near(bounds(&s, b), (115.0, 105.0, 10.0, 30.0)), "{:?}", bounds(&s, b));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
let r = s.execute("addon.arrange.match", &json!({"source": "bottom", "size": "both"})).unwrap();
|
||||
assert_eq!(r["source"], json!(a.0));
|
||||
assert!(near(bounds(&s, b), (110.0, 115.0, 20.0, 10.0)), "{:?}", bounds(&s, b));
|
||||
assert!(near(bounds(&s, c), (195.0, 10.0, 20.0, 10.0)), "{:?}", bounds(&s, c));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
// "top" names the frontmost even while a key object is set.
|
||||
s.execute("select.key", &json!({"id": a.0})).unwrap();
|
||||
let r = s.execute("addon.arrange.match", &json!({"source": "top", "size": "both"})).unwrap();
|
||||
assert_eq!(r["source"], json!(c.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_turns_the_others_to_the_sources_angle() {
|
||||
let mut s = session();
|
||||
let (a, b, c) = three(&mut s);
|
||||
select(&mut s, &[b]);
|
||||
s.execute("object.rotate", &json!({"angle": 30})).unwrap();
|
||||
select(&mut s, &[a, b, c]);
|
||||
s.execute("select.key", &json!({"id": b.0})).unwrap();
|
||||
let n = steps(&s);
|
||||
s.execute("addon.arrange.match", &json!({"rotate": true, "size": "both"})).unwrap();
|
||||
assert_eq!(steps(&s), n + 1, "one undo step");
|
||||
for (id, center) in [(a, (10.0, 5.0)), (c, (205.0, 15.0))] {
|
||||
let o = s.transform_box(&[id]).unwrap();
|
||||
assert!((o.angle - 30.0).abs() < 1e-6, "{id:?} turned to {}", o.angle);
|
||||
assert!((o.rect.width() - 40.0).abs() < 1e-6 && (o.rect.height() - 40.0).abs() < 1e-6, "{id:?} sized {:?}", o.rect);
|
||||
let at = o.center();
|
||||
assert!((at.x - center.0).abs() < 1e-6 && (at.y - center.1).abs() < 1e-6, "{id:?} turned about its center: {at:?}");
|
||||
}
|
||||
// Turned back to the angle of an unturned source.
|
||||
let d = rect(&mut s, 300.0, 0.0, 10.0, 10.0);
|
||||
select(&mut s, &[a, d]);
|
||||
s.execute("addon.arrange.match", &json!({"rotate": true, "source": "top"})).unwrap();
|
||||
assert!(s.transform_box(&[a]).unwrap().angle.abs() < 1e-6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_size_and_rotation_measure_pixel_aligned_art_in_its_final_frame() {
|
||||
for size in ["width", "height", "both"] {
|
||||
let mut s = session();
|
||||
let target = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
|
||||
select(&mut s, &[target]);
|
||||
s.execute("object.setPixelAligned", &json!({"on": true})).unwrap();
|
||||
let source = rect(&mut s, 100.0, 0.0, 10.5, 10.5);
|
||||
select(&mut s, &[source]);
|
||||
s.execute("object.rotate", &json!({"angle": 30})).unwrap();
|
||||
let wanted = s.transform_box(&[source]).unwrap();
|
||||
select(&mut s, &[target, source]);
|
||||
s.execute("select.key", &json!({"id": source.0})).unwrap();
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let n = steps(&s);
|
||||
let r = s.execute("addon.arrange.match", &json!({"size": size, "rotate": true})).unwrap();
|
||||
assert_eq!(r, json!({"source": source.0, "count": 1}));
|
||||
let measured = s.transform_box(&[target]).unwrap();
|
||||
assert!((measured.angle - wanted.angle).abs() < 1e-6, "{size}: {measured:?}");
|
||||
assert!((measured.rect.width() - wanted.rect.width()).abs() < 1e-6, "{size}: {measured:?}");
|
||||
assert!((measured.rect.height() - wanted.rect.height()).abs() < 1e-6, "{size}: {measured:?}");
|
||||
assert_eq!(steps(&s), n + 1);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(*s.doc().unwrap().doc == *before);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_rotation_refuses_a_target_without_bounds_when_its_angle_differs() {
|
||||
for angle in [0, 30] {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
|
||||
let target = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
select(&mut s, &[a]);
|
||||
s.execute("edit.clear", &json!({})).unwrap();
|
||||
let b = rect(&mut s, 100.0, 0.0, 10.0, 10.0);
|
||||
let source = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("object.rotate", &json!({"angle": angle})).unwrap();
|
||||
select(&mut s, &[b]);
|
||||
s.execute("edit.clear", &json!({})).unwrap();
|
||||
assert!(s.transform_box(&[target]).is_none());
|
||||
assert!(s.transform_box(&[source]).is_none());
|
||||
assert!((s.doc().unwrap().doc.bbox_angle(&[source]) - f64::from(angle)).abs() < 1e-6);
|
||||
select(&mut s, &[target, source]);
|
||||
s.execute("select.key", &json!({"id": source.0})).unwrap();
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let n = steps(&s);
|
||||
let result = s.execute("addon.arrange.match", &json!({"rotate": true}));
|
||||
if angle == 0 {
|
||||
assert_eq!(result.unwrap(), json!({"source": source.0, "count": 1}));
|
||||
} else {
|
||||
let error = result.unwrap_err().to_string();
|
||||
assert!(error.contains(&format!("object {} has no bounds to rotate", target.0)), "{error}");
|
||||
}
|
||||
assert_eq!(steps(&s), n);
|
||||
assert!(*s.doc().unwrap().doc == *before);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_puts_the_others_directly_above_the_source() {
|
||||
let mut s = session();
|
||||
let (a, b, c) = three(&mut s);
|
||||
let d = rect(&mut s, 300.0, 0.0, 10.0, 10.0);
|
||||
select(&mut s, &[d, a, c]);
|
||||
s.execute("select.key", &json!({"id": a.0})).unwrap();
|
||||
let n = steps(&s);
|
||||
s.execute("addon.arrange.match", &json!({"stacking": true})).unwrap();
|
||||
assert_eq!(steps(&s), n + 1, "one undo step");
|
||||
assert_eq!(layer_order(&s), [a, c, d, b], "in the order they had, above the key object");
|
||||
assert!(near(bounds(&s, c), (200.0, 0.0, 10.0, 30.0)), "nothing else changes");
|
||||
s.execute("addon.arrange.match", &json!({"stacking": true})).unwrap();
|
||||
assert_eq!(steps(&s), n + 1, "already above it: no step");
|
||||
// An object in another layer goes into the source's.
|
||||
s.execute("layer.new", &json!({})).unwrap();
|
||||
let e = rect(&mut s, 0.0, 200.0, 10.0, 10.0);
|
||||
select(&mut s, &[b, e]);
|
||||
s.execute("select.key", &json!({"id": b.0})).unwrap();
|
||||
s.execute("addon.arrange.match", &json!({"stacking": true})).unwrap();
|
||||
assert_eq!(layer_order(&s), [a, c, d, b, e]);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(layer_order(&s), [a, c, d, b]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_makes_no_step_when_everything_matches() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 20.0, 10.0);
|
||||
let b = rect(&mut s, 100.0, 100.0, 20.0, 10.0);
|
||||
select(&mut s, &[a, b]);
|
||||
let n = steps(&s);
|
||||
let r = s.execute("addon.arrange.match", &json!({"size": "both", "rotate": true})).unwrap();
|
||||
assert_eq!(r["count"], json!(1));
|
||||
assert_eq!(steps(&s), n, "the same size and angle: no step");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_turns_the_others_about_their_reference_point() {
|
||||
let mut s = session();
|
||||
let (a, b, c) = three(&mut s);
|
||||
select(&mut s, &[b]);
|
||||
s.execute("object.rotate", &json!({"angle": 30})).unwrap();
|
||||
select(&mut s, &[a, b, c]);
|
||||
s.execute("select.key", &json!({"id": b.0})).unwrap();
|
||||
s.execute("addon.arrange.match", &json!({"rotate": true, "reference": 0})).unwrap();
|
||||
// Each top-left corner stays where it was.
|
||||
for (id, corner) in [(a, (0.0, 0.0)), (c, (200.0, 0.0))] {
|
||||
let o = s.transform_box(&[id]).unwrap();
|
||||
assert!((o.angle - 30.0).abs() < 1e-6, "{id:?} turned to {}", o.angle);
|
||||
let at = o.to_doc() * vectorcraft_geom::reference_point(o.rect, 0);
|
||||
assert!((at.x - corner.0).abs() < 1e-6 && (at.y - corner.1).abs() < 1e-6, "{id:?} turned about its top-left corner: {at:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_scales_strokes_as_asked() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
|
||||
let b = rect(&mut s, 100.0, 0.0, 20.0, 20.0);
|
||||
select(&mut s, &[a, b]);
|
||||
s.execute("paint.setStroke", &json!({"color": "#000000"})).unwrap();
|
||||
s.execute("stroke.set", &json!({"weight": 2})).unwrap();
|
||||
let weight = |s: &Session, id| s.doc().unwrap().doc.node(id).unwrap().appearance.stroke_width();
|
||||
s.execute("addon.arrange.match", &json!({"size": "both"})).unwrap();
|
||||
assert_eq!(weight(&s, a), 2.0, "off by default (the preference)");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("addon.arrange.match", &json!({"size": "both", "scaleStrokes": true})).unwrap();
|
||||
assert!((weight(&s, a) - 4.0).abs() < 1e-9, "{}", weight(&s, a));
|
||||
assert!(near(bounds(&s, a), (-5.0, -5.0, 20.0, 20.0)), "{:?}", bounds(&s, a));
|
||||
}
|
||||
|
||||
/// Running `cmd` with Scale Strokes & Effects on doubles the 2 pt stroke of a 10 pt square, and
|
||||
/// replaying its journal entry after the preference is turned off scales the stroke the same way.
|
||||
fn replays_the_stroke_scaling_it_ran_with(cmd: &str, p: Value) {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
|
||||
let b = rect(&mut s, 100.0, 0.0, 20.0, 20.0);
|
||||
select(&mut s, &[a, b]);
|
||||
s.execute("paint.setStroke", &json!({"color": "#000000"})).unwrap();
|
||||
s.execute("stroke.set", &json!({"weight": 2})).unwrap();
|
||||
let weight = |s: &Session| s.doc().unwrap().doc.node(a).unwrap().appearance.stroke_width();
|
||||
s.execute("prefs.set", &json!({"key": "scaleStrokes", "value": true})).unwrap();
|
||||
s.execute(cmd, &p).unwrap();
|
||||
assert!((weight(&s) - 4.0).abs() < 1e-9, "{cmd}: {}", weight(&s));
|
||||
let (id, q) = s.journal.last().unwrap().clone();
|
||||
assert_eq!(id, cmd);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("prefs.set", &json!({"key": "scaleStrokes", "value": false})).unwrap();
|
||||
select(&mut s, &[a, b]);
|
||||
s.replay(&id, &q).unwrap();
|
||||
assert!((weight(&s) - 4.0).abs() < 1e-9, "{cmd} replayed: {}", weight(&s));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_stacking_leaves_a_clipping_path_in_place() {
|
||||
let mut s = session();
|
||||
let art = rect(&mut s, 0.0, 0.0, 40.0, 40.0);
|
||||
let mask = rect(&mut s, 10.0, 10.0, 10.0, 10.0);
|
||||
select(&mut s, &[art, mask]);
|
||||
s.execute("object.clippingMask.make", &json!({})).unwrap();
|
||||
let x = rect(&mut s, 200.0, 0.0, 10.0, 10.0);
|
||||
select(&mut s, &[mask, x]);
|
||||
s.execute("select.key", &json!({"id": x.0})).unwrap();
|
||||
refuses(&mut s, "addon.arrange.match", &[json!({"stacking": true})]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_size_refuses_a_target_with_no_width() {
|
||||
let mut s = session();
|
||||
let line = NodeId(s.execute("shape.line", &json!({"x1": 0, "y1": 0, "x2": 0, "y2": 50})).unwrap()["id"].as_u64().unwrap());
|
||||
let b = rect(&mut s, 100.0, 0.0, 20.0, 20.0);
|
||||
select(&mut s, &[line, b]);
|
||||
s.execute("select.key", &json!({"id": b.0})).unwrap();
|
||||
refuses(&mut s, "addon.arrange.match", &[json!({"size": "width"}), json!({"size": "both"})]);
|
||||
// Its height can still take the source's.
|
||||
s.execute("addon.arrange.match", &json!({"size": "height"})).unwrap();
|
||||
assert!((bounds(&s, line).height() - 20.0).abs() < 1e-6, "{:?}", bounds(&s, line));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_size_uses_preview_bounds_for_a_target_with_no_geometric_width() {
|
||||
let mut s = session();
|
||||
s.execute("prefs.set", &json!({"key": "usePreviewBounds", "value": true})).unwrap();
|
||||
let line = NodeId(s.execute("shape.line", &json!({"x1": 0, "y1": 0, "x2": 0, "y2": 50})).unwrap()["id"].as_u64().unwrap());
|
||||
select(&mut s, &[line]);
|
||||
s.execute("paint.setStroke", &json!({"color": "#000000"})).unwrap();
|
||||
s.execute("stroke.set", &json!({"weight": 2, "cap": "butt"})).unwrap();
|
||||
let b = rect(&mut s, 100.0, 0.0, 2.0, 100.0);
|
||||
select(&mut s, &[b]);
|
||||
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
|
||||
select(&mut s, &[line, b]);
|
||||
s.execute("select.key", &json!({"id": b.0})).unwrap();
|
||||
s.execute("addon.arrange.match", &json!({"size": "both", "scaleStrokes": false})).unwrap();
|
||||
let measured = s.transform_box(&[line]).unwrap().rect;
|
||||
let wanted = s.transform_box(&[b]).unwrap().rect;
|
||||
assert!((measured.width() - wanted.width()).abs() < 1e-6, "{measured:?}");
|
||||
assert!((measured.height() - wanted.height()).abs() < 1e-6, "{measured:?}");
|
||||
select(&mut s, &[b]);
|
||||
s.execute("object.setBounds", &json!({"width": 4})).unwrap();
|
||||
select(&mut s, &[line, b]);
|
||||
s.execute("select.key", &json!({"id": b.0})).unwrap();
|
||||
refuses(&mut s, "addon.arrange.match", &[json!({"size": "both", "scaleStrokes": false})]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_stacking_takes_a_member_out_of_its_intertwine_group() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 40.0, 40.0);
|
||||
let b = rect(&mut s, 20.0, 20.0, 40.0, 40.0);
|
||||
select(&mut s, &[a, b]);
|
||||
let g = NodeId(s.execute("object.intertwine.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("object.intertwine.arrange", &json!({"at": [30, 30], "order": "front", "member": a.0})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.node(a).unwrap().extras().intertwine.is_some(), "a is drawn over b in their overlap");
|
||||
let c = rect(&mut s, 200.0, 0.0, 10.0, 10.0);
|
||||
select(&mut s, &[a, c]);
|
||||
s.execute("select.key", &json!({"id": c.0})).unwrap();
|
||||
s.execute("addon.arrange.match", &json!({"stacking": true})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_ne!(d.parent_of(a), Some(g), "a left the Intertwine group");
|
||||
let e = d.node(a).unwrap().extras();
|
||||
assert!(e.intertwine.is_none() && e.intertwine_tiers.is_empty(), "a keeps no Intertwine areas");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(a), Some(g), "undo puts a back in its group");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_stacking_needs_no_bounds_on_the_source() {
|
||||
let mut s = session();
|
||||
let b = rect(&mut s, 100.0, 0.0, 20.0, 20.0);
|
||||
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
|
||||
let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
|
||||
s.execute("edit.clear", &json!({})).unwrap();
|
||||
select(&mut s, &[b, g]);
|
||||
s.execute("select.key", &json!({"id": g.0})).unwrap();
|
||||
s.execute("addon.arrange.match", &json!({"stacking": true})).unwrap();
|
||||
assert_eq!(layer_order(&s), [g, b], "b goes directly above the empty group");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_stacking_refuses_intertwine_nesting_beside_an_empty_group() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 40.0, 40.0);
|
||||
let source = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
let b = rect(&mut s, 20.0, 20.0, 40.0, 40.0);
|
||||
select(&mut s, &[source, b]);
|
||||
let parent = NodeId(s.execute("object.intertwine.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
select(&mut s, &[a]);
|
||||
s.execute("edit.clear", &json!({})).unwrap();
|
||||
assert!(s.transform_box(&[source]).is_none());
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(source), Some(parent));
|
||||
let c = rect(&mut s, 100.0, 0.0, 40.0, 40.0);
|
||||
let d = rect(&mut s, 120.0, 20.0, 40.0, 40.0);
|
||||
select(&mut s, &[c, d]);
|
||||
let target = NodeId(s.execute("object.intertwine.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
select(&mut s, &[source, target]);
|
||||
s.execute("select.key", &json!({"id": source.0})).unwrap();
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let n = steps(&s);
|
||||
let error = s.execute("addon.arrange.match", &json!({"stacking": true})).unwrap_err().to_string();
|
||||
assert!(error.contains("can't be intertwined"), "{error}");
|
||||
assert_eq!(steps(&s), n);
|
||||
assert!(*s.doc().unwrap().doc == *before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_replays_with_the_stroke_scaling_it_ran_with() {
|
||||
replays_the_stroke_scaling_it_ran_with("addon.arrange.match", json!({"size": "both"}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_size_of_each_replays_with_the_stroke_scaling_it_ran_with() {
|
||||
replays_the_stroke_scaling_it_ran_with("addon.arrange.size", json!({"width": 20, "height": 20}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn swap_replays_with_the_stroke_scaling_it_ran_with() {
|
||||
replays_the_stroke_scaling_it_ran_with("addon.arrange.swap", json!({"size": true}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_refuses_bad_params() {
|
||||
let mut s = session();
|
||||
let (a, _, _) = three(&mut s);
|
||||
refuses(
|
||||
&mut s,
|
||||
"addon.arrange.match",
|
||||
&[
|
||||
json!({}),
|
||||
json!({"size": "none"}),
|
||||
json!({"size": "area"}),
|
||||
json!({"size": 1}),
|
||||
json!({"rotate": 1}),
|
||||
json!({"stacking": "yes"}),
|
||||
json!({"size": "both", "reference": 9}),
|
||||
json!({"size": "both", "reference": 1.5}),
|
||||
json!({"size": "both", "source": "left"}),
|
||||
json!({"size": "both", "scaleStrokes": "no"}),
|
||||
json!({"size": "both", "patterns": 0}),
|
||||
],
|
||||
);
|
||||
let e = s.execute("addon.arrange.match", &json!({"source": "key", "rotate": true})).unwrap_err().to_string();
|
||||
assert!(e.contains("no key object"), "{e}");
|
||||
select(&mut s, &[a]);
|
||||
assert!(!enabled(&s, "addon.arrange.match"), "one object selected");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_params_are_refused() {
|
||||
let mut s = session();
|
||||
@@ -261,6 +777,7 @@ fn off_without_a_selection() {
|
||||
"addon.arrange.swap",
|
||||
"addon.arrange.replace",
|
||||
"addon.arrange.size",
|
||||
"addon.arrange.match",
|
||||
"addon.arrange.groupOverlapping",
|
||||
"addon.arrange.randomizeOpacity",
|
||||
"addon.arrange.sort",
|
||||
|
||||
@@ -14,7 +14,7 @@ use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::color_mask::{ColorMask, MaskBackground, MaskMatch};
|
||||
use vectorcraft_doc::{Document, ImageBlob, Node, NodeId, NodeKind};
|
||||
use vectorcraft_doc::{Document, ImageBlob, Node, NodeId, NodeKind, changed_nodes};
|
||||
use vectorcraft_geom::Affine;
|
||||
|
||||
use super::super::super::paint::{PROCESS_ON_TRANSPARENCY, colorized_with_process};
|
||||
@@ -367,14 +367,7 @@ fn stale_in(doc: &Document, n: &Arc<Node>, old: Option<&Arc<Node>>) -> bool {
|
||||
}
|
||||
let Some(children) = n.children() else { return false };
|
||||
let before = old.and_then(|o| o.children()).map_or(&[][..], Vec::as_slice);
|
||||
let mut by_id: Option<HashMap<NodeId, &Arc<Node>>> = None;
|
||||
children.iter().enumerate().any(|(i, c)| {
|
||||
let b = match before.get(i) {
|
||||
Some(b) if b.id == c.id => Some(b),
|
||||
_ => by_id.get_or_insert_with(|| before.iter().map(|b| (b.id, b)).collect()).get(&c.id).copied(),
|
||||
};
|
||||
stale_in(doc, c, b)
|
||||
})
|
||||
changed_nodes(before, children).any(|(_, c, b)| stale_in(doc, c, b))
|
||||
}
|
||||
|
||||
/// Whether `n` is an image whose color mask was not made from its own pixels (or whose masked
|
||||
|
||||
@@ -225,7 +225,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Symbol Options…",
|
||||
[],
|
||||
None,
|
||||
"{name?, newName?, registration?: 0..8, exportType?: movieClip|graphic, nineSlice?: bool, nineSliceGuides?: array, type?: static|dynamic, alignToPixelGrid?: bool} rename a symbol (its instances and the graphics and Map Art maps on 3D objects follow the new name) and/or set Symbol Options › Registration, Export Type, 9-slice guides (nineSliceGuides [left, top, right, bottom] fractions in from each edge, each -16..16, with left + right < 1 and top + bottom < 1), Symbol Type (a dynamic symbol's instances may change the appearance of objects in its art and stay linked; making it static drops those changes) and Align to Pixel Grid (on: the horizontal and vertical straight segments of the paths in the symbol's art snap to whole points, or half points for an odd centered stroke, at the symbol's natural size, its stroke weights become whole points, and every instance placed at that size, reflected across one axis or not, moves to whole points and goes back to them after each move; a scaled, rotated (a half turn included) or sheared instance, and an instance in another symbol's art, is left where it is; the art snaps again after it is edited); alignToPixelGrid alone with the value the symbol already has changes nothing and adds no undo step; default name: current → {name, registration, exportType, nineSlice, type, alignToPixelGrid}",
|
||||
"{name?, newName?, registration?: 0..8, exportType?: movieClip|graphic, nineSlice?: bool, nineSliceGuides?: array, type?: static|dynamic, alignToPixelGrid?: bool} rename a symbol (its instances and the graphics and Map Art maps on 3D objects follow the new name) and/or set Symbol Options › Registration, Export Type, 9-slice guides (nineSliceGuides [left, top, right, bottom] fractions in from each edge, each -16..16, with left + right < 1 and top + bottom < 1), Symbol Type (a dynamic symbol's instances may change the appearance of objects in its art and stay linked; making it static drops those changes) and Align to Pixel Grid (on: the horizontal and vertical straight segments of the paths in the symbol's art snap to whole points, or half points for an odd centered stroke, at the symbol's natural size, its stroke weights become whole points, and every instance placed at that size, reflected across one axis or not, moves to whole points and goes back to them after each move; a scaled, rotated (a half turn included) or sheared instance, and an instance in another symbol's art, is left where it is; the art snaps again after it is edited); values the symbol already has, newName included, change nothing and add no undo step; default name: current → {name, registration, exportType, nineSlice, type, alignToPixelGrid}",
|
||||
has_doc,
|
||||
symbol_options
|
||||
),
|
||||
@@ -289,7 +289,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Replace Symbol",
|
||||
[],
|
||||
None,
|
||||
"{name, ids?|id?} swap the symbol of the selected instances (an instance given a different symbol drops its appearance changes; one given its own symbol keeps them) → {ids}",
|
||||
"{name, ids?|id?} swap the symbol of the selected instances (an instance given a different symbol drops its appearance changes; one given its own symbol keeps them; when every instance already shows the symbol, nothing changes and no undo step is recorded) → {ids}",
|
||||
has_selection,
|
||||
symbol_replace
|
||||
),
|
||||
|
||||
@@ -347,13 +347,8 @@ pub(super) fn symbol_options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let dynamic = type_param(p, C)?;
|
||||
let pixel = pixel_grid_param(p, C)?;
|
||||
let new_name = str_param(p, "newName").map(str::trim).filter(|n| !n.is_empty()).map(str::to_string);
|
||||
if new_name.is_none() && export.is_none() && reg.is_none() && nine.is_none() && dynamic.is_none() {
|
||||
match pixel {
|
||||
None => return Err(bad(C, "pass newName, registration, exportType, nineSlice, type and/or alignToPixelGrid")),
|
||||
// Align to Pixel Grid alone, already as asked: nothing changes and no undo step is added.
|
||||
Some(on) if on == s.doc()?.doc.symbol_pixel_aligned(&name) => return Ok(options_json(&s.doc()?.doc, &name)),
|
||||
Some(_) => {}
|
||||
}
|
||||
if new_name.is_none() && export.is_none() && reg.is_none() && nine.is_none() && dynamic.is_none() && pixel.is_none() {
|
||||
return Err(bad(C, "pass newName, registration, exportType, nineSlice, type and/or alignToPixelGrid"));
|
||||
}
|
||||
if let Some(ref n) = new_name
|
||||
&& n != &name
|
||||
@@ -362,7 +357,8 @@ pub(super) fn symbol_options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(bad(C, format!("a symbol named `{n}` already exists")));
|
||||
}
|
||||
let final_name = new_name.clone().unwrap_or_else(|| name.clone());
|
||||
s.edit("Symbol Options", |d, _| {
|
||||
// Values the symbol already has leave the document as it is, and no undo step is added.
|
||||
crate::cmd::colorcmds::edit_if_changed(s, "Symbol Options", |before, d| {
|
||||
if let Some(ref n) = new_name
|
||||
&& n != &name
|
||||
{
|
||||
@@ -439,7 +435,7 @@ pub(super) fn symbol_options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if let Some(on) = pixel {
|
||||
d.set_symbol_pixel_aligned(&final_name, on);
|
||||
}
|
||||
Ok(())
|
||||
Ok(((), before != &*d))
|
||||
})?;
|
||||
Ok(options_json(&s.doc()?.doc, &final_name))
|
||||
}
|
||||
@@ -859,7 +855,8 @@ pub(super) fn symbol_replace(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if ids.is_empty() {
|
||||
return Err(EngineError::Other("no symbol instances selected".into()));
|
||||
}
|
||||
s.edit("Replace Symbol", |d, _| {
|
||||
// Instances that already show the symbol leave the document as it is, and no undo step is added.
|
||||
crate::cmd::colorcmds::edit_if_changed(s, "Replace Symbol", |before, d| {
|
||||
let new = natural_size(d, &name);
|
||||
for id in &ids {
|
||||
let (old, other) = match d.node(*id).map(|n| &n.kind) {
|
||||
@@ -877,7 +874,7 @@ pub(super) fn symbol_replace(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
fit_overrides(d, &ids);
|
||||
Ok(())
|
||||
Ok(((), ids.iter().any(|id| before.node(*id) != d.node(*id))))
|
||||
})?;
|
||||
Ok(json!({ "ids": ids_json(&ids) }))
|
||||
}
|
||||
|
||||
@@ -146,18 +146,52 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
always,
|
||||
parse_color
|
||||
),
|
||||
cmd!(
|
||||
query "color.format",
|
||||
"Format Color",
|
||||
[],
|
||||
None,
|
||||
"{color (#rrggbbaa and #rgba are refused), opacity?: 0..100 (100), notation: \"hex\"|\"hexAlpha\"|\"rgb\"|\"hsl\"|\"oklch\"|\"cmyk\"} the color as text → {text}: hex is #rrggbb and hexAlpha #rrggbbaa (ff at 100) of the working RGB numbers, the same numbers the Color panel's hex field shows, in lowercase; rgb, hsl and oklch are CSS Color 4's rgb(), hsl() and oklch() of the same numbers (https://www.w3.org/TR/css-color-4/#rgb-functions, https://www.w3.org/TR/css-color-4/#the-hsl-notation, https://www.w3.org/TR/css-color-4/#specifying-oklab-oklch), each in the space-separated form with ` / opacity%` added when the opacity rounded to two decimal places is under 100 (99.999 writes no suffix), hsl() and oklch() to two decimal places (chroma to four), and oklch() takes up to two more where fewer would read back to another color; cmyk is \"C=0 M=50 Y=100 K=0\", as a new swatch is named, of the color in the working CMYK space through the color settings (a CMYK color keeps its own values); hex and cmyk leave the opacity out. color.parse reads every notation but cmyk back to the same #rrggbb; oklch is an error while the working RGB space is not sRGB",
|
||||
always,
|
||||
format_color
|
||||
),
|
||||
cmd!(
|
||||
query "color.contrast",
|
||||
"Contrast",
|
||||
[],
|
||||
None,
|
||||
"{color?: a color (#rrggbbaa and #rgba are refused; default the active Fill or Stroke proxy's color, or its selected gradient stop or freeform point, or a gradient mesh's first picked point; a picked object's solid color mixed towards the fill that stains its dynamic symbol instance), against?: a color or \"below\" (default: the color VectorCraft draws at the center of the selection's bounds with the selected objects hidden, as the canvas shows it without template layers and guides; a picked object of a dynamic symbol instance hides only itself and is measured at its own center; needs a selection), opacity?: 0..100 (default the opacity the proxy's color is drawn with: the object's opacity times that of its groups and layer (for a picked symbol object, also of its instance and the groups of the symbol's art around it), its fill's or stroke's row (not for type's character paint) and a stop's or point's own, a translucent group or layer drawing the art inside it, the art behind the object included, over what is outside it; 100 for a given `color` or while the active tool paints with the proxy's color)} the WCAG 2 contrast ratio (https://www.w3.org/TR/WCAG22/#dfn-contrast-ratio) of the color, drawn at that opacity over the background with the blend modes the proxy's color is drawn with (its row's, the object's and those of its groups and layer, innermost first, each blending the result with the art below it inside the object, groups and layer around it, the object's rows below its row included (with `against` or `opacity` given, with the background); inside an object, group or layer that isolates its blending, the modes blend only with the art it holds; Normal for a given `color` or while the active tool paints with the proxy's color), against the background, in display sRGB: normal text needs 4.5:1 for AA and 7:1 for AAA, large text 3:1 and 4.5:1, and graphics 3:1 for AA; the unrounded ratio is compared → {ratio, against: \"#rrggbb\" (the background in working RGB, as `against` takes it; the sampled one rounded to 8 bits, so giving it back answers the same ratio unless `opacity` is omitted and a group or layer around the object is translucent, has a blend mode or isolates its blending, or the measured row is translucent or blends over rows below it, since a given background stands for the art below each such level), normalText: {aa, aaa}, largeText: {aa, aaa}, graphics: {aa}}",
|
||||
"{color?: a color (#rrggbbaa and #rgba are refused; default the active Fill or Stroke proxy's color, or its selected gradient stop or freeform point, or a gradient mesh's first picked point; a picked object's solid color mixed towards the fill that stains its dynamic symbol instance), against?: a color or \"below\" (default: the color VectorCraft draws at the center of the selection's bounds with the selected objects hidden, as the canvas shows it without template layers and guides; a picked object of a dynamic symbol instance hides only itself and is measured at its own center; needs a selection), opacity?: 0..100 (default the opacity the proxy's color is drawn with: the object's opacity times that of its groups and layer (for a picked symbol object, also of its instance and the groups of the symbol's art around it), its fill's or stroke's row (not for type's character paint) and a stop's or point's own, a translucent group or layer drawing the art inside it, the art behind the object included, over what is outside it; 100 for a given `color` or while the active tool paints with the proxy's color), for?: normalText|largeText|graphics (default normalText: the category `fix` answers for)} (with \"below\", a color drawn with a blend mode other than Normal over art that is not one color where it is read is an error) the WCAG 2 contrast ratio (https://www.w3.org/TR/WCAG22/#dfn-contrast-ratio) of the color, drawn at that opacity over the background with the blend modes the proxy's color is drawn with (its row's, the object's and those of its groups and layer, innermost first, each blending the result with the art below it inside the object, groups and layer around it, the object's rows below its row included (with `against` or `opacity` given, with the background); inside an object, group or layer that isolates its blending, the modes blend only with the art it holds; Normal for a given `color` or while the active tool paints with the proxy's color), against the background, in display sRGB: normal text needs 4.5:1 for AA and 7:1 for AAA, large text 3:1 and 4.5:1, and graphics 3:1 for AA; the unrounded ratio is compared → {ratio, against: \"#rrggbb\" (the background in working RGB, as `against` takes it; the sampled one rounded to 8 bits, so giving it back answers the same ratio unless `opacity` is omitted and a group or layer around the object is translucent, has a blend mode or isolates its blending, or the measured row is translucent or blends over rows below it, since a given background stands for the art below each such level), normalText: {aa, aaa}, largeText: {aa, aaa}, graphics: {aa}, for, fix: {aa, aaa (not for graphics)}: for each level of `for`, the closest color that meets it, drawn the same way, in the model of the measured color (as the Color Wheel stores a pick): the same OKLCH hue with the lightness raised or lowered, whichever takes the smaller step, and the chroma lowered where sRGB cannot show it, that also meets the level with the color, the background, the art below each group or layer, the opacities, and the color and alpha each level gives rounded to 8 bits per channel (16 lightnesses are tested on each side and the first that passes is narrowed down, so where the passing ones fall apart in more than one stretch, a nearer one between two tested can be missed); null when the color already meets the level, or when no lightness of its hue does}",
|
||||
always,
|
||||
contrast
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
fn format_color(_: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "color.format";
|
||||
let col = p.get("color").and_then(color_value).ok_or_else(|| bad(C, "missing or invalid `color`"))?;
|
||||
let opacity = super::paint::opacity_param(p, C)?;
|
||||
let notation = match text_param(p, "notation", C)? {
|
||||
Some("hex") => Some(css::Notation::Hex),
|
||||
Some("hexAlpha") => Some(css::Notation::HexAlpha),
|
||||
Some("rgb") => Some(css::Notation::Rgb),
|
||||
Some("hsl") => Some(css::Notation::Hsl),
|
||||
Some("oklch") => Some(css::Notation::Oklch),
|
||||
Some("cmyk") => None,
|
||||
_ => return Err(bad(C, "`notation` must be hex, hexAlpha, rgb, hsl, oklch or cmyk")),
|
||||
};
|
||||
let cms = vectorcraft_color::cms::active();
|
||||
let intent = cms.settings().intent;
|
||||
let text = match notation {
|
||||
None => vectorcraft_doc::swatches::color_name(cms.convert(&col, Model::Cmyk, intent)),
|
||||
Some(css::Notation::Oklch) if !cms.rgb_is_srgb() => return Err(bad(C, "OKLCH needs sRGB as the working RGB space")),
|
||||
// The working RGB numbers, as the Color panel's hex field and color.parse read them; for
|
||||
// oklch() the working RGB space is sRGB.
|
||||
Some(n) => css::format(cms.convert(&col, Model::Rgb, intent).to_rgb_uncalibrated(), opacity, n),
|
||||
};
|
||||
Ok(json!({ "text": text }))
|
||||
}
|
||||
|
||||
fn parse_color(_: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "color.parse";
|
||||
let text = text_param(p, "text", C)?.ok_or_else(|| bad(C, "missing `text`"))?;
|
||||
@@ -1032,7 +1066,229 @@ const BELOW_SIDE: f64 = 1.0;
|
||||
/// The pixels per point [`color_below`] renders at.
|
||||
const BELOW_SCALE: f64 = 4.0;
|
||||
|
||||
/// What `color.contrast` measures a color against: the background, and how the color is drawn over
|
||||
/// it (its row, object, groups and layer, each with its blend mode and opacity over the art below
|
||||
/// it). The Color Wheel panel's contrast lines measure many colors against one.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Backdrop {
|
||||
/// The background in display sRGB.
|
||||
against: [f32; 3],
|
||||
/// The background in working RGB, rounded to 8 bits, as the answer writes it.
|
||||
written: [u8; 3],
|
||||
/// The levels the color is drawn through, innermost first, without those that leave it as it is.
|
||||
passes: Vec<Pass>,
|
||||
/// The color and amount a fill stains the picked object of a dynamic symbol instance with.
|
||||
stain: Option<(Color, f32)>,
|
||||
/// Whether the canvas shows 100 % K alone as black (a rich black Appearance of Black).
|
||||
rich_black: bool,
|
||||
}
|
||||
|
||||
/// One level of a [`Backdrop`]: its blend mode and opacity, the art below it (a display sRGB color
|
||||
/// and its alpha), whether it blends without isolating or isolates its blending, and the alpha of
|
||||
/// the art below it inside the level around it, while a blending level lies further out.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
struct Pass {
|
||||
blend: BlendMode,
|
||||
opacity: f32,
|
||||
backdrop: ([f32; 3], f32),
|
||||
blends: bool,
|
||||
isolate: bool,
|
||||
inner: f32,
|
||||
}
|
||||
|
||||
/// A color drawn through the levels so far: the color, its alpha, and the alpha of what the next
|
||||
/// level out holds drawn alone.
|
||||
type Through = ([f32; 3], f32, f32);
|
||||
|
||||
impl Pass {
|
||||
/// What the level draws for color and alpha `x`, drawn over the art below it: a level that
|
||||
/// blends takes that art back out by `alone`, the alpha of what it holds drawn alone.
|
||||
fn source(&self, x: ([f32; 3], f32), alone: f32) -> ([f32; 3], f32) {
|
||||
if !self.blends {
|
||||
return x;
|
||||
}
|
||||
if alone <= 0.0 {
|
||||
return (x.0, 0.0);
|
||||
}
|
||||
let b = self.backdrop;
|
||||
(std::array::from_fn(|i| ((x.0[i] * x.1 - (1.0 - alone) * b.0[i] * b.1) / alone).clamp(0.0, 1.0)), alone)
|
||||
}
|
||||
|
||||
/// `d` drawn through the level. The level's opacity applies to what it holds, a level that
|
||||
/// isolates its blending carries out the alpha of what it holds composited on its own, and the
|
||||
/// art beside it in the level around it adds to the alpha once.
|
||||
fn draw(&self, (color, alpha, alone): Through) -> Through {
|
||||
let source = self.source((color, alpha), alone);
|
||||
let drawn = if self.isolate { alpha } else { alone } * self.opacity.clamp(0.0, 1.0);
|
||||
let (color, alpha) = composite(self.blend, source, self.opacity, self.backdrop);
|
||||
(color, alpha, drawn + self.inner * (1.0 - drawn))
|
||||
}
|
||||
|
||||
/// The level with its opacity, the art below it and its alphas passed through `q`.
|
||||
fn with(&self, q: impl Fn(f32) -> f32) -> Pass {
|
||||
let (color, alpha) = self.backdrop;
|
||||
Pass { opacity: q(self.opacity), backdrop: (color.map(&q), q(alpha)), inner: q(self.inner), ..self.clone() }
|
||||
}
|
||||
}
|
||||
|
||||
impl Backdrop {
|
||||
/// `c` as the measured object draws it: the picked object of a dynamic symbol instance that a
|
||||
/// fill stains mixes its solid color towards the stain.
|
||||
pub fn drawn_color(&self, c: &Color) -> Color {
|
||||
match self.stain {
|
||||
Some((stain, amount)) => c.lerp(&stain, amount),
|
||||
None => *c,
|
||||
}
|
||||
}
|
||||
|
||||
/// The display sRGB the canvas shows for `c` drawn as the measured object draws it, through
|
||||
/// `cms` and the Appearance of Black the backdrop was read with.
|
||||
pub fn shown(&self, cms: &vectorcraft_color::cms::Cms, c: &Color) -> [f32; 3] {
|
||||
shown_rgb(cms, self.rich_black, &self.drawn_color(c))
|
||||
}
|
||||
|
||||
/// Display sRGB `shown`, drawn as the measured color is drawn, over the background.
|
||||
pub fn front(&self, shown: [f32; 3]) -> [f32; 3] {
|
||||
let (color, alpha, _) = self.passes.iter().fold((shown, 1.0f32, 1.0f32), |d, p| p.draw(d));
|
||||
if alpha >= 1.0 { color } else { wcag::over(color, alpha, self.against) }
|
||||
}
|
||||
|
||||
/// The contrast ratio of display sRGB `shown`, drawn as the measured color is drawn, against
|
||||
/// the background.
|
||||
pub fn ratio(&self, shown: [f32; 3]) -> f64 {
|
||||
wcag::contrast_ratio(self.front(shown), self.against)
|
||||
}
|
||||
|
||||
/// [`Backdrop::ratio`] with every value rounded to 8 bits per channel: the color, the art
|
||||
/// below each level, the background, the opacities, and the color and alpha each level gives.
|
||||
fn ratio_at_eight_bits(&self, shown: [f32; 3]) -> f64 {
|
||||
let eight = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() / 255.0;
|
||||
let painted = |c: [f32; 3]| c.map(eight);
|
||||
let against = painted(self.against);
|
||||
let (color, alpha, _) = self.passes.iter().fold((painted(shown), 1.0f32, 1.0f32), |d, p| {
|
||||
let (color, alpha, alone) = p.with(eight).draw(d);
|
||||
(painted(color), eight(alpha), eight(alone))
|
||||
});
|
||||
let front = if alpha >= 1.0 { color } else { wcag::over(color, alpha, against) };
|
||||
wcag::contrast_ratio(painted(front), against)
|
||||
}
|
||||
|
||||
/// The background as `#rrggbb` in working RGB, the form a color param takes.
|
||||
pub fn against_hex(&self) -> String {
|
||||
let [r, g, b] = self.written;
|
||||
format!("#{r:02x}{g:02x}{b:02x}")
|
||||
}
|
||||
}
|
||||
|
||||
/// The display sRGB the canvas shows for `c` through `cms`: with a rich black Appearance of Black,
|
||||
/// 100 % K alone shows as black.
|
||||
fn shown_rgb(cms: &vectorcraft_color::cms::Cms, rich_black: bool, c: &Color) -> [f32; 3] {
|
||||
match *c {
|
||||
Color::Cmyk { c, m, y, k } if rich_black && c <= 0.0 && m <= 0.0 && y <= 0.0 && k >= 1.0 => [0.0; 3],
|
||||
_ => cms.display_rgb(c),
|
||||
}
|
||||
}
|
||||
|
||||
/// Display sRGB `srgb` as a color in the model of `like`, as a pick on the Color Wheel stores it:
|
||||
/// an RGB color in the working RGB space, a CMYK or Lab color converted with the color settings, a
|
||||
/// Gray color as gray.
|
||||
fn in_model_of(cms: &vectorcraft_color::cms::Cms, srgb: [f32; 3], like: &Color) -> Color {
|
||||
let [r, g, b] = cms.srgb_to_rgb(srgb);
|
||||
let rgb = Color::rgb(r, g, b);
|
||||
match like {
|
||||
Color::Rgb { .. } => rgb,
|
||||
Color::Cmyk { .. } => {
|
||||
let [c, m, y, k] = cms.to_cmyk(&rgb, cms.settings().intent);
|
||||
Color::cmyk(c, m, y, k)
|
||||
}
|
||||
Color::Lab { .. } => {
|
||||
let l = cms.lab(&rgb);
|
||||
Color::lab(l.l, l.a, l.b)
|
||||
}
|
||||
Color::Gray { .. } => keep_model(*like, rgb),
|
||||
}
|
||||
}
|
||||
|
||||
/// The closest color in the model of `color` whose contrast against `backdrop` meets `minimum`
|
||||
/// ([`wcag::closest_passing`]), checked as the canvas shows it once stored (a symbol's stain
|
||||
/// included). A candidate meets it by [`Backdrop::ratio`] and also with its values rounded to 8
|
||||
/// bits per channel ([`Backdrop::ratio_at_eight_bits`]). None when `color` already meets it by
|
||||
/// [`Backdrop::ratio`], or when no lightness of its hue does.
|
||||
fn closest_passing(backdrop: &Backdrop, color: &Color, minimum: f64) -> Option<Color> {
|
||||
let cms = vectorcraft_color::cms::active();
|
||||
let ratio = |srgb: [f32; 3]| {
|
||||
let shown = backdrop.shown(&cms, &in_model_of(&cms, srgb, color));
|
||||
backdrop.ratio(shown).min(backdrop.ratio_at_eight_bits(shown))
|
||||
};
|
||||
if backdrop.ratio(backdrop.shown(&cms, color)) >= minimum {
|
||||
return None;
|
||||
}
|
||||
let fix = wcag::closest_passing(shown_rgb(&cms, backdrop.rich_black, color), minimum, &ratio)?;
|
||||
Some(in_model_of(&cms, fix, color))
|
||||
}
|
||||
|
||||
fn contrast(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
contrast_measure(s, p).map(|(answer, _)| answer)
|
||||
}
|
||||
|
||||
/// `color.contrast`'s answer for params `p`, and what it measured the color against.
|
||||
pub fn contrast_measure(s: &Session, p: &Value) -> Result<(Value, Backdrop)> {
|
||||
const C: &str = "color.contrast";
|
||||
let category = match p.get("for") {
|
||||
None | Some(Value::Null) => Category::NormalText,
|
||||
Some(v) => {
|
||||
let key = "for";
|
||||
let ids: Vec<&str> = Category::ALL.iter().map(|c| c.id()).collect();
|
||||
v.as_str().and_then(Category::parse).ok_or_else(|| bad(C, format!("`{key}` must be one of {}", ids.join(", "))))?
|
||||
}
|
||||
};
|
||||
let (color, backdrop) = contrast_backdrop(s, p)?;
|
||||
let ratio = backdrop.ratio(backdrop.shown(&vectorcraft_color::cms::active(), &color));
|
||||
let levels = |c: Category| {
|
||||
let (aa, aaa) = c.passes(ratio);
|
||||
match aaa {
|
||||
Some(aaa) => json!({ "aa": aa, "aaa": aaa }),
|
||||
None => json!({ "aa": aa }),
|
||||
}
|
||||
};
|
||||
let fix = |minimum: f64| match closest_passing(&backdrop, &color, minimum) {
|
||||
Some(c) => serde_json::to_value(c).unwrap_or(Value::Null),
|
||||
None => Value::Null,
|
||||
};
|
||||
let fixes = match category.minimums() {
|
||||
(aa, Some(aaa)) => json!({ "aa": fix(aa), "aaa": fix(aaa) }),
|
||||
(aa, None) => json!({ "aa": fix(aa) }),
|
||||
};
|
||||
let answer = json!({
|
||||
"ratio": ratio,
|
||||
"against": backdrop.against_hex(),
|
||||
"normalText": levels(Category::NormalText),
|
||||
"largeText": levels(Category::LargeText),
|
||||
"graphics": levels(Category::Graphics),
|
||||
"for": category.id(),
|
||||
"fix": fixes,
|
||||
});
|
||||
Ok((answer, backdrop))
|
||||
}
|
||||
|
||||
/// The color `color.contrast` measures for params `p`, as stored (before a symbol's stain), and
|
||||
/// what it measures it against.
|
||||
fn contrast_backdrop(s: &Session, p: &Value) -> Result<(Color, Backdrop)> {
|
||||
let (color, backdrop) = contrast_reading(s, p, true)?;
|
||||
let color = color.ok_or_else(|| bad("color.contrast", no_color()))?;
|
||||
Ok((color, backdrop))
|
||||
}
|
||||
|
||||
/// What a color picked for the active proxy would be measured against by `color.contrast` with
|
||||
/// params `p` (without `color`), also when the proxy has no color to measure (None, a pattern): the
|
||||
/// Color Wheel's contrast lines show where a pick would pass.
|
||||
pub fn contrast_pick_backdrop(s: &Session, p: &Value) -> Result<Backdrop> {
|
||||
contrast_reading(s, p, false).map(|(_, backdrop)| backdrop)
|
||||
}
|
||||
|
||||
/// [`contrast_backdrop`], with None for the color when the proxy has none, which is an error when
|
||||
/// `need_color`.
|
||||
fn contrast_reading(s: &Session, p: &Value, need_color: bool) -> Result<(Option<Color>, Backdrop)> {
|
||||
const C: &str = "color.contrast";
|
||||
check_numbers(p, &["opacity"], C)?;
|
||||
let opacity = match p.get("opacity").and_then(Value::as_f64) {
|
||||
@@ -1044,23 +1300,28 @@ fn contrast(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
None => None,
|
||||
};
|
||||
let below = p.get("against").is_none_or(|v| v.is_null() || v.as_str() == Some("below"));
|
||||
let given = p.get("color").is_some_and(|v| !v.is_null());
|
||||
let (color, drawn) = match p.get("color") {
|
||||
None | Some(Value::Null) => proxy_color(s, opacity.is_some(), below).map_err(|e| bad(C, e))?,
|
||||
Some(v) => (color_value(v).ok_or_else(|| bad(C, "invalid `color`"))?, Drawn::default()),
|
||||
Some(v) => (Some(color_value(v).ok_or_else(|| bad(C, "invalid `color`"))?), Drawn::default()),
|
||||
};
|
||||
if need_color && color.is_none() {
|
||||
return Err(bad(C, no_color()));
|
||||
}
|
||||
let rich_black = s.prefs.black_on_screen == "rich";
|
||||
let cms = vectorcraft_color::cms::active();
|
||||
let shown = |c: &Color| match *c {
|
||||
Color::Cmyk { c, m, y, k } if rich_black && c <= 0.0 && m <= 0.0 && y <= 0.0 && k >= 1.0 => [0.0; 3],
|
||||
_ => cms.display_rgb(c),
|
||||
};
|
||||
let shown = |c: &Color| shown_rgb(&cms, rich_black, c);
|
||||
let to_8bit = |c: [f32; 3]| c.map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8);
|
||||
// Whether the background read is one color across its pixels.
|
||||
let mut uniform = true;
|
||||
// The background in display sRGB, and as the working RGB `#rrggbb` a given `against` reads as.
|
||||
let (against, written) = match p.get("against").filter(|_| !below) {
|
||||
None => {
|
||||
// The sample in working RGB, rounded to 8 bits: the background the answer writes is the
|
||||
// one the ratio uses, and giving it back answers the same ratio.
|
||||
let working = to_8bit(cms.srgb_to_rgb(color_below(s, rich_black, None, &[], None).map_err(|e| bad(C, e))?.0));
|
||||
let ((sample, _), one) = color_below(s, rich_black, None, &[], None).map_err(|e| bad(C, e))?;
|
||||
uniform &= one;
|
||||
let working = to_8bit(cms.srgb_to_rgb(sample));
|
||||
(cms.rgb_to_srgb(working.map(|v| f32::from(v) / 255.0)), working)
|
||||
}
|
||||
Some(v) => {
|
||||
@@ -1096,60 +1357,51 @@ fn contrast(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// then takes that art back out by the alpha of what it holds drawn alone, and blends the rest:
|
||||
// `alone` is the alpha of what the next level out holds drawn alone. Each level's opacity
|
||||
// applies to what it holds, and the art beside it in the level around it adds to the alpha once.
|
||||
// The alphas, the art below each level and `alone` do not depend on the color, so each level
|
||||
// is read once here and [`Backdrop::front`] draws any color through the levels.
|
||||
let blends = |a: &Step| a.blend != BlendMode::Normal && !a.isolate;
|
||||
let mut x = (shown(&color), 1.0f32);
|
||||
let mut passes = vec![];
|
||||
let mut alpha = 1.0f32;
|
||||
let mut alone = 1.0f32;
|
||||
// Whether a level so far read art that is not one color.
|
||||
let mut mixed = false;
|
||||
for (k, step) in steps.iter().enumerate() {
|
||||
if step.blend == BlendMode::Normal && step.opacity >= 1.0 && x.1 >= 1.0 && alone >= 1.0 {
|
||||
if step.blend == BlendMode::Normal && step.opacity >= 1.0 && alpha >= 1.0 && alone >= 1.0 {
|
||||
continue;
|
||||
}
|
||||
let above = &steps[k + 1..];
|
||||
let scope = above.iter().find(|a| a.isolate);
|
||||
let full = above.iter().filter(|a| a.blend != BlendMode::Normal || a.opacity < 1.0).map(|a| &a.within).collect::<Vec<_>>();
|
||||
let read = |scope: Option<&Part>| color_below(s, rich_black, step.hide.as_ref(), &full, scope).map_err(|e| bad(C, e));
|
||||
let backdrop = match scope {
|
||||
Some(_) if !sampled => ([0.0; 3], 0.0),
|
||||
None if !sampled => (against, 1.0),
|
||||
let (backdrop, one) = match scope {
|
||||
Some(_) if !sampled => (([0.0; 3], 0.0), true),
|
||||
None if !sampled => ((against, 1.0), uniform),
|
||||
// The background itself, as the answer writes it.
|
||||
None if step.hide.is_none() && full.is_empty() => (against, 1.0),
|
||||
None if step.hide.is_none() && full.is_empty() => ((against, 1.0), uniform),
|
||||
_ => read(scope.map(|a| &a.within))?,
|
||||
};
|
||||
// The alpha of the art below the level inside the level around it, while a blending level
|
||||
// lies further out (none for a given background).
|
||||
let inner = match above.first() {
|
||||
Some(around) if sampled && above.iter().take_while(|a| !a.isolate).any(blends) => read(Some(&around.within))?.1,
|
||||
_ => 0.0,
|
||||
let (inner, inner_one) = match above.first() {
|
||||
Some(around) if sampled && above.iter().take_while(|a| !a.isolate).any(blends) => {
|
||||
let ((_, a), one) = read(Some(&around.within))?;
|
||||
(a, one)
|
||||
}
|
||||
_ => (0.0, true),
|
||||
};
|
||||
let source = if !blends(step) {
|
||||
x
|
||||
} else if alone <= 0.0 {
|
||||
(x.0, 0.0)
|
||||
} else {
|
||||
(std::array::from_fn(|i| ((x.0[i] * x.1 - (1.0 - alone) * backdrop.0[i] * backdrop.1) / alone).clamp(0.0, 1.0)), alone)
|
||||
};
|
||||
// A level that isolates its blending carries out the alpha of what it holds composited on
|
||||
// its own.
|
||||
let drawn = if step.isolate { x.1 } else { alone } * step.opacity.clamp(0.0, 1.0);
|
||||
x = composite(step.blend, source, step.opacity, backdrop);
|
||||
alone = drawn + inner * (1.0 - drawn);
|
||||
}
|
||||
let front = if x.1 >= 1.0 { x.0 } else { wcag::over(x.0, x.1, against) };
|
||||
let ratio = wcag::contrast_ratio(front, against);
|
||||
let levels = |c: Category| {
|
||||
let (aa, aaa) = c.passes(ratio);
|
||||
match aaa {
|
||||
Some(aaa) => json!({ "aa": aa, "aaa": aaa }),
|
||||
None => json!({ "aa": aa }),
|
||||
// A blend mode mixes the color with the art below it pixel by pixel, which one color read for
|
||||
// art of several colors does not stand for, also when that art reaches it through the levels
|
||||
// inside it.
|
||||
mixed |= !one || !inner_one;
|
||||
if mixed && step.blend != BlendMode::Normal && step.opacity > 0.0 {
|
||||
return Err(bad(C, "the art behind the selection is not one color where it is read, and the color blends with it: give `against`"));
|
||||
}
|
||||
};
|
||||
let [r, g, b] = written;
|
||||
Ok(json!({
|
||||
"ratio": ratio,
|
||||
"against": format!("#{r:02x}{g:02x}{b:02x}"),
|
||||
"normalText": levels(Category::NormalText),
|
||||
"largeText": levels(Category::LargeText),
|
||||
"graphics": levels(Category::Graphics),
|
||||
}))
|
||||
let pass = Pass { blend: step.blend, opacity: step.opacity, backdrop, blends: blends(step), isolate: step.isolate, inner };
|
||||
(_, alpha, alone) = pass.draw(([0.0; 3], alpha, alone));
|
||||
passes.push(pass);
|
||||
}
|
||||
let stain = if given { None } else { stain_of(s, !need_color) };
|
||||
Ok((color, Backdrop { against, written, passes, stain, rich_black }))
|
||||
}
|
||||
|
||||
/// An object around the proxy's object: one in the document, or a group of the picked object's
|
||||
@@ -1232,7 +1484,8 @@ fn composite(mode: BlendMode, x: ([f32; 3], f32), opacity: f32, backdrop: ([f32;
|
||||
/// levels that change what they draw must be the same objects too, since the art below each one is
|
||||
/// read with that object hidden, and the object's opacity must be the same apart from its row's,
|
||||
/// since the row draws over the object's rows below it and the object over the art behind it, and a
|
||||
/// row that blends or is translucent must lie over the same shown rows.
|
||||
/// row that blends or is translucent must lie over the same shown rows, and over a lower row that
|
||||
/// blends, with the same isolation.
|
||||
fn draws_alike(a: &Drawn, b: &Drawn, given_opacity: bool, below: bool) -> bool {
|
||||
let counts = |l: &&Level| l.blend != BlendMode::Normal || l.isolate || (!given_opacity && l.opacity < 1.0);
|
||||
let level = |x: &Level, y: &Level| {
|
||||
@@ -1248,10 +1501,26 @@ fn draws_alike(a: &Drawn, b: &Drawn, given_opacity: bool, below: bool) -> bool {
|
||||
let total = |d: &Drawn| d.opacity * d.row.map_or(1.0, |r| r.1);
|
||||
// A row that blends or lets art through draws over the rows below it, read at one point.
|
||||
let over_rows = |d: &Drawn| d.row.is_some_and(|(m, o)| m != BlendMode::Normal || o < 1.0);
|
||||
// A lower row that blends reads the art behind the object unless the object isolates its
|
||||
// blending, so a row drawn over it reads a backdrop that depends on the isolation. A blending
|
||||
// row at no opacity does not show, nor does a fill row without effects under an opaque solid
|
||||
// Normal fill row without effects, which covers the same shape (a stroke reaches outside it).
|
||||
let plain_fill = |i: &vectorcraft_doc::AppearanceItem| i.is_fill() && i.effects().is_empty();
|
||||
let covers = |i: &vectorcraft_doc::AppearanceItem| {
|
||||
plain_fill(i) && i.blend() == BlendMode::Normal && i.opacity() >= 1.0 && matches!(i.paint(), Paint::Solid { .. })
|
||||
};
|
||||
let over_blended = |d: &Drawn| {
|
||||
over_rows(d)
|
||||
&& d.lower
|
||||
.iter()
|
||||
.enumerate()
|
||||
.any(|(k, i)| i.blend() != BlendMode::Normal && i.opacity() > 0.0 && !(plain_fill(i) && d.lower[k + 1..].iter().any(covers)))
|
||||
};
|
||||
row(a) == row(b)
|
||||
&& (given_opacity || !below || !(over_rows(a) || over_rows(b)) || a.lower == b.lower)
|
||||
&& a.blend == b.blend
|
||||
&& (row(a).is_none() || a.isolate == b.isolate)
|
||||
&& (given_opacity || !below || !(over_blended(a) || over_blended(b)) || a.isolate == b.isolate)
|
||||
&& (given_opacity || (total(a) - total(b)).abs() < 1e-6)
|
||||
&& (given_opacity || (row(a).is_none() && !below) || (a.opacity - b.opacity).abs() < 1e-6)
|
||||
&& la.len() == lb.len()
|
||||
@@ -1263,8 +1532,9 @@ fn draws_alike(a: &Drawn, b: &Drawn, given_opacity: bool, below: bool) -> bool {
|
||||
/// it is drawn ([`Drawn`]). With `given_opacity`, the opacities of the selected objects are not
|
||||
/// compared, since the given opacity takes their place; with `below` (the background is sampled),
|
||||
/// objects in different translucent or blending groups or layers differ, since the art below each
|
||||
/// such level is read with it hidden.
|
||||
fn proxy_color(s: &Session, given_opacity: bool, below: bool) -> std::result::Result<(Color, Drawn), String> {
|
||||
/// such level is read with it hidden. The color is None when the proxy has none (None, a pattern),
|
||||
/// and the drawing is then the one a solid color in its place would have.
|
||||
fn proxy_color(s: &Session, given_opacity: bool, below: bool) -> std::result::Result<(Option<Color>, Drawn), String> {
|
||||
let stroke = !s.fill_active;
|
||||
let (fill_mixed, stroke_mixed) = s.proxy_mixed();
|
||||
if if stroke { stroke_mixed } else { fill_mixed } {
|
||||
@@ -1320,20 +1590,28 @@ fn proxy_color(s: &Session, given_opacity: bool, below: bool) -> std::result::Re
|
||||
} else {
|
||||
drawing = source()?.unwrap_or_default();
|
||||
}
|
||||
let no_color = || "the active fill or stroke has no color: give `color`".to_string();
|
||||
match if stroke { stroke_paint } else { fill } {
|
||||
Paint::Solid { color, .. } => Ok((stained(s, color), drawing)),
|
||||
let found = match if stroke { stroke_paint } else { fill } {
|
||||
Paint::Solid { color, .. } => Some((color, drawing.clone())),
|
||||
Paint::Gradient(g) if g.gradient.kind == vectorcraft_color::GradientKind::Freeform => {
|
||||
let f = g.freeform_on(vectorcraft_geom::Rect::new(0.0, 0.0, 1.0, 1.0));
|
||||
let i = s.selected_freeform_point().filter(|i| *i < f.points.len()).unwrap_or(0);
|
||||
f.points.get(i).map(|pt| (pt.color, at(&drawing, pt.opacity))).ok_or_else(no_color)
|
||||
f.points.get(i).map(|pt| (pt.color, at(&drawing, pt.opacity)))
|
||||
}
|
||||
Paint::Gradient(g) => {
|
||||
let i = s.selected_stop().unwrap_or(0).min(g.gradient.stops.len().saturating_sub(1));
|
||||
g.gradient.stops.get(i).map(|st| (st.color, at(&drawing, st.opacity))).ok_or_else(no_color)
|
||||
g.gradient.stops.get(i).map(|st| (st.color, at(&drawing, st.opacity)))
|
||||
}
|
||||
Paint::None | Paint::Pattern { .. } => Err(no_color()),
|
||||
}
|
||||
Paint::None | Paint::Pattern { .. } => None,
|
||||
};
|
||||
Ok(match found {
|
||||
Some((color, drawn)) => (Some(color), drawn),
|
||||
None => (None, drawing),
|
||||
})
|
||||
}
|
||||
|
||||
/// The message for an active fill or stroke with no color to measure.
|
||||
fn no_color() -> String {
|
||||
"the active fill or stroke has no color: give `color`".to_string()
|
||||
}
|
||||
|
||||
/// `drawing` with a stop's or point's `opacity`, which applies where its paint is drawn: in its
|
||||
@@ -1398,19 +1676,21 @@ fn drawn_settings(s: &Session, n: &Node, item: Option<usize>, stroke: bool) -> s
|
||||
Ok(Drawn { opacity: n.opacity, row: own.map(|o| (o.1, o.0)), blend: n.blend, isolate: n.isolate, around, lower })
|
||||
}
|
||||
|
||||
/// `color` as the canvas draws the picked object of a dynamic symbol instance that a fill stains
|
||||
/// (`symbol_overrides::instance_art` mixes the art's solid paints towards the instance's fill);
|
||||
/// `color` itself otherwise.
|
||||
fn stained(s: &Session, color: Color) -> Color {
|
||||
let stain = s.active().and_then(|st| {
|
||||
let sp = st.selection.symbol_part.as_ref()?;
|
||||
st.selected_symbol_part()?;
|
||||
vectorcraft_doc::symbol_overrides::stain(st.doc.node(sp.instance)?)
|
||||
});
|
||||
match stain {
|
||||
Some((c, amount)) => color.lerp(&c, amount.clamp(0.0, 1.0)),
|
||||
None => color,
|
||||
/// The color and amount a fill stains the picked object of a dynamic symbol instance with
|
||||
/// (`symbol_overrides::instance_art` mixes the art's solid paints towards the instance's fill), when
|
||||
/// such an object is picked and its proxy shows a solid color. For a pick (`pick`), a proxy of None
|
||||
/// or a pattern counts too, as the pick puts a solid color in its place.
|
||||
fn stain_of(s: &Session, pick: bool) -> Option<(Color, f32)> {
|
||||
let (fill, stroke) = s.proxy_paints();
|
||||
match if s.fill_active { fill } else { stroke } {
|
||||
Paint::Solid { .. } => {}
|
||||
Paint::None | Paint::Pattern { .. } if pick => {}
|
||||
_ => return None,
|
||||
}
|
||||
let st = s.active()?;
|
||||
let sp = st.selection.symbol_part.as_ref()?;
|
||||
st.selected_symbol_part()?;
|
||||
vectorcraft_doc::symbol_overrides::stain(st.doc.node(sp.instance)?).map(|(c, amount)| (c, amount.clamp(0.0, 1.0)))
|
||||
}
|
||||
|
||||
/// The objects that draw the proxy's object `id` ([`Level`]), outermost first: its groups and
|
||||
@@ -1455,14 +1735,14 @@ fn enclosing(s: &Session, id: NodeId) -> Vec<Level> {
|
||||
/// hidden in place of the selection, or for [`Part::Rows`], the proxy's row and the rows above it;
|
||||
/// the objects of `full` draw at full opacity in Normal mode; and with `scope` (a group or layer
|
||||
/// around the selection, or the proxy's objects), only the art inside it is drawn, over nothing,
|
||||
/// without artboards.
|
||||
/// without artboards. Also whether the square's pixels are all one color.
|
||||
fn color_below(
|
||||
s: &Session,
|
||||
rich_black: bool,
|
||||
hide: Option<&Part>,
|
||||
full: &[&Part],
|
||||
scope: Option<&Part>,
|
||||
) -> std::result::Result<([f32; 3], f32), String> {
|
||||
) -> std::result::Result<(([f32; 3], f32), bool), String> {
|
||||
super::has_selection(s)?;
|
||||
let st = s.active().ok_or("no document open")?;
|
||||
let ids = st.selection.objects.clone();
|
||||
@@ -1591,8 +1871,10 @@ fn color_below(
|
||||
let img = vectorcraft_render::Renderer::new().render_region_with(copy.as_ref().unwrap_or(&st.doc), region, BELOW_SCALE, &opts);
|
||||
let px = img.pixels.as_chunks::<4>().0;
|
||||
if px.is_empty() {
|
||||
return Ok(if scope.is_none() { ([1.0; 3], 1.0) } else { ([0.0; 3], 0.0) });
|
||||
return Ok((if scope.is_none() { ([1.0; 3], 1.0) } else { ([0.0; 3], 0.0) }, true));
|
||||
}
|
||||
// Whether the pixels are one color, to within one step of 255 per channel.
|
||||
let uniform = px.first().is_none_or(|first| px.iter().all(|p| p.iter().zip(first).all(|(a, b)| a.abs_diff(*b) <= 1)));
|
||||
// The pixels are premultiplied: the average color is their sum over their alpha's.
|
||||
let mut sum = [0.0f64; 4];
|
||||
for p in px {
|
||||
@@ -1602,10 +1884,10 @@ fn color_below(
|
||||
}
|
||||
let alpha = sum[3] / (px.len() as f64 * 255.0);
|
||||
if alpha <= 0.0 {
|
||||
return Ok(([0.0; 3], 0.0));
|
||||
return Ok((([0.0; 3], 0.0), uniform));
|
||||
}
|
||||
let rgb = [0, 1, 2].map(|i| (sum[i] / (px.len() as f64 * 255.0) / alpha).clamp(0.0, 1.0) as f32);
|
||||
Ok((rgb, alpha as f32))
|
||||
Ok(((rgb, alpha as f32), uniform))
|
||||
}
|
||||
|
||||
/// Hides fill or stroke row `item` of `n` (else its topmost row of the kind) and every row above it.
|
||||
|
||||
@@ -110,7 +110,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Three-Point Arc",
|
||||
[],
|
||||
None,
|
||||
"{start: [x, y], end: [x, y], through?: [x, y], toward?: [x, y], at?: \"start\"|\"end\" (default \"start\"; only with `toward`)} → {id, cx, cy, radius, sweep}: an open circular arc from `start` to `end` in the current stroke (black when it is none) with no fill, its ends exactly at the two points (not pixel-aligned). With `through`, the arc passes through that point, an anchor of the path; with `toward`, it leaves the end `at` names heading toward that point (its tangent there). Give exactly one of `through` and `toward`; `at` with `through` is an error. `sweep` is the arc's turn in degrees, positive clockwise on the page. Two points that are the same, three on one line, or an arc reaching past the canvas are an error, and nothing is drawn",
|
||||
"{start: [x, y], end: [x, y], through?: [x, y], toward?: [x, y], at?: \"start\"|\"end\" (default \"start\"; only with `toward`), join?: bool (default false)} → {id, cx, cy, radius, sweep, joined?}: an open circular arc from `start` to `end` in the current stroke (black when it is none) with no fill, its ends exactly at the two points (not pixel-aligned). With `through`, the arc passes through that point, an anchor of the path; with `toward`, it leaves the end `at` names heading toward that point (its tangent there). Give exactly one of `through` and `toward`; `at` with `through` is an error. `sweep` is the arc's turn in degrees, positive clockwise on the page. With `join`, an end of the arc on an end of an editable open path (inside the isolated group in isolation mode) joins the arc to that path, which keeps its look and, when one end joins, its direction (a path in the selection comes first); with both ends on open path ends the second path joins too, or the path closes when both are its own ends. The result then has `joined: true` and `id` is the joined path (or its compound path). A `join` that is not true or false is an error. Two points that are the same, three on one line, or an arc reaching past the canvas are an error, and nothing is drawn",
|
||||
has_doc,
|
||||
three_point_arc
|
||||
),
|
||||
@@ -747,7 +747,8 @@ fn arc(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
/// An open circular arc from `start` to `end` ([`shapes::CircularArc`]): through `through`, or
|
||||
/// leaving the end `at` names toward `toward`. One undo step, named as an Arc tool drag is.
|
||||
/// leaving the end `at` names toward `toward`. With `join`, joined to the open paths whose ends
|
||||
/// its ends lie on ([`super::path::join_arc`]). One undo step, named as an Arc tool drag is.
|
||||
fn three_point_arc(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "shape.threePointArc";
|
||||
let point = |key: &str| finite_numbers::<2>(&p[key]).map(|[x, y]| Point::new(x, y)).ok_or_else(|| bad(C, format!("`{key}` must be [x, y]")));
|
||||
@@ -774,8 +775,32 @@ fn three_point_arc(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
_ => return Err(bad(C, "give exactly one of `through` and `toward`")),
|
||||
};
|
||||
let join = match p.get("join") {
|
||||
None => false,
|
||||
Some(Value::Bool(on)) => *on,
|
||||
Some(_) => return Err(bad(C, "`join` must be true or false")),
|
||||
};
|
||||
let arc = arc.ok_or_else(|| bad(C, "no arc fits these points: two are the same or all three lie on one line"))?;
|
||||
let path = via.map_or_else(|| arc.to_path(), |v| arc.to_path_via(v));
|
||||
let ends = if join {
|
||||
let st = s.doc()?;
|
||||
let selected = st.selection.objects.clone();
|
||||
let find = |at| super::path::open_end_at(&st.doc, st.isolation, &selected, at);
|
||||
(find(start), find(end))
|
||||
} else {
|
||||
(None, None)
|
||||
};
|
||||
if ends.0.is_some() || ends.1.is_some() {
|
||||
let sub = path.subpaths.first().cloned().ok_or_else(|| bad(C, "no arc fits these points"))?;
|
||||
let id = s.edit("Arc", |d, sel| {
|
||||
let id = super::path::join_arc(d, &sub, ends.0, ends.1)?;
|
||||
sel.set([id]);
|
||||
Ok(id)
|
||||
})?;
|
||||
return Ok(
|
||||
json!({ "id": id.0, "joined": true, "cx": arc.center.x, "cy": arc.center.y, "radius": arc.radius, "sweep": arc.sweep.to_degrees() }),
|
||||
);
|
||||
}
|
||||
let look = s.new_art_look(
|
||||
vectorcraft_color::Paint::None,
|
||||
if s.paint.stroke.is_none() { vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK) } else { s.paint.stroke.clone() },
|
||||
@@ -895,7 +920,8 @@ pub(crate) fn anchor_from_json(v: &Value, cmd: &str) -> Result<Anchor> {
|
||||
};
|
||||
let mut anchor = Anchor::with_handles(p, handle("in")?, handle("out")?);
|
||||
match v.get("smooth").filter(|b| !b.is_null()) {
|
||||
None | Some(Value::Bool(false)) => {}
|
||||
None => {}
|
||||
Some(Value::Bool(false)) => anchor.kind = AnchorKind::Corner,
|
||||
Some(Value::Bool(true)) => anchor.kind = AnchorKind::Smooth,
|
||||
Some(_) => return Err(bad(cmd, "anchor `smooth` must be true or false")),
|
||||
}
|
||||
|
||||
@@ -954,9 +954,43 @@ pub(crate) fn selected_roots(s: &Session) -> Result<Vec<NodeId>> {
|
||||
Ok(selection_roots(s.doc()?))
|
||||
}
|
||||
|
||||
/// [`selected_roots`] of one document's selection.
|
||||
/// [`selected_roots`] of one document's selection, found once for each document version and set of selected
|
||||
/// objects and kept on this thread: the menus' enabled checks read it many times for one selection.
|
||||
pub(crate) fn selection_roots(st: &crate::DocState) -> Vec<NodeId> {
|
||||
roots_of(&st.doc, st.selection.in_paint_order(&st.doc))
|
||||
let at = Arc::as_ptr(&st.doc);
|
||||
ROOTS.with_borrow_mut(|kept| {
|
||||
if let Some((doc, objects, roots)) = kept.as_ref()
|
||||
&& doc.as_ptr() == at
|
||||
&& *objects == st.selection.objects
|
||||
{
|
||||
return roots.clone();
|
||||
}
|
||||
#[cfg(test)]
|
||||
ROOTS_FOUND.set(ROOTS_FOUND.get() + 1);
|
||||
let roots = roots_of(&st.doc, st.selection.in_paint_order(&st.doc));
|
||||
*kept = Some((Arc::downgrade(&st.doc), st.selection.objects.clone(), roots.clone()));
|
||||
roots
|
||||
})
|
||||
}
|
||||
|
||||
/// The selected objects and roots of the last [`selection_roots`], with the document version they belong to. It is
|
||||
/// held weakly, so its address is not reused while it is kept, and an edit in place moves it.
|
||||
type KeptRoots = Option<(std::sync::Weak<Document>, Vec<NodeId>, Vec<NodeId>)>;
|
||||
|
||||
thread_local! {
|
||||
static ROOTS: std::cell::RefCell<KeptRoots> = const { std::cell::RefCell::new(None) };
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// How many times [`selection_roots`] found the roots on this thread.
|
||||
static ROOTS_FOUND: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// How many times [`selection_roots`] has found the roots on this thread.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn roots_found() -> u64 {
|
||||
ROOTS_FOUND.get()
|
||||
}
|
||||
|
||||
/// [`super::brushsym::part_only`] while an object of a dynamic symbol instance's art is selected:
|
||||
|
||||
@@ -347,3 +347,26 @@ fn direct_selection_cut_timing() {
|
||||
println!("median {}: cpu {:?}, wall {:?}", ["one at a time", "Cut"][k], median(cpu), median(wall));
|
||||
}
|
||||
}
|
||||
|
||||
/// The selected roots are found once for a document version and its selected objects, however many enabled checks
|
||||
/// read them, and found again after the selection changes, after an edit, and for another selection.
|
||||
#[test]
|
||||
fn selected_roots_are_found_once_for_each_document_and_selection() {
|
||||
let mut s = session(30, square);
|
||||
let all = selected_roots(&s).unwrap();
|
||||
assert_eq!(all.len(), 30);
|
||||
let before = roots_found();
|
||||
for _ in 0..20 {
|
||||
assert_eq!(selected_roots(&s).unwrap(), all);
|
||||
}
|
||||
assert_eq!(roots_found() - before, 0, "reading the same selection again finds nothing");
|
||||
s.execute("select.set", &json!({"ids": [all[3].0, all[7].0]})).unwrap();
|
||||
assert_eq!(selected_roots(&s).unwrap(), vec![all[3], all[7]]);
|
||||
assert_eq!(roots_found() - before, 1, "a new selection is found once");
|
||||
s.execute("object.group", &json!({})).unwrap();
|
||||
let grouped = selected_roots(&s).unwrap();
|
||||
assert_eq!(grouped.len(), 1, "the group is the one root: {grouped:?}");
|
||||
assert_ne!(grouped, vec![all[3], all[7]]);
|
||||
selected_roots(&s).unwrap();
|
||||
assert_eq!(roots_found() - before, 2, "an edit finds the roots once again");
|
||||
}
|
||||
@@ -13,13 +13,16 @@
|
||||
//! a new document whose artboard is their bounds (or, to place, the art of one group), and nothing
|
||||
//! opens or is placed when the importer fails, declines, is cancelled or returns objects that don't
|
||||
//! pass the checks a filter's output does.
|
||||
//! An importer at plug-in API level 4 may also return point type, embedded images, top-level
|
||||
//! layers and artboards (its manifest's `outputKinds`): the artboards it returns replace the one
|
||||
//! around the art of a new document, and File › Place leaves them out.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::Value;
|
||||
use vectorcraft_doc::{Document, MAX_COORD, NodeId};
|
||||
use vectorcraft_geom::Rect;
|
||||
use vectorcraft_plugins::import::Mode;
|
||||
use vectorcraft_doc::{CharStyle, Document, ImageObject, LAYER_COLORS, LayerColor, MAX_COORD, Node, NodeId, NodeKind, TextObject};
|
||||
use vectorcraft_geom::{Point, Rect};
|
||||
use vectorcraft_plugins::import::{ImportObject, Mode};
|
||||
use vectorcraft_plugins::{Manifest, Plugin, export, import, objects};
|
||||
|
||||
use super::super::{Result, bad, str_param};
|
||||
@@ -210,17 +213,15 @@ pub(crate) fn place_source<'a>(p: &'a Value, cmd: &str) -> Result<Source<'a>> {
|
||||
}
|
||||
}
|
||||
|
||||
/// What [`read`] gives: the importer's format, the new document, its objects' ids, the artboards
|
||||
/// the importer returned and its warnings.
|
||||
type Read = (&'static Format, Document, Vec<NodeId>, Vec<import::OutArtboard>, Vec<String>);
|
||||
|
||||
/// The file `name` holding `bytes` read by importer `plugin` for `mode` with command `cmd`'s params
|
||||
/// `p` (`params`: the importer's own parameters) → the importer's format, a new document holding its
|
||||
/// objects on its first layer, their ids, and its warnings.
|
||||
fn read(
|
||||
name: &str,
|
||||
bytes: &[u8],
|
||||
plugin: &Plugin,
|
||||
p: &Value,
|
||||
cmd: &str,
|
||||
mode: Mode,
|
||||
) -> Result<(&'static Format, Document, Vec<NodeId>, Vec<String>)> {
|
||||
/// objects (on its first layer, or in the layers the importer returned), their ids, the artboards
|
||||
/// the importer returned, and its warnings.
|
||||
fn read(name: &str, bytes: &[u8], plugin: &Plugin, p: &Value, cmd: &str, mode: Mode) -> Result<Read> {
|
||||
let m = plugin.manifest();
|
||||
let format = format(&export::format_id(&m.id)).filter(|f| f.read).ok_or_else(|| err(vectorcraft_plugins::Error::NotFound(m.id.clone())))?;
|
||||
let (ext, stem) = (extension(name), file_stem(name));
|
||||
@@ -234,15 +235,24 @@ fn read(
|
||||
let mut doc = Document::new(1.0, 1.0);
|
||||
let layer = doc.layers.first().map(|l| l.id);
|
||||
let admit = |fx: &[vectorcraft_doc::Effect], n: &vectorcraft_doc::Node| crate::cmd::plugin::admit_effects_for(cmd, fx, n);
|
||||
let ids = objects::apply_output(&mut doc, &[], imported.objects, layer, &admit).map_err(|e| failed(mode, name, e))?;
|
||||
Ok((format, doc, ids, imported.warnings))
|
||||
let mut warnings = Vec::new();
|
||||
let (ids, artboards) = if imported.paths_only() {
|
||||
let paths = imported.objects.into_iter().filter_map(|o| if let ImportObject::Path(o) = o { Some(o) } else { None }).collect();
|
||||
(objects::apply_output(&mut doc, &[], paths, layer, &admit).map_err(|e| failed(mode, name, e))?, Vec::new())
|
||||
} else {
|
||||
let ids = build(&mut doc, imported.objects, imported.layers, &admit, &mut warnings).map_err(|e| failed(mode, name, e))?;
|
||||
(ids, imported.artboards)
|
||||
};
|
||||
warnings.splice(0..0, imported.warnings);
|
||||
Ok((format, doc, ids, artboards, warnings))
|
||||
}
|
||||
|
||||
/// The file `name` holding `bytes` read by importer `plugin` to place it, with `file.place`'s params
|
||||
/// `p` (errors of command `cmd`) → the importer's format, the document holding its objects on its
|
||||
/// first layer, and its warnings. Importer `plugin`'s manifest must set `place`.
|
||||
/// `p` (errors of command `cmd`) → the importer's format, the document holding its objects in its
|
||||
/// layers, and its warnings; artboards the importer returned are left out. Importer `plugin`'s
|
||||
/// manifest must set `place`.
|
||||
pub(crate) fn read_for_place(name: &str, bytes: &[u8], plugin: &Plugin, p: &Value, cmd: &str) -> Result<(&'static Format, Document, Vec<String>)> {
|
||||
let (format, doc, _, warnings) = read(name, bytes, plugin, p, cmd, Mode::Place)?;
|
||||
let (format, doc, _, _, warnings) = read(name, bytes, plugin, p, cmd, Mode::Place)?;
|
||||
Ok((format, doc, warnings))
|
||||
}
|
||||
|
||||
@@ -250,14 +260,148 @@ pub(crate) fn read_for_place(name: &str, bytes: &[u8], plugin: &Plugin, p: &Valu
|
||||
/// (`params`: the importer's own parameters) into a new document, its artboard the bounds of what
|
||||
/// the importer returned.
|
||||
pub(super) fn load(name: &str, bytes: &[u8], plugin: &Plugin, p: &Value) -> Result<Loaded> {
|
||||
let (format, mut doc, ids, warnings) = read(name, bytes, plugin, p, C, Mode::Import)?;
|
||||
if let (Some(bounds), Some(board)) = (doc.bounds_of(&ids, true), doc.artboards.first_mut()) {
|
||||
board.rect = artboard_rect(bounds);
|
||||
let (format, mut doc, ids, artboards, warnings) = read(name, bytes, plugin, p, C, Mode::Import)?;
|
||||
if artboards.is_empty() {
|
||||
if let (Some(bounds), Some(board)) = (doc.bounds_of(&ids, true), doc.artboards.first_mut()) {
|
||||
board.rect = artboard_rect(bounds);
|
||||
}
|
||||
} else {
|
||||
set_artboards(&mut doc, artboards);
|
||||
}
|
||||
doc.title = file_name(name);
|
||||
Ok(Loaded { doc, format, warnings, restored: false, converted: false, preview_only: false, editing_data: false, native_pdf_compatible: None })
|
||||
}
|
||||
|
||||
/// Puts `objects`, what an importer at plug-in API level 4 returned, into `doc`, a new document of
|
||||
/// one layer: in `layers`, bottom first, each holding the objects it lists in their order, or all in
|
||||
/// that one layer when there are none. Paths are made as a filter's new ones are (their effects let
|
||||
/// in by `admit`), type is laid out, and each image is stored in the document as a PNG of its
|
||||
/// pixels. A warning for type whose font isn't there, or doesn't have its style, goes to `warnings`.
|
||||
/// An object that reaches more than [`MAX_COORD`] from the origin is an error. Returns the objects'
|
||||
/// ids in order.
|
||||
fn build(
|
||||
doc: &mut Document,
|
||||
objects: Vec<ImportObject>,
|
||||
layers: Vec<import::OutLayer>,
|
||||
admit: objects::AdmitEffects,
|
||||
warnings: &mut Vec<String>,
|
||||
) -> std::result::Result<Vec<NodeId>, String> {
|
||||
let count = objects.len();
|
||||
let first = doc.layers.first().map(|l| (**l).clone());
|
||||
let first = first.unwrap_or_else(|| Node::layer(doc.alloc_id(), "Layer 1", LayerColor::Preset(0)));
|
||||
let mut owner = vec![0usize; count];
|
||||
for (li, l) in layers.iter().enumerate() {
|
||||
for &k in &l.objects {
|
||||
if let Some(o) = owner.get_mut(k) {
|
||||
*o = li;
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut members: Vec<Vec<Arc<Node>>> = vec![Vec::new(); layers.len().max(1)];
|
||||
let mut ids = Vec::with_capacity(count);
|
||||
let mut fonts = std::collections::BTreeSet::new();
|
||||
for (i, o) in objects.into_iter().enumerate() {
|
||||
let at = format!("objects[{i}]");
|
||||
let node = match o {
|
||||
ImportObject::Path(o) => objects::new_object(doc, o, &at, admit).map_err(|e| e.to_string())?,
|
||||
ImportObject::Type(t) => {
|
||||
let node = type_node(doc, t);
|
||||
if let NodeKind::Text(t) = &node.kind {
|
||||
fonts.extend(t.runs.iter().flat_map(crate::cmd::fonts::run_fonts));
|
||||
}
|
||||
node
|
||||
}
|
||||
ImportObject::Image(im) => image_node(doc, im).map_err(|e| e.to_string())?,
|
||||
};
|
||||
if node.geometric_bounds().is_some_and(|b| ![b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite() && v.abs() <= MAX_COORD)) {
|
||||
return Err(format!("plug-in output: {at}: it reaches more than {MAX_COORD} pt from the origin"));
|
||||
}
|
||||
ids.push(node.id);
|
||||
if let Some(list) = owner.get(i).and_then(|&li| members.get_mut(li)) {
|
||||
list.push(Arc::new(node));
|
||||
}
|
||||
}
|
||||
let built: Vec<Arc<Node>> = if layers.is_empty() {
|
||||
let mut layer = first;
|
||||
if let Some(children) = layer.children_mut() {
|
||||
*children = members.into_iter().next().unwrap_or_default();
|
||||
}
|
||||
vec![Arc::new(layer)]
|
||||
} else {
|
||||
layers
|
||||
.into_iter()
|
||||
.zip(members)
|
||||
.enumerate()
|
||||
.map(|(li, (l, children))| {
|
||||
let mut layer = Node::layer(doc.alloc_id(), &l.name, LayerColor::Preset((li % LAYER_COLORS.len()) as u8));
|
||||
layer.visible = l.visible;
|
||||
layer.locked = l.locked;
|
||||
if let Some(c) = layer.children_mut() {
|
||||
*c = children;
|
||||
}
|
||||
Arc::new(layer)
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
doc.layers = built;
|
||||
warnings.extend(crate::cmd::fonts::set_font_warning(fonts));
|
||||
Ok(ids)
|
||||
}
|
||||
|
||||
/// Point type `t` as a new node of `doc`, in [Normal Character Style] with the face, size and fill
|
||||
/// `t` gives, laid out.
|
||||
fn type_node(doc: &mut Document, t: import::OutType) -> Node {
|
||||
let mut style = crate::cmd::textstyles::normal_char_style(doc);
|
||||
style.font_version = None;
|
||||
style.font_axes.clear();
|
||||
style.font_family = t.font_family;
|
||||
match t.font_style {
|
||||
Some(s) => style.font_style = s,
|
||||
None => {
|
||||
style.font_style = CharStyle::default().font_style;
|
||||
crate::cmd::textedit::fit_font_style(&mut style);
|
||||
}
|
||||
}
|
||||
style.size = t.font_size;
|
||||
if let Some(fill) = t.fill {
|
||||
style.fill = fill;
|
||||
}
|
||||
let mut text = TextObject::point(Point::ZERO, &t.text, style);
|
||||
text.xf = t.transform;
|
||||
text.para = crate::cmd::create::new_type_para();
|
||||
text.system_layout = doc.setup.system_layout;
|
||||
crate::cmd::typecmd::refresh_bounds(&mut text);
|
||||
let mut n = Node::new(doc.alloc_id(), NodeKind::Text(Box::new(text)));
|
||||
n.name = t.name;
|
||||
n
|
||||
}
|
||||
|
||||
/// Image `im` as a new node of `doc`, its pixels stored in `doc` as a PNG.
|
||||
fn image_node(doc: &mut Document, im: import::OutImage) -> Result<Node> {
|
||||
let pixels = image::RgbaImage::from_raw(im.width, im.height, im.rgba).ok_or_else(|| err("the image's pixels don't match its size"))?;
|
||||
let stored = super::load::as_png(pixels, None, None)?;
|
||||
let image = ImageObject {
|
||||
key: stored.key.clone(),
|
||||
width: stored.width,
|
||||
height: stored.height,
|
||||
xf: im.transform,
|
||||
link: None,
|
||||
placement: Default::default(),
|
||||
pixels: None,
|
||||
};
|
||||
doc.images.insert(stored.key, stored.blob);
|
||||
let mut n = Node::new(doc.alloc_id(), NodeKind::Image(Box::new(image)));
|
||||
n.name = im.name;
|
||||
Ok(n)
|
||||
}
|
||||
|
||||
/// Gives `doc` the artboards `boards` an importer returned, in order, in place of its one.
|
||||
fn set_artboards(doc: &mut Document, boards: Vec<import::OutArtboard>) {
|
||||
let Some(template) = doc.artboards.first().cloned() else { return };
|
||||
doc.artboards =
|
||||
boards.into_iter().zip(1u32..).map(|(b, id)| vectorcraft_doc::Artboard { id, name: b.name, rect: b.rect, ..template.clone() }).collect();
|
||||
}
|
||||
|
||||
/// The artboard of art with bounds `r`: `r` within ±[`MAX_COORD`], at least 1 pt wide and high
|
||||
/// about its center (the artboard of a single line or point). A side that would pass the edge
|
||||
/// moves inward, so art at the edge keeps an artboard the document's edits accept.
|
||||
|
||||
@@ -268,16 +268,22 @@ fn from_editing_data_alone(opened: &vectorcraft_pdf::Opened, opts: &LoadOptions)
|
||||
if !every_page(opened.page_count(), opts) || !opts.layers || !opts.editing_data {
|
||||
return None;
|
||||
}
|
||||
Some(editing_copy_alone(&decoded_copy(opened)?, opts))
|
||||
// A placeholder page's fonts aren't the art's.
|
||||
Some(editing_copy_alone(&decoded_copy(opened)?, opts, Default::default()))
|
||||
}
|
||||
|
||||
/// [`from_editing_data_alone`] of `decoded`, the editor's copy already read and decoded, or why it
|
||||
/// can't be decoded.
|
||||
fn editing_copy_alone(decoded: &std::result::Result<Vec<u8>, String>, opts: &LoadOptions) -> Result<(Document, Vec<String>)> {
|
||||
/// can't be decoded, with `widths`, the widths the file's PDF part gives the characters of its
|
||||
/// fonts, which tell installed copies of a font apart ([`vectorcraft_eps::AiLayers::with_page_widths`]).
|
||||
fn editing_copy_alone(
|
||||
decoded: &std::result::Result<Vec<u8>, String>,
|
||||
opts: &LoadOptions,
|
||||
widths: vectorcraft_pdf::PageWidths,
|
||||
) -> Result<(Document, Vec<String>)> {
|
||||
decoded
|
||||
.as_ref()
|
||||
.map_err(Clone::clone)
|
||||
.and_then(|data| vectorcraft_eps::ai_alone_decoded(data, opts.legacy_names))
|
||||
.and_then(|data| vectorcraft_eps::ai_alone_decoded(data, opts.legacy_names, widths))
|
||||
.map_err(|why| err(format!("this file was saved without PDF compatibility, and its editing data can't be read ({why})")))
|
||||
}
|
||||
|
||||
@@ -473,6 +479,10 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
|
||||
Err(e) => Err(err(e)),
|
||||
};
|
||||
let mut read = restore_or_import(editing, || {
|
||||
// The widths the PDF part gives the characters of its fonts, which tell installed
|
||||
// copies of a font apart: read once, when the editing copy is.
|
||||
let page_widths = std::cell::OnceCell::new();
|
||||
let widths = || page_widths.get_or_init(|| opened.as_ref().map(vectorcraft_pdf::Opened::page_widths).unwrap_or_default()).clone();
|
||||
// Type all from the text document and nothing that needs the PDF part: the layers
|
||||
// alone, the PDF part not imported. Else what was read of the layers is kept for
|
||||
// reading them with the PDF part.
|
||||
@@ -480,7 +490,7 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
|
||||
if let Some((o, private)) = opened.as_ref().ok().filter(|_| reads_layers_alone(opts)).and_then(|o| Some((o, editing_copy(o, opts)?)))
|
||||
{
|
||||
let pages = o.trim_pages();
|
||||
match vectorcraft_eps::ai_layers_alone_decoded(private, &pages.sizes, pages.user_unit, opts.legacy_names) {
|
||||
match vectorcraft_eps::ai_layers_alone_decoded(private, &pages.sizes, pages.user_unit, opts.legacy_names, widths()) {
|
||||
Ok((mut doc, warnings)) => {
|
||||
doc.setup.bleed = pages.bleed;
|
||||
editing_data = true;
|
||||
@@ -502,9 +512,9 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
|
||||
// decoded draws nothing either): its notes are at most the page's own.
|
||||
let empty = draws_nothing(&r.document) && r.warnings.iter().all(|w| is_page_note(w));
|
||||
let copy_alone = || match &private {
|
||||
Some(private) => Some(editing_copy_alone(private, opts)),
|
||||
Some(private) => Some(editing_copy_alone(private, opts, widths())),
|
||||
None if layers.is_some() => {
|
||||
opened.as_ref().ok().and_then(|o| editing_copy(o, opts)).map(|p| editing_copy_alone(&p, opts))
|
||||
opened.as_ref().ok().and_then(|o| editing_copy(o, opts)).map(|p| editing_copy_alone(&p, opts, widths()))
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
@@ -516,7 +526,7 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
|
||||
let (doc, warnings, read) = match alone {
|
||||
Some((doc, warnings)) => (doc, warnings, true),
|
||||
None => {
|
||||
let layers = layers.or_else(|| private.map(vectorcraft_eps::AiLayers::decoded));
|
||||
let layers = layers.or_else(|| private.map(|p| vectorcraft_eps::AiLayers::decoded(p).with_page_widths(widths())));
|
||||
through_editing_data(layers, opts, r.document, r.warnings, r.user_unit)
|
||||
}
|
||||
};
|
||||
|
||||
@@ -2234,3 +2234,110 @@ fn an_illustrator_ai_file_opens_with_its_layers_closed() {
|
||||
assert_eq!(r["restored"], json!(true), "{r}");
|
||||
assert_eq!(open_rows(&s).1, ["Art", "Hidden"]);
|
||||
}
|
||||
|
||||
/// A `.ai` whose layer `Art` holds one line of type, `Hamburg`, that its text document sets in the
|
||||
/// font of PostScript name `name` (a font record without a version), and whose PDF part sets it in
|
||||
/// a subset of that font that gives each character the width `width` gives it, in thousandths of an
|
||||
/// em. With `square`, the layer and the page have a gray square too. The editing copy's artboard is
|
||||
/// 200 × 100 pt, and the page `page_width` × 100.
|
||||
fn type_in_copy_ai(name: &str, square: bool, page_width: f64, width: impl Fn(char) -> f64) -> Vec<u8> {
|
||||
let story = "Hamburg";
|
||||
let n = story.chars().count() + 1;
|
||||
let document = format!(
|
||||
"/0 << /1 << /0 [ << /0 << /0 << /0 ({name}) >> >> >> ] >> /8 << /0 [ << /0 << /0 [ 0 0 ] /2 << /2 [ 1 0 0 1 0 0 ] >> >> >> ] >> >>\n\
|
||||
/1 << /1 [ << /0 << /0 ({story}\r) /5 << /0 [ << /0 << /0 << /0 () /5 << /0 0 >> /6 0 >> >> /1 {n} >> ] >> \
|
||||
/6 << /0 [ << /0 << /0 << /0 () /5 0 /6 << /0 0 /1 10.0 >> >> >> /1 {n} >> ] >> >> \
|
||||
/1 << /0 [ << /0 0 >> ] /2 [ << /99 /PC /6 [ << /99 /F /0 << /0 [ 8105.5 8176.5 ] >> /6 [ << /99 /R /6 [ << /99 /R /6 [ << /99 /L /6 [ \
|
||||
<< /99 /S /0 << /0 [ 0.0 0.0 ] >> /15 << /0 {n} >> >> ] >> ] >> ] >> ] >> ] >> ] >> >> ] /2 << /1 12.0 >> >>\n"
|
||||
);
|
||||
let lines: Vec<String> = ascii85(document.as_bytes()).as_bytes().chunks(60).map(|c| format!("%{}", String::from_utf8_lossy(c))).collect();
|
||||
let text = "/AI11Text :\n0 /FreeUndo ,\n0 /FrameIndex ,\n0 /StoryIndex ,\n;\n";
|
||||
let (art, drawn) =
|
||||
if square { (format!("0.5 g\n{}f\n{text}", ai::rect(120.0, 20.0, 160.0, 60.0)), "0.5 g 120 20 40 40 re f ") } else { (text.to_string(), "") };
|
||||
let body = format!(
|
||||
"%AI3_TemplateBox: 100 50 100 50\n{}%AI11_BeginTextDocument\n/AI11TextDocument : /ASCII85Decode ,\n{}\n%AI11_EndTextDocument\n",
|
||||
ai::layer("Art", &art),
|
||||
lines.join("\n")
|
||||
);
|
||||
let data = ai::editing_data(200.0, 100.0, &body);
|
||||
let widths: Vec<String> = (32u8..=126).map(char::from).map(|c| if story.contains(c) { width(c).to_string() } else { "0".into() }).collect();
|
||||
let page = PdfPage {
|
||||
resources: format!(
|
||||
"/Font << /F1 << /Type /Font /Subtype /TrueType /BaseFont /ABCDEF+{name} /FirstChar 32 /Widths [{}] /Encoding /WinAnsiEncoding >> >>",
|
||||
widths.join(" ")
|
||||
),
|
||||
entries: format!("/PieceInfo << /Illustrator << /Private << /AIPrivateData1 {} 0 R /NumBlock 1 >> >> >>", first_extra(1)),
|
||||
// A page that is only type, with its art box, isn't a placeholder.
|
||||
art: Some([0.0, 0.0, page_width, 100.0]),
|
||||
..PdfPage::new(page_width, 100.0, &format!("{drawn}BT /F1 10 Tf 14 65 Td ({story}) Tj ET"))
|
||||
};
|
||||
pdf_with(&[page], &[&format!("<< /Length {} >>\nstream\n{data}\nendstream", data.len())], None)
|
||||
}
|
||||
|
||||
/// Type from the text document of a `.ai` whose font record keeps no version, where two installed
|
||||
/// copies of the font share its PostScript name, family and style and differ in their widths, is
|
||||
/// set in the copy that sets its characters at the widths the file's PDF part gives them: whether
|
||||
/// its layers open alone, with the PDF part imported, or from the editing copy alone because the PDF
|
||||
/// part is only type (read after the layers alone, on a page of another size, were not used).
|
||||
#[test]
|
||||
fn type_from_the_text_document_takes_the_copy_its_pdf_part_sets_it_in() {
|
||||
let (db, width) = (vectorcraft_text::FontDb::global(), install_width_copies("Pagewtest Ink", "PagewtestInk-Regular"));
|
||||
let trim = LoadOptions { crop: vectorcraft_pdf::CropTo::Trim, ..Default::default() };
|
||||
// (a square beside the type, the page's width, the options, whether the PDF part is imported)
|
||||
let cases = [
|
||||
(true, 200.0, &LoadOptions::default(), false),
|
||||
(true, 200.0, &trim, true),
|
||||
(false, 200.0, &LoadOptions::default(), false),
|
||||
(false, 200.0, &trim, true),
|
||||
(false, 260.0, &LoadOptions::default(), true),
|
||||
];
|
||||
for (square, page_width, opts, imported) in cases {
|
||||
let file = type_in_copy_ai("PagewtestInk-Regular", square, page_width, &width);
|
||||
let before = vectorcraft_pdf::imports_of(&file);
|
||||
let loaded = load_with("copies.ai", &file, opts).unwrap();
|
||||
let case = format!("square {square}, page {page_width}, {:?}: {:?}", opts.crop, loaded.warnings);
|
||||
assert!(loaded.editing_data, "{case}");
|
||||
assert_eq!(vectorcraft_pdf::imports_of(&file) > before, imported, "{case}");
|
||||
let art = loaded.doc.layers[0].children().unwrap();
|
||||
assert_eq!(art.len(), 1 + usize::from(square), "{case}");
|
||||
let Some(NodeKind::Text(t)) = art.iter().map(|n| &n.kind).find(|k| matches!(k, NodeKind::Text(_))) else { panic!("type: {case}") };
|
||||
assert_eq!(t.plain_text(), "Hamburg");
|
||||
assert_eq!(db.style_face(&t.runs[0].style).unwrap().version, "1.1", "{case}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Installs two copies of family `family` and PostScript name `name`: Inter as version 1.0, loaded
|
||||
/// first, and Source Sans 3 as 1.1, whose advances (thousandths of an em) the returned function gives.
|
||||
fn install_width_copies(family: &str, name: &str) -> impl Fn(char) -> f64 + use<> {
|
||||
let db = vectorcraft_text::FontDb::global();
|
||||
for (inter, version) in [(true, "1.0"), (false, "1.1")] {
|
||||
let font = vectorcraft_text::test_fonts::named_copy(inter, (family, "Regular", version, name)).unwrap();
|
||||
assert_eq!(db.add_font(font), 1);
|
||||
}
|
||||
let newer = db.postscript_faces(name).into_iter().find(|f| f.version == "1.1").unwrap();
|
||||
move |c: char| newer.advance(newer.glyph_for(c)) * 1000.0 / newer.units_per_em()
|
||||
}
|
||||
|
||||
/// Type the PDF part's widths set in the second copy of its font is saved as `.ai` with that
|
||||
/// copy's version in its font record, so it opens in the same copy again, from the editing copy
|
||||
/// alone as from the whole file.
|
||||
#[test]
|
||||
fn type_in_the_copy_its_pdf_part_sets_comes_back_in_it_from_a_save() {
|
||||
let (db, width) = (vectorcraft_text::FontDb::global(), install_width_copies("Pagewrt Ink", "PagewrtInk-Regular"));
|
||||
let mut s = Session::new();
|
||||
let r = open(&mut s, "copies.ai", &type_in_copy_ai("PagewrtInk-Regular", true, 200.0, &width), json!({})).unwrap();
|
||||
let saved = s.execute("file.saveCopy", &json!({"format": "ai"})).unwrap();
|
||||
let bytes = vectorcraft_format::base64_decode(saved["dataBase64"].as_str().unwrap()).unwrap();
|
||||
let versions = |doc: &vectorcraft_doc::Document| -> Vec<String> {
|
||||
let art = doc.layers[0].children().unwrap();
|
||||
art.iter()
|
||||
.filter_map(|n| if let NodeKind::Text(t) = &n.kind { Some(db.style_face(&t.runs[0].style).unwrap().version.clone()) } else { None })
|
||||
.collect()
|
||||
};
|
||||
assert_eq!(versions(&s.doc().unwrap().doc), ["1.1"], "{r}");
|
||||
let loaded = load_with("saved.ai", &bytes, &LoadOptions { native: false, ..Default::default() }).unwrap();
|
||||
assert!(loaded.editing_data, "{:?}", loaded.warnings);
|
||||
assert_eq!(versions(&loaded.doc), ["1.1"], "{:?}", loaded.warnings);
|
||||
let private = vectorcraft_pdf::illustrator_data(&bytes, None).unwrap();
|
||||
assert_eq!(versions(&vectorcraft_eps::ai_alone(&private).unwrap().0), ["1.1"]);
|
||||
}
|
||||
@@ -602,6 +602,53 @@ fn relink_and_update_follow_the_clipping_path_of_a_linked_psd() {
|
||||
assert_eq!(clip_group(&s.doc().unwrap().doc, group), (squared, true, NodeId(image)), "links.update reads the clipping path again");
|
||||
}
|
||||
|
||||
/// Place with Replace of an image changed by Perspective Distort or Free Distort by a clipped PSD
|
||||
/// file with many more pixels keeps its corners when the image is tiny: the new image's transform
|
||||
/// is the old one scaled down to the new pixel size, which is invertible however small it is.
|
||||
#[test]
|
||||
fn replacing_a_tiny_distorted_image_by_a_large_clipped_psd_keeps_its_corners() {
|
||||
let dir = vectorcraft_testkit::TempDir::new("psd-replace-tiny-distorted");
|
||||
let plane = vec![255u8; 2000 * 2000];
|
||||
let zero = vec![0u8; 2000 * 2000];
|
||||
let big = psd(1, 3, (2000, 2000), 8, 3, &[], &triangle_resources(), &[], &raw(&[&plane, &zero, &zero]));
|
||||
let cut = write_file(&dir, "big.psd", &big);
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
|
||||
let png = crate::tests_links::png(4, 4, [0, 0, 255]);
|
||||
let r = s
|
||||
.execute("file.place", &json!({"name": "a.png", "dataBase64": vectorcraft_format::base64_encode(&png), "rect": [100, 100, 0.001, 0.001]}))
|
||||
.unwrap();
|
||||
let old = NodeId(r["ids"][0].as_u64().unwrap());
|
||||
s.execute("select.set", &json!({"ids": [old.0]})).unwrap();
|
||||
s.execute("object.distort", &json!({"corners": [[100, 100], [100.001, 100.0001], [100.0009, 100.001], [99.9998, 100.0008]]})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.node(old).unwrap().is_distorted_image(), "the old image is distorted");
|
||||
let corners = s.doc().unwrap().doc.node(old).unwrap().image_corners().unwrap();
|
||||
let r = s.execute("file.place", &json!({"path": cut, "replace": true})).unwrap();
|
||||
let image = s.doc().unwrap().doc.node(NodeId(r["image"].as_u64().unwrap())).unwrap().clone();
|
||||
assert!(image.is_distorted_image());
|
||||
assert_eq!(image.image_corners().unwrap(), corners);
|
||||
}
|
||||
|
||||
/// Place with Replace of a clipped PSD file's image changed by Perspective Distort or Free Distort
|
||||
/// by a DCS file keeps the image's corners: the DCS file's image fills them.
|
||||
#[test]
|
||||
fn replacing_a_distorted_clipped_psd_by_a_dcs_file_keeps_its_corners() {
|
||||
let dir = vectorcraft_testkit::TempDir::new("psd-replace-distorted-dcs");
|
||||
let cut = write_file(&dir, "cut.psd", &red_psd(&triangle_resources()));
|
||||
let dcs = write_file(&dir, "pic.eps", &crate::tests::dcs::two_plates());
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 50})).unwrap();
|
||||
let r = s.execute("file.place", &json!({"path": cut, "at": [50, 25]})).unwrap();
|
||||
let (group, image) = (NodeId(r["ids"][0].as_u64().unwrap()), NodeId(r["image"].as_u64().unwrap()));
|
||||
s.execute("select.set", &json!({"ids": [group.0]})).unwrap();
|
||||
s.execute("object.distort", &json!({"corners": [[0, 0], [100, 8], [90, 50], [6, 44]]})).unwrap();
|
||||
let corners = s.doc().unwrap().doc.node(image).unwrap().image_corners().unwrap();
|
||||
let r = s.execute("file.place", &json!({"path": dcs, "replace": true})).unwrap();
|
||||
let new = s.doc().unwrap().doc.node(NodeId(r["image"].as_u64().unwrap())).unwrap().clone();
|
||||
assert!(new.is_distorted_image(), "the DCS file's image takes the corners");
|
||||
assert_eq!(new.image_corners().unwrap(), corners);
|
||||
}
|
||||
|
||||
/// links.relink follows the clipping path of a linked PSD file for an image changed by Perspective
|
||||
/// Distort or Free Distort too: the new file's clipping path is mapped through the image's corners,
|
||||
/// a clip group of the old file's clipping path loses it when the new file names none, and a later
|
||||
|
||||
@@ -456,6 +456,30 @@ fn placed_embedded_files_bring_their_slices_with_the_art_in_one_undo_step() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A file placed with Replace over an image changed by Perspective Distort or Free Distort takes
|
||||
/// its corners, and its slices cover what the corners put their part of the pixels on.
|
||||
#[test]
|
||||
fn slices_placed_over_a_distorted_image_follow_its_corners() {
|
||||
let f = with_resource(&psd(false), 1050, &v6(&[user("a", [0, 0, 10, 10])], &[]));
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
|
||||
let png = crate::tests_links::png(4, 4, [0, 0, 255]);
|
||||
s.execute("file.place", &json!({"name": "a.png", "dataBase64": b64(&png), "at": [100, 100]})).unwrap();
|
||||
s.execute("object.distort", &json!({"corners": [[100, 100], [160, 104], [150, 140], [96, 136]]})).unwrap();
|
||||
let r = s.execute("file.place", &json!({"name": "poster.psd", "dataBase64": b64(&f), "replace": true})).unwrap();
|
||||
assert_eq!(r["slices"].as_array().map(Vec::len), Some(1), "{r}");
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let image = d.node(vectorcraft_doc::NodeId(r["ids"][0].as_u64().unwrap())).unwrap();
|
||||
assert!(image.is_distorted_image());
|
||||
let vectorcraft_doc::NodeKind::Image(im) = &image.kind else { panic!("an image") };
|
||||
// The top left quarter of the 20 × 20 px canvas.
|
||||
let (w, h) = (f64::from(im.width) / 2.0, f64::from(im.height) / 2.0);
|
||||
let want = image.image_map().unwrap().map_rect_bbox(Rect::new(0.0, 0.0, w, h)).unwrap();
|
||||
let got = slices(&s)[0].0;
|
||||
let near = |a: f64, b: f64| (a - b).abs() < 1e-6;
|
||||
assert!(near(got.x0, want.x0) && near(got.y0, want.y0) && near(got.x1, want.x1) && near(got.y1, want.y1), "{got:?} vs {want:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn linked_files_are_placed_without_their_slices() {
|
||||
let dir = std::env::temp_dir().join(format!("vc-psd-slices-{}", std::process::id()));
|
||||
|
||||
@@ -114,7 +114,17 @@ pub fn missing_fonts(d: &Document) -> Vec<MissingFont> {
|
||||
/// `text.missingFonts`'s answer for the open document `st`, where searches go by `rules` (this
|
||||
/// computer's when `None`).
|
||||
pub fn missing_fonts_of(st: &DocState, rules: Option<&findfiles::Rules>) -> Value {
|
||||
let fonts: Vec<Value> = missing_fonts(&st.doc)
|
||||
let fonts = missing_font_rows(&st.doc);
|
||||
let mut out = json!({ "count": fonts.len(), "fonts": fonts });
|
||||
if let Some(dir) = fonts_next_to_document(st, rules) {
|
||||
out["fontsNextToDocument"] = json!(dir);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// `text.missingFonts`'s `fonts` rows for `d` ([`missing_fonts`]).
|
||||
pub fn missing_font_rows(d: &Document) -> Vec<Value> {
|
||||
missing_fonts(d)
|
||||
.into_iter()
|
||||
.map(|m| {
|
||||
json!({
|
||||
@@ -122,26 +132,26 @@ pub fn missing_fonts_of(st: &DocState, rules: Option<&findfiles::Rules>) -> Valu
|
||||
"resolved": m.resolved.map(|(family, style)| json!({ "family": family, "style": style })),
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let mut out = json!({ "count": fonts.len(), "fonts": fonts });
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// `text.missingFonts`'s `fontsNextToDocument` for the open document `st`, where searches go by
|
||||
/// `rules` (this computer's when `None`).
|
||||
pub fn fonts_next_to_document(st: &DocState, rules: Option<&findfiles::Rules>) -> Option<String> {
|
||||
// File › Package puts the fonts in a `Fonts` folder next to the packaged document. The folder
|
||||
// is made absolute against the working folder when the document's path is relative. It is
|
||||
// offered when a search may start there, as far as the rules tell without listing a folder.
|
||||
if let Some(dir) = st.path.as_deref().and_then(|p| Path::new(p).parent()).map(|d| d.join("Fonts")).filter(|d| d.is_dir()) {
|
||||
let dir = super::fileio::absolute_path(&dir.to_string_lossy());
|
||||
let system;
|
||||
let rules = match rules {
|
||||
Some(rules) => rules,
|
||||
None => {
|
||||
system = findfiles::Rules::system();
|
||||
&system
|
||||
}
|
||||
};
|
||||
if std::fs::canonicalize(&dir).is_ok_and(|c| rules.refusal_unlisted(&c).is_none()) {
|
||||
out["fontsNextToDocument"] = json!(dir);
|
||||
let dir = st.path.as_deref().and_then(|p| Path::new(p).parent()).map(|d| d.join("Fonts")).filter(|d| d.is_dir())?;
|
||||
let dir = super::fileio::absolute_path(&dir.to_string_lossy());
|
||||
let system;
|
||||
let rules = match rules {
|
||||
Some(rules) => rules,
|
||||
None => {
|
||||
system = findfiles::Rules::system();
|
||||
&system
|
||||
}
|
||||
}
|
||||
out
|
||||
};
|
||||
std::fs::canonicalize(&dir).is_ok_and(|c| rules.refusal_unlisted(&c).is_none()).then_some(dir)
|
||||
}
|
||||
|
||||
fn missing(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
|
||||
@@ -91,6 +91,8 @@
|
||||
//! deselects it as before), Global Edit ends when fewer than two members are left, and leaving
|
||||
//! one out is not an undo step.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde::Serialize;
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{Appearance, AppearanceItem, Document, FillLayer, Node, NodeId, NodeKind, Scaling, Shared, StrokeLayer};
|
||||
@@ -192,6 +194,51 @@ impl Options {
|
||||
/// Outlines with their layer colours ([`highlights`]).
|
||||
pub type Outlines = Vec<(BezPath, [u8; 3])>;
|
||||
|
||||
/// The outlines [`highlights`] gives the canvas, grouped by layer color. The canvas asks every frame and gets the same
|
||||
/// allocation back until the outlines are found again.
|
||||
#[derive(Debug, Default, PartialEq)]
|
||||
pub struct Highlights {
|
||||
/// A number given to each set of outlines when it is found, and never to another set: the canvas keeps the lines
|
||||
/// it stroked for these outlines while the number stays the same.
|
||||
pub revision: u64,
|
||||
/// The outlines in each layer color, the colors in the order of their first outline.
|
||||
pub groups: Vec<([u8; 3], std::sync::Arc<[BezPath]>)>,
|
||||
}
|
||||
|
||||
/// The [`Highlights::revision`] the next set of outlines takes.
|
||||
static NEXT_HIGHLIGHTS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
|
||||
|
||||
/// [`Highlights`] with no outline, shared so the frames that show none allocate nothing.
|
||||
static NO_HIGHLIGHTS: std::sync::LazyLock<std::sync::Arc<Highlights>> = std::sync::LazyLock::new(Default::default);
|
||||
|
||||
impl Highlights {
|
||||
/// `outlines` grouped by color, under a new revision.
|
||||
fn new(outlines: Outlines) -> std::sync::Arc<Self> {
|
||||
if outlines.is_empty() {
|
||||
return NO_HIGHLIGHTS.clone();
|
||||
}
|
||||
let mut groups: Vec<([u8; 3], Vec<BezPath>)> = vec![];
|
||||
for (path, color) in outlines {
|
||||
match groups.iter_mut().find(|(c, _)| *c == color) {
|
||||
Some((_, paths)) => paths.push(path),
|
||||
None => groups.push((color, vec![path])),
|
||||
}
|
||||
}
|
||||
let revision = NEXT_HIGHLIGHTS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
std::sync::Arc::new(Highlights { revision, groups: groups.into_iter().map(|(c, paths)| (c, paths.into())).collect() })
|
||||
}
|
||||
|
||||
/// How many outlines there are, in every color.
|
||||
pub fn len(&self) -> usize {
|
||||
self.groups.iter().map(|(_, paths)| paths.len()).sum()
|
||||
}
|
||||
|
||||
/// Whether there is no outline.
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.groups.iter().all(|(_, paths)| paths.is_empty())
|
||||
}
|
||||
}
|
||||
|
||||
/// A Global Edit in progress (per document; not saved, not an undo step).
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct GlobalEdit {
|
||||
@@ -200,7 +247,7 @@ pub struct GlobalEdit {
|
||||
/// outline onto its own.
|
||||
pub members: Vec<(NodeId, Affine)>,
|
||||
/// [`highlights`] as of a document revision: the canvas asks every frame.
|
||||
outlines: std::cell::RefCell<Option<(u64, Outlines)>>,
|
||||
outlines: std::cell::RefCell<Option<(u64, std::sync::Arc<Highlights>)>>,
|
||||
}
|
||||
|
||||
/// An outline reduced to its form: the anchors and handles placed in a unit box, with what tells
|
||||
@@ -214,8 +261,20 @@ struct Form {
|
||||
frame: Affine,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// Tests: how many times [`Form::of`] reduced an object to its form on this thread.
|
||||
pub(crate) static FORMS_MADE: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
/// Tests: how many times [`outlines`] made the outline of a highlighted object on this thread.
|
||||
pub(crate) static OUTLINES_MADE: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
/// Tests: how many objects [`matches`] looked at on this thread.
|
||||
pub(crate) static OBJECTS_WALKED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
impl Form {
|
||||
fn of(n: &Node) -> Option<Self> {
|
||||
#[cfg(test)]
|
||||
FORMS_MADE.with(|c| c.set(c.get() + 1));
|
||||
let mut f = Self { tag: vec![], symbols: vec![], points: vec![], frame: Affine::IDENTITY };
|
||||
f.add(n, 0)?;
|
||||
let first = *f.points.first()?;
|
||||
@@ -450,8 +509,8 @@ fn matches(s: &Session, o: &Options) -> Result<Vec<(NodeId, Affine)>> {
|
||||
),
|
||||
};
|
||||
let on = |r: Rect, b: Rect| b.intersect(r).area() > 0.0 || vectorcraft_doc::artboard_holds(r, b.center());
|
||||
let in_scope = |n: &Node| {
|
||||
let Some(b) = n.geometric_bounds_with(&symbols) else { return false };
|
||||
let in_scope = |b: Option<Rect>| {
|
||||
let Some(b) = b else { return false };
|
||||
if !d.artboards.iter().any(|a| on(a.rect, b)) {
|
||||
return o.include_canvas;
|
||||
}
|
||||
@@ -459,15 +518,19 @@ fn matches(s: &Session, o: &Options) -> Result<Vec<(NodeId, Affine)>> {
|
||||
};
|
||||
// A copy that lies the same way has the size of the selected object when their boxes are as
|
||||
// wide and as high; a turned copy, when the transform that lays the object on it doesn't scale.
|
||||
let same_size = |n: &Node, xf: Affine, turned: bool| {
|
||||
let same_size = |b: Option<Rect>, xf: Affine, turned: bool| {
|
||||
if turned {
|
||||
close(xf.determinant().abs().sqrt(), 1.0)
|
||||
} else {
|
||||
matches!((key_size, size(n)), (Some((w, h)), Some((w2, h2))) if close(w, w2) && close(h, h2))
|
||||
matches!((key_size, b), (Some((w, h)), Some(b)) if close(w, b.width()) && close(h, b.height()))
|
||||
}
|
||||
};
|
||||
let mut out = vec![(*id, Affine::IDENTITY)];
|
||||
let mut cache = st.global_edit_forms.0.borrow_mut();
|
||||
let mut pass = cache.forms.pass();
|
||||
super::select::walk_selectable(d, st.isolation, |n| {
|
||||
#[cfg(test)]
|
||||
OBJECTS_WALKED.with(|c| c.set(c.get() + 1));
|
||||
if n.id == *id || out.len() >= MAX_MEMBERS {
|
||||
return false;
|
||||
}
|
||||
@@ -482,21 +545,134 @@ fn matches(s: &Session, o: &Options) -> Result<Vec<(NodeId, Affine)>> {
|
||||
_ => false,
|
||||
};
|
||||
// The object count first: it turns most objects down before their form is made.
|
||||
if n.children().map(Vec::len) == count
|
||||
&& let Some((xf, turned)) = Form::of(n).and_then(|f| form.onto(&f)).filter(|_| supported(n))
|
||||
&& (!o.size || same_size(n, xf, turned))
|
||||
&& (!o.appearance || same_look(key, n))
|
||||
&& in_scope(n)
|
||||
{
|
||||
out.push((n.id, xf));
|
||||
// A group taken is taken whole, as compound paths, symbol instances and the others are.
|
||||
return false;
|
||||
if n.children().map(Vec::len) != count {
|
||||
return look_in;
|
||||
}
|
||||
let seen = pass.get(n, || Seen { form: Form::of(n).filter(|_| supported(n)), bounds: None });
|
||||
if let Some((xf, turned)) = seen.form.as_ref().and_then(|f| form.onto(f)) {
|
||||
let b = seen.bounds(n, &symbols);
|
||||
if (!o.size || same_size(b, xf, turned)) && (!o.appearance || same_look(key, n)) && in_scope(b) {
|
||||
out.push((n.id, xf));
|
||||
// A group taken is taken whole, as compound paths, symbol instances and the others are.
|
||||
return false;
|
||||
}
|
||||
}
|
||||
look_in
|
||||
});
|
||||
cache.forms.end(pass, d);
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// What [`matches`] and [`outlines`] found for each object they looked at, kept from one call to
|
||||
/// the next so that after an edit only the objects the edit replaced are measured again. A clone
|
||||
/// starts empty.
|
||||
#[derive(Default)]
|
||||
pub struct FormCache(std::cell::RefCell<FormCacheInner>);
|
||||
|
||||
#[derive(Default)]
|
||||
struct FormCacheInner {
|
||||
forms: ByNode<Seen>,
|
||||
/// The outline of each highlighted object, or `None` when it has none and its box is shown.
|
||||
outlines: ByNode<Option<BezPath>>,
|
||||
}
|
||||
|
||||
/// An object as [`matches`] found it.
|
||||
struct Seen {
|
||||
/// Its form, or `None` when Global Edit doesn't support it.
|
||||
form: Option<Form>,
|
||||
/// Its geometric bounds, once measured; not kept for an object with symbol instances, whose
|
||||
/// bounds follow the symbols' art.
|
||||
bounds: Option<Option<Rect>>,
|
||||
}
|
||||
|
||||
impl Seen {
|
||||
fn bounds(&mut self, n: &Node, symbols: &vectorcraft_doc::SymbolBoxes<'_>) -> Option<Rect> {
|
||||
if self.form.as_ref().is_some_and(|f| !f.symbols.is_empty()) {
|
||||
return n.geometric_bounds_with(symbols);
|
||||
}
|
||||
*self.bounds.get_or_insert_with(|| n.geometric_bounds_with(symbols))
|
||||
}
|
||||
}
|
||||
|
||||
/// Values found for nodes of a document, by node address. The layers they were found in are held,
|
||||
/// which keeps every node in them alive and unchanged (an edit replaces each node it changes), so
|
||||
/// no other node can have that address while its entry is here.
|
||||
struct ByNode<T> {
|
||||
layers: Vec<Arc<Node>>,
|
||||
values: ByAddress<T>,
|
||||
}
|
||||
|
||||
impl<T> Default for ByNode<T> {
|
||||
fn default() -> Self {
|
||||
Self { layers: vec![], values: ByAddress::default() }
|
||||
}
|
||||
}
|
||||
|
||||
/// Values by node address.
|
||||
type ByAddress<T> = std::collections::HashMap<usize, T, std::hash::BuildHasherDefault<AddressHasher>>;
|
||||
|
||||
/// Hashes a node address: a multiply that spreads its bits, with the high half folded into the low
|
||||
/// half (addresses are aligned, so their low bits are always the same).
|
||||
#[derive(Default)]
|
||||
struct AddressHasher(u64);
|
||||
|
||||
impl std::hash::Hasher for AddressHasher {
|
||||
fn write(&mut self, bytes: &[u8]) {
|
||||
for b in bytes {
|
||||
self.0 = (self.0 ^ u64::from(*b)).wrapping_mul(0x100_0000_01b3);
|
||||
}
|
||||
}
|
||||
|
||||
fn write_usize(&mut self, n: usize) {
|
||||
let x = (n as u64).wrapping_mul(0x9e37_79b9_7f4a_7c15);
|
||||
self.0 = x ^ (x >> 32);
|
||||
}
|
||||
|
||||
fn finish(&self) -> u64 {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
/// One walk of a document: the values it asks for, taken from the ones kept or found anew.
|
||||
struct Pass<T> {
|
||||
old: ByAddress<T>,
|
||||
new: ByAddress<T>,
|
||||
}
|
||||
|
||||
impl<T> Pass<T> {
|
||||
fn get(&mut self, n: &Node, find: impl FnOnce() -> T) -> &mut T {
|
||||
let at = std::ptr::from_ref(n) as usize;
|
||||
let old = &mut self.old;
|
||||
self.new.entry(at).or_insert_with(|| old.remove(&at).unwrap_or_else(find))
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> ByNode<T> {
|
||||
fn pass(&mut self) -> Pass<T> {
|
||||
let old = std::mem::take(&mut self.values);
|
||||
Pass { new: ByAddress::with_capacity_and_hasher(old.len(), Default::default()), old }
|
||||
}
|
||||
|
||||
/// Keep the values `pass` asked for, found in `d`.
|
||||
fn end(&mut self, pass: Pass<T>, d: &Document) {
|
||||
self.values = pass.new;
|
||||
self.layers.clone_from(&d.layers);
|
||||
}
|
||||
}
|
||||
|
||||
impl Clone for FormCache {
|
||||
fn clone(&self) -> Self {
|
||||
Self::default()
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for FormCache {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
let c = self.0.borrow();
|
||||
f.debug_struct("FormCache").field("forms", &c.forms.values.len()).field("outlines", &c.outlines.values.len()).finish()
|
||||
}
|
||||
}
|
||||
|
||||
fn can_toggle(s: &Session) -> std::result::Result<(), String> {
|
||||
let st = s.active().ok_or("no document open")?;
|
||||
if st.global_edit.is_some() {
|
||||
@@ -890,65 +1066,234 @@ fn keep_series_changes(before: &Document, d: &mut Document, edited: &[NodeId]) {
|
||||
/// highlights them while Global Edit is on. While it is off, with one supported object selected,
|
||||
/// they are the outlines of the objects Start Global Edit would take with the Global Edit Options
|
||||
/// ([`similar`]).
|
||||
pub fn highlights(s: &Session) -> Outlines {
|
||||
let Some(st) = s.active() else { return vec![] };
|
||||
pub fn highlights(s: &Session) -> std::sync::Arc<Highlights> {
|
||||
let Some(st) = s.active() else { return NO_HIGHLIGHTS.clone() };
|
||||
let Some(ge) = &st.global_edit else { return similar(s) };
|
||||
if let Some((rev, out)) = &*ge.outlines.borrow()
|
||||
&& *rev == st.revision
|
||||
{
|
||||
return out.clone();
|
||||
}
|
||||
let out = outlines(st, &ge.members);
|
||||
let out = Highlights::new(outlines(st, &ge.members));
|
||||
*ge.outlines.borrow_mut() = Some((st.revision, out.clone()));
|
||||
out
|
||||
}
|
||||
|
||||
/// [`similar`]'s outlines as of a document revision and the options they were found with.
|
||||
pub type SimilarCache = std::cell::RefCell<Option<(u64, Options, Outlines)>>;
|
||||
/// [`similar`]'s outlines as of a document revision, with what they were found from.
|
||||
pub type SimilarCache = std::cell::RefCell<Option<Similar>>;
|
||||
|
||||
/// [`similar`]'s outlines and what they were found from.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Similar {
|
||||
revision: u64,
|
||||
options: Options,
|
||||
/// The document, the one selected object and the isolated object they were found with.
|
||||
doc: Arc<Document>,
|
||||
key: NodeId,
|
||||
isolation: Option<NodeId>,
|
||||
out: Arc<Highlights>,
|
||||
}
|
||||
|
||||
/// Before Global Edit starts: with one supported object selected, the outlines of the other
|
||||
/// objects Start Global Edit would take now with the session's Global Edit Options, so the canvas
|
||||
/// shows them as soon as the object is selected. None while an interaction (a drag) is in
|
||||
/// progress, or when fewer than two objects would be taken. Kept per document revision and
|
||||
/// options, as finding them walks the whole document.
|
||||
pub fn similar(s: &Session) -> Outlines {
|
||||
let Some(st) = s.active() else { return vec![] };
|
||||
if st.global_edit.is_some() || st.interaction.is_some() || st.selection.objects.len() != 1 {
|
||||
return vec![];
|
||||
/// options, as finding them walks the whole document. After an edit that replaced only the
|
||||
/// selected object, and left what the others are compared with as it was (a move), the outlines
|
||||
/// found before are kept without a walk.
|
||||
pub fn similar(s: &Session) -> std::sync::Arc<Highlights> {
|
||||
let Some(st) = s.active() else { return NO_HIGHLIGHTS.clone() };
|
||||
// Global Edit is refused while an object of a dynamic symbol instance's art is selected.
|
||||
if st.global_edit.is_some() || st.interaction.is_some() || st.selection.objects.len() != 1 || super::edit::refuse_symbol_part(s).is_err() {
|
||||
return NO_HIGHLIGHTS.clone();
|
||||
}
|
||||
let o = &s.global_edit_options;
|
||||
if let Some((rev, opts, out)) = &*st.similar_outlines.borrow()
|
||||
&& *rev == st.revision
|
||||
&& opts == o
|
||||
let key = st.selection.objects[0];
|
||||
if let Some(c) = &mut *st.similar_outlines.borrow_mut()
|
||||
&& c.options == *o
|
||||
&& c.key == key
|
||||
&& c.isolation == st.isolation
|
||||
&& (c.revision == st.revision || Arc::ptr_eq(&c.doc, &st.doc) || only_key_changed(&c.doc, &st.doc, key))
|
||||
{
|
||||
return out.clone();
|
||||
c.revision = st.revision;
|
||||
c.doc = st.doc.clone();
|
||||
return c.out.clone();
|
||||
}
|
||||
let out = match matches(s, o) {
|
||||
let out = Highlights::new(match matches(s, o) {
|
||||
Ok(m) if m.len() >= 2 => outlines(st, &m),
|
||||
_ => vec![],
|
||||
};
|
||||
*st.similar_outlines.borrow_mut() = Some((st.revision, o.clone(), out.clone()));
|
||||
});
|
||||
*st.similar_outlines.borrow_mut() =
|
||||
Some(Similar { revision: st.revision, options: o.clone(), doc: st.doc.clone(), key, isolation: st.isolation, out: out.clone() });
|
||||
out
|
||||
}
|
||||
|
||||
/// Would [`matches`] find the same objects in `now` as in `then`, with `key` selected in both?
|
||||
/// True when the layers differ only in `key` and in the layers and groups that hold it (the same
|
||||
/// apart from their contents), `key` is compared with the others as before ([`same_key`]), and the
|
||||
/// rest of the document is the same. A group that holds `key` is never like it (its form holds
|
||||
/// `key`'s and more), so the walk looks into it before and after alike.
|
||||
fn only_key_changed(then: &Document, now: &Document, key: NodeId) -> bool {
|
||||
let mut found = None;
|
||||
let same_symbol = |a: &vectorcraft_doc::Symbol, b: &vectorcraft_doc::Symbol| {
|
||||
a.name == b.name && a.dynamic == b.dynamic && (Arc::ptr_eq(&a.art, &b.art) || a.art == b.art)
|
||||
};
|
||||
// Everything else in the document (artboards, symbol settings, editing modes) as it was: the
|
||||
// symbols' art is compared on its own, as one copy when no edit changed it.
|
||||
let rest = |d: &Document| {
|
||||
let mut d = d.clone();
|
||||
d.layers.clear();
|
||||
d.symbols.clear();
|
||||
d
|
||||
};
|
||||
if then.symbols.len() != now.symbols.len()
|
||||
|| !then.symbols.iter().zip(&now.symbols).all(|(a, b)| same_symbol(a, b))
|
||||
|| rest(then) != rest(now)
|
||||
|| !changed_only(&then.layers, &now.layers, key, &mut found)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
found.is_none_or(|(a, b)| same_key(a, b, &now.symbol_boxes()))
|
||||
}
|
||||
|
||||
/// Do `then` and `now` hold the same objects, apart from `key` and the layers and groups on the way
|
||||
/// to it? `found` takes the two versions of `key` when it changed.
|
||||
fn changed_only<'a>(then: &'a [Arc<Node>], now: &'a [Arc<Node>], key: NodeId, found: &mut Option<(&'a Node, &'a Node)>) -> bool {
|
||||
if then.len() != now.len() {
|
||||
return false;
|
||||
}
|
||||
then.iter().zip(now).all(|(a, b)| {
|
||||
if Arc::ptr_eq(a, b) {
|
||||
return true;
|
||||
}
|
||||
if a.id != b.id {
|
||||
return false;
|
||||
}
|
||||
if a.id == key {
|
||||
return found.replace((a, b)).is_none();
|
||||
}
|
||||
match (holder_children(a), holder_children(b)) {
|
||||
(Some(x), Some(y)) => same_holder(a, b) && changed_only(x, y, key, found),
|
||||
_ => false,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// The objects in a layer or a group.
|
||||
fn holder_children(n: &Node) -> Option<&[Arc<Node>]> {
|
||||
match &n.kind {
|
||||
NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => Some(children),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Are two versions of a layer or a group the same apart from the objects in them?
|
||||
fn same_holder(a: &Node, b: &Node) -> bool {
|
||||
let Node { id, name, visible, locked, opacity, blend, isolate, knockout, knockout_shape, appearance, kind, bbox_angle, extras } = a;
|
||||
let kinds = match (kind, &b.kind) {
|
||||
(
|
||||
NodeKind::Layer { color, template, printable, children: _, clip, preview, dim_images },
|
||||
NodeKind::Layer { color: c, template: t, printable: p, children: _, clip: cl, preview: pv, dim_images: di },
|
||||
) => color == c && template == t && printable == p && clip == cl && preview == pv && dim_images == di,
|
||||
(NodeKind::Group { children: _, clip }, NodeKind::Group { children: _, clip: c }) => clip == c,
|
||||
_ => false,
|
||||
};
|
||||
kinds
|
||||
&& *id == b.id
|
||||
&& *name == b.name
|
||||
&& *visible == b.visible
|
||||
&& *locked == b.locked
|
||||
&& *opacity == b.opacity
|
||||
&& *blend == b.blend
|
||||
&& *isolate == b.isolate
|
||||
&& *knockout == b.knockout
|
||||
&& *knockout_shape == b.knockout_shape
|
||||
&& *appearance == b.appearance
|
||||
&& *bbox_angle == b.bbox_angle
|
||||
&& *extras == b.extras
|
||||
}
|
||||
|
||||
/// How far apart two versions of the selected object's form may lie, in its unit box, and how much
|
||||
/// their sizes may differ (relative), for [`similar`] to keep the objects found like the first: a
|
||||
/// millionth of [`SAME`]. A move leaves the form the same but for rounding (the form is placed in
|
||||
/// its unit box by a transform that includes the move), well within this.
|
||||
const KEPT: f64 = 1e-12;
|
||||
|
||||
/// Are two versions of the selected object compared with the other objects in the same way by
|
||||
/// [`matches`]: the same form in a box of the same size and the same geometric size (a perspective
|
||||
/// projection changes that alone), within [`KEPT`], and the same fill and stroke in each object in
|
||||
/// them?
|
||||
fn same_key(a: &Node, b: &Node, symbols: &vectorcraft_doc::SymbolBoxes<'_>) -> bool {
|
||||
let near = |x: f64, y: f64| (x - y).abs() <= KEPT * x.abs().max(y.abs()).max(1.0);
|
||||
fn same_look(a: &Node, b: &Node) -> bool {
|
||||
fill_of(a) == fill_of(b)
|
||||
&& stroke_of(a) == stroke_of(b)
|
||||
&& match (a.children(), b.children()) {
|
||||
(Some(x), Some(y)) => x.len() == y.len() && x.iter().zip(y).all(|(p, q)| same_look(p, q)),
|
||||
(x, y) => x.is_none() && y.is_none(),
|
||||
}
|
||||
}
|
||||
if !(supported(a) && supported(b)) {
|
||||
return false;
|
||||
}
|
||||
let (Some(f), Some(g)) = (Form::of(a), Form::of(b)) else { return false };
|
||||
let (fl, gl) = (f.frame.as_coeffs(), g.frame.as_coeffs());
|
||||
let sizes = match (a.geometric_bounds_with(symbols), b.geometric_bounds_with(symbols)) {
|
||||
(Some(x), Some(y)) => near(x.width(), y.width()) && near(x.height(), y.height()),
|
||||
(x, y) => x.is_none() && y.is_none(),
|
||||
};
|
||||
f.tag == g.tag
|
||||
&& f.symbols == g.symbols
|
||||
&& f.points.len() == g.points.len()
|
||||
&& f.points.iter().zip(&g.points).all(|(p, q)| p.distance(*q) <= KEPT)
|
||||
&& fl[..4].iter().zip(&gl[..4]).all(|(x, y)| near(*x, *y))
|
||||
&& sizes
|
||||
&& same_look(a, b)
|
||||
}
|
||||
|
||||
/// The outlines of `members` that are not selected, hold no selected object and sit inside no
|
||||
/// selected object, in their layer's color.
|
||||
fn outlines(st: &crate::DocState, members: &[(NodeId, Affine)]) -> Outlines {
|
||||
let symbols = st.doc.symbol_boxes();
|
||||
members
|
||||
let mut cache = st.global_edit_forms.0.borrow_mut();
|
||||
let mut pass = cache.outlines.pass();
|
||||
let out = members
|
||||
.iter()
|
||||
.filter_map(|(id, _)| {
|
||||
let n = st.doc.node(*id).filter(|n| !holds(n, &st.selection.objects))?;
|
||||
if st.doc.ancestry(*id).is_some_and(|a| a.iter().any(|p| st.selection.objects.contains(p))) {
|
||||
return None;
|
||||
// One look-up of the object's place, then down through its layers and groups: none of
|
||||
// them may be selected, and the innermost layer gives the color.
|
||||
let (mut nodes, mut found, mut layer) = (&st.doc.layers, None, None);
|
||||
for i in st.doc.index_path(*id)? {
|
||||
let c: &Node = nodes.get(i)?;
|
||||
if st.selection.objects.contains(&c.id) {
|
||||
return None;
|
||||
}
|
||||
if c.is_layer() {
|
||||
layer = Some(c);
|
||||
}
|
||||
if let Some(ch) = c.children() {
|
||||
nodes = ch;
|
||||
}
|
||||
found = Some(c);
|
||||
}
|
||||
let path = match n.stroke_path() {
|
||||
Some(p) => p,
|
||||
let n = found.filter(|n| n.id == *id && !holds(n, &st.selection.objects))?;
|
||||
let color = match layer.map(|l| &l.kind) {
|
||||
Some(NodeKind::Layer { color, .. }) => color.rgb(),
|
||||
_ => vectorcraft_doc::LAYER_COLORS[0].1,
|
||||
};
|
||||
let path = match pass.get(n, || {
|
||||
#[cfg(test)]
|
||||
OUTLINES_MADE.with(|c| c.set(c.get() + 1));
|
||||
n.stroke_path()
|
||||
}) {
|
||||
Some(p) => p.clone(),
|
||||
None => n.geometric_bounds_with(&symbols)?.to_path(0.1),
|
||||
};
|
||||
Some((path, st.doc.layer_color(*id)))
|
||||
Some((path, color))
|
||||
})
|
||||
.collect()
|
||||
.collect();
|
||||
cache.outlines.end(pass, &st.doc);
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -576,23 +576,36 @@ struct ObjectOpacity {
|
||||
knockout_shape: bool,
|
||||
}
|
||||
|
||||
/// The series `id` belongs to when it is a graph series group or a path directly in one, as [`series_members`] finds
|
||||
/// it. Looked up through its parents, with no pass over the document.
|
||||
fn series_group_or_mark(doc: &Document, id: NodeId) -> Option<SeriesRef> {
|
||||
let node = doc.node(id)?;
|
||||
let chain = doc.ancestry(id)?;
|
||||
let parent = doc.node(*chain.iter().rev().nth(1)?)?;
|
||||
let in_graph = |group: &Node, graph: &Node| {
|
||||
let index = group.extras().series_index.and_then(|i| usize::try_from(i).ok())?;
|
||||
graph.extras().graph.as_deref().filter(|spec| index < series_count(spec)).map(|_| SeriesRef { graph: graph.id, group: group.id, index })
|
||||
};
|
||||
if let Some(r) = in_graph(node, parent) {
|
||||
return Some(r);
|
||||
}
|
||||
// Only the paths the graph draws again, not the copy of a graph design.
|
||||
if !matches!(node.kind, NodeKind::Path { .. }) {
|
||||
return None;
|
||||
}
|
||||
in_graph(parent, doc.node(*chain.iter().rev().nth(2)?)?)
|
||||
}
|
||||
|
||||
/// The graph, series, whether it is the series group itself (`true`) or a path directly in it, and the object
|
||||
/// transparency of each of `edited` that is one of those, in order.
|
||||
/// transparency of each of `edited` that is one of those, in order. Each object is looked up through its parents
|
||||
/// ([`series_group_or_mark`]), so an edit of a few objects does not read the rest of the document.
|
||||
fn object_opacity_captures(doc: &Document, edited: &[NodeId]) -> Vec<(NodeId, usize, bool, ObjectOpacity)> {
|
||||
if edited.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
let members = series_members(doc);
|
||||
if members.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
edited
|
||||
.iter()
|
||||
.filter_map(|id| {
|
||||
let r = members.get(id)?;
|
||||
let r = series_group_or_mark(doc, *id)?;
|
||||
let group = r.group == *id;
|
||||
// Only the series group and the paths the graph draws again, not the copy of a graph design.
|
||||
let node = doc.node(*id).filter(|n| group || (doc.parent_of(*id) == Some(r.group) && matches!(n.kind, NodeKind::Path { .. })))?;
|
||||
let node = doc.node(*id)?;
|
||||
let mut look = ObjectOpacity {
|
||||
opacity: (node.opacity < 1.0).then_some(node.opacity),
|
||||
blend: (node.blend != BlendMode::Normal).then_some(node.blend),
|
||||
@@ -675,6 +688,25 @@ fn graph_labels(doc: &Document) -> HashMap<NodeId, (NodeId, Role)> {
|
||||
out
|
||||
}
|
||||
|
||||
/// The graph and kind of generated label `id`, as [`graph_labels`] finds it. Only the graphs among its parent and
|
||||
/// grandparent are read, with no pass over the document; `own` keeps each graph's labels read so far.
|
||||
fn graph_label_of(doc: &Document, id: NodeId, own: &mut HashMap<NodeId, HashMap<NodeId, Role>>) -> Option<(NodeId, Role)> {
|
||||
if !doc.node(id).is_some_and(|n| matches!(n.kind, NodeKind::Text(_))) {
|
||||
return None;
|
||||
}
|
||||
let chain = doc.ancestry(id)?;
|
||||
// The nearer graph first: [`graph_labels`] visits it later, so its entry is the one kept.
|
||||
for graph in chain.iter().rev().skip(1).take(2) {
|
||||
let Some(n) = doc.node(*graph) else { continue };
|
||||
let Some(spec) = n.extras().graph.as_deref() else { continue };
|
||||
let labels = own.entry(*graph).or_insert_with(|| own_labels(n, spec).into_iter().collect());
|
||||
if let Some(role) = labels.get(&id) {
|
||||
return Some((*graph, *role));
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// The generated labels of graph `n` (with spec `g`) and what each shows, as [`graph_labels`] finds them.
|
||||
fn own_labels(n: &Node, g: &GraphSpec) -> Vec<(NodeId, Role)> {
|
||||
let mut out = vec![];
|
||||
@@ -1725,9 +1757,9 @@ fn label_rows_of(doc: &Document, ids: &[NodeId]) -> Vec<(NodeId, Role, Option<ve
|
||||
if !ids.iter().any(|id| doc.node(*id).is_some_and(|n| matches!(n.kind, NodeKind::Text(_)))) {
|
||||
return vec![];
|
||||
}
|
||||
let labels = graph_labels(doc);
|
||||
let mut own = HashMap::new();
|
||||
let mut picked: Vec<(NodeId, Role, Option<vectorcraft_doc::LabelRows>)> = vec![];
|
||||
for (&(g, role), n) in ids.iter().rev().filter_map(|id| Some((labels.get(id)?, doc.node(*id)?))) {
|
||||
for ((g, role), n) in ids.iter().rev().filter_map(|id| Some((graph_label_of(doc, *id, &mut own)?, doc.node(*id)?))) {
|
||||
if !picked.iter().any(|(pg, pr, _)| *pg == g && *pr == role) {
|
||||
picked.push((g, role, label_rows(n)));
|
||||
}
|
||||
|
||||
@@ -1314,7 +1314,7 @@ fn refill_distorted(
|
||||
/// `path` with its anchors and handles mapped through `map` as a distort maps a path's points
|
||||
/// (`xform::Projective::apply`): a point on the map's horizon is mapped as if a billionth in front
|
||||
/// of it, and one past it to the far side. `None` when a point maps to no finite page point.
|
||||
fn warped(path: &PathData, map: &Homography) -> Option<PathData> {
|
||||
pub(super) fn warped(path: &PathData, map: &Homography) -> Option<PathData> {
|
||||
let [[a, b, c], [d, e, f], [g, h, i]] = map.0;
|
||||
let apply = |p: vectorcraft_geom::Point| {
|
||||
let w = g * p.x + h * p.y + i;
|
||||
|
||||
@@ -6,7 +6,8 @@
|
||||
//! and strokes, effects, opacity and blend mode, and the link to the style) or, with the Appearance
|
||||
//! panel's New Art Has Basic Appearance off, the whole appearance of the last selection. With the
|
||||
//! option on (the default) an inherited appearance gives new art its top stroke's options only,
|
||||
//! and a change of selection loads only the proxies. `paint.default` resets it.
|
||||
//! and a change of selection loads only the proxies. `paint.default` resets it, and
|
||||
//! `appearance.setNewArt` sets its fill, stroke and stroke options whatever is selected.
|
||||
//!
|
||||
//! A document whose Default Graphic Style no longer has the shipped look (a New Document profile
|
||||
//! redefined it) gives the reset that style's fills, strokes and effects instead, and `file.new`
|
||||
@@ -34,7 +35,7 @@ pub(crate) struct NewArtSource {
|
||||
|
||||
use super::gradient::unplaced;
|
||||
use super::paint::SelectionPaints;
|
||||
use super::{CommandSpec, Result, Session, always, cmd, switch_or};
|
||||
use super::{CommandSpec, Result, Session, always, bad, cmd, switch_or};
|
||||
use crate::doc_state::{SelectionRecord, objects_only};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
@@ -57,9 +58,181 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
always,
|
||||
describe
|
||||
),
|
||||
cmd!(
|
||||
"appearance.setNewArt",
|
||||
"Set New Art Appearance",
|
||||
[],
|
||||
None,
|
||||
"{fill?: {color?, none?, swatch?, tint?, gradient?, keepModel?} (a paint as paint.setFill takes it), stroke?: (a paint, as fill), weight?: 0..1000 pt, cap?: butt|round|square, join?: miter|round|bevel, miterLimit?: 1..500, dash?: [lengths, each 0..1000000 pt, at most 64, not all 0]|null (null: a solid line), dashOffset?: -1000000..1000000 pt (with a dash pattern), fillOverprint?: bool, strokeOverprint?: bool} set the fill, stroke and stroke options the next object drawn gets, whatever is selected: the selection and its art, the active proxy and the recent colors stay as they are. Without `weight` the stored stroke weight stays; a stroke painted on new art without one gets 1 pt only when that stored weight is 0. A bad value is an error with nothing changed, and so is any change while New Art Has Basic Appearance is off and an object is selected (new art takes that object's appearance then) → {changed: whether the next object drawn looks different}",
|
||||
always,
|
||||
set_new_art
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
/// The most dash and gap lengths `appearance.setNewArt` takes.
|
||||
const MAX_DASHES: usize = 64;
|
||||
/// The settings a `fill` or `stroke` paint of `appearance.setNewArt` takes.
|
||||
const PAINT_KEYS: [&str; 6] = ["color", "none", "swatch", "tint", "gradient", "keepModel"];
|
||||
/// The largest dash, gap or dash offset `appearance.setNewArt` takes, in points.
|
||||
const MAX_DASH_LENGTH: f64 = 1_000_000.0;
|
||||
|
||||
/// What [`dash_fault`] finds wrong with a list of dash and gap lengths.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub(crate) enum DashFault {
|
||||
/// More than [`MAX_DASHES`] lengths.
|
||||
TooMany,
|
||||
/// A length that is not a number from 0 to [`MAX_DASH_LENGTH`].
|
||||
OutOfRange,
|
||||
/// Lengths that are all 0.
|
||||
AllZero,
|
||||
}
|
||||
|
||||
/// What is wrong with the dash and gap lengths `lengths`, which `appearance.setNewArt` and the
|
||||
/// scripts' `strokeDashes` and `defaultStrokeDashes` check the same way; `None` when they are good.
|
||||
/// An empty list (a solid line) is good.
|
||||
pub(crate) fn dash_fault(lengths: &[f64]) -> Option<DashFault> {
|
||||
if lengths.len() > MAX_DASHES {
|
||||
Some(DashFault::TooMany)
|
||||
} else if !lengths.iter().all(|n| n.is_finite() && (0.0..=MAX_DASH_LENGTH).contains(n)) {
|
||||
Some(DashFault::OutOfRange)
|
||||
} else if !lengths.is_empty() && lengths.iter().all(|n| *n == 0.0) {
|
||||
Some(DashFault::AllZero)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// `c` as `appearance.setNewArt` stores it without `keepModel`: an RGB color in the color mode of
|
||||
/// the document in front.
|
||||
pub(crate) fn stored_color(s: &Session, c: vectorcraft_color::Color) -> vectorcraft_color::Color {
|
||||
super::paint::new_color(s, &json!({}), c)
|
||||
}
|
||||
|
||||
/// `appearance.setNewArt`: new art's fill, stroke and stroke options, every value checked before
|
||||
/// anything changes.
|
||||
fn set_new_art(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "appearance.setNewArt";
|
||||
let paint = |key: &str, fill: bool| -> Result<Option<Paint>> {
|
||||
let Some(v) = p.get(key) else { return Ok(None) };
|
||||
if !v.is_object() {
|
||||
return Err(bad(C, format!("{key} must be a paint object (color, none, swatch or gradient), got {v}")));
|
||||
}
|
||||
if let Some(k) = v.as_object().and_then(|o| o.keys().find(|k| !PAINT_KEYS.contains(&k.as_str()))) {
|
||||
return Err(bad(C, format!("{key}: unknown setting `{k}` (a paint takes {})", PAINT_KEYS.join(", "))));
|
||||
}
|
||||
if v.get("swatch").is_some_and(|w| !w.is_string()) {
|
||||
return Err(bad(C, format!("{key}: `swatch` must be a swatch name")));
|
||||
}
|
||||
let pattern_only = |name: &str| s.doc().is_ok_and(|st| st.doc.swatch(name).is_none() && st.doc.pattern(name).is_some());
|
||||
if v.get("tint").is_some() && v.get("swatch").and_then(Value::as_str).is_none_or(pattern_only) {
|
||||
return Err(bad(C, format!("{key}: `tint` goes with a global or spot `swatch`")));
|
||||
}
|
||||
let given = super::paint::paint_from(s, v)?.ok_or_else(|| bad(C, format!("{key}: give color, none, swatch or gradient")))?;
|
||||
if !fill && matches!(&given, Paint::Gradient(g) if g.gradient.dither) && v.get("swatch").and_then(Value::as_str).is_none() {
|
||||
return Err(bad(C, "`dither` applies to gradient fills"));
|
||||
}
|
||||
Ok(Some(unplaced(&given)))
|
||||
};
|
||||
let (fill, stroke) = (paint("fill", true)?, paint("stroke", false)?);
|
||||
let number = |key: &str, min: f64, max: f64| -> Result<()> {
|
||||
match p.get(key) {
|
||||
None => Ok(()),
|
||||
Some(v) if v.as_f64().is_some_and(|n| n.is_finite() && (min..=max).contains(&n)) => Ok(()),
|
||||
Some(v) => Err(bad(C, format!("{key} must be a number from {min} to {max}, got {v}"))),
|
||||
}
|
||||
};
|
||||
number("weight", 0.0, 1000.0)?;
|
||||
number("miterLimit", 1.0, 500.0)?;
|
||||
number("dashOffset", -MAX_DASH_LENGTH, MAX_DASH_LENGTH)?;
|
||||
for key in ["cap", "join"] {
|
||||
if p.get(key).is_some_and(|v| !v.is_string()) {
|
||||
return Err(bad(C, format!("{key} must be a name")));
|
||||
}
|
||||
}
|
||||
match p.get("dash") {
|
||||
None | Some(Value::Null) => {}
|
||||
Some(Value::Array(a)) if a.len() > MAX_DASHES => return Err(bad(C, format!("dash takes at most {MAX_DASHES} lengths"))),
|
||||
Some(Value::Array(a)) => {
|
||||
let lengths: Option<Vec<f64>> = a.iter().map(Value::as_f64).collect();
|
||||
match lengths.map_or(Some(DashFault::OutOfRange), |l| dash_fault(&l)) {
|
||||
None => {}
|
||||
Some(DashFault::TooMany) => return Err(bad(C, format!("dash takes at most {MAX_DASHES} lengths"))),
|
||||
Some(DashFault::OutOfRange) => return Err(bad(C, format!("each dash length must be a number from 0 to {MAX_DASH_LENGTH}"))),
|
||||
Some(DashFault::AllZero) => return Err(bad(C, "dash needs a length that is not 0")),
|
||||
}
|
||||
}
|
||||
Some(v) => return Err(bad(C, format!("dash must be a list of lengths or null, got {v}"))),
|
||||
}
|
||||
let flag = |key: &str| -> Result<Option<bool>> {
|
||||
p.get(key).map(|v| v.as_bool().ok_or_else(|| bad(C, format!("{key} must be true or false, got {v}")))).transpose()
|
||||
};
|
||||
let (fill_overprint, stroke_overprint) = (flag("fillOverprint")?, flag("strokeOverprint")?);
|
||||
let options: serde_json::Map<String, Value> =
|
||||
["weight", "cap", "join", "miterLimit", "dash", "dashOffset"].iter().filter_map(|k| Some((k.to_string(), p.get(*k)?.clone()))).collect();
|
||||
let change = super::stroke::StrokeChange::parse(&Value::Object(options), C)?;
|
||||
let dashed = match p.get("dash") {
|
||||
Some(Value::Array(a)) => !a.is_empty(),
|
||||
Some(_) => false,
|
||||
None => s.new_art().stroke().is_some_and(|st| st.dash.is_some()),
|
||||
};
|
||||
if p.get("dashOffset").and_then(Value::as_f64).is_some_and(|o| o != 0.0) && !dashed {
|
||||
return Err(bad(C, "dashOffset needs a dash pattern"));
|
||||
}
|
||||
let nothing = fill.is_none() && stroke.is_none() && change.is_empty() && fill_overprint.is_none() && stroke_overprint.is_none();
|
||||
if !nothing
|
||||
&& !s.prefs.new_art_basic
|
||||
&& !(s.tool_paints(false) && s.tool_paints(true))
|
||||
&& s.active().is_some_and(|st| !st.selection.subjects().is_empty())
|
||||
{
|
||||
return Err(bad(
|
||||
C,
|
||||
"with New Art Has Basic Appearance off, new art takes the selected object's appearance: deselect it or turn the option on",
|
||||
));
|
||||
}
|
||||
let look = |s: &Session| {
|
||||
let (opacity, blend, style) = s.new_art_transparency();
|
||||
(s.new_art(), opacity, blend, style.map(str::to_string))
|
||||
};
|
||||
let (before, was) = (s.paint.clone(), look(s));
|
||||
if let Some(f) = fill {
|
||||
s.paint.fill = f;
|
||||
}
|
||||
if let Some(st) = stroke {
|
||||
if !st.is_none() && s.paint.stroke.is_none() && s.paint.stroke_width == 0.0 {
|
||||
s.paint.stroke_width = 1.0;
|
||||
}
|
||||
s.paint.stroke = st;
|
||||
}
|
||||
if let Some(w) = change.weight {
|
||||
s.paint.stroke_width = w;
|
||||
}
|
||||
if !change.is_empty()
|
||||
&& let Some(st) = s.new_art_stroke_mut()
|
||||
{
|
||||
change.apply(st);
|
||||
}
|
||||
if let Some(on) = fill_overprint {
|
||||
let t = s.new_art_template_mut();
|
||||
if t.fill().is_none() {
|
||||
t.items.insert(0, AppearanceItem::Fill(FillLayer::new(Paint::None)));
|
||||
}
|
||||
if let Some(f) = t.fill_mut() {
|
||||
f.overprint = on;
|
||||
}
|
||||
}
|
||||
if let Some(on) = stroke_overprint
|
||||
&& let Some(st) = s.new_art_stroke_mut()
|
||||
{
|
||||
st.overprint = on;
|
||||
}
|
||||
let changed = look(s) != was;
|
||||
if !changed {
|
||||
s.paint = before;
|
||||
}
|
||||
Ok(json!({ "changed": changed }))
|
||||
}
|
||||
|
||||
/// `t` reduced to a basic appearance: an empty fill under its top stroke (options kept, without
|
||||
/// its own transparency or effects).
|
||||
fn basic_of(t: &Appearance) -> Appearance {
|
||||
|
||||
@@ -180,8 +180,9 @@ pub struct DocSettings {
|
||||
pub layout: ArtboardLayout,
|
||||
/// Columns of a grid layout.
|
||||
pub columns: u32,
|
||||
/// Rows of a grid by column, in place of `columns` when more than 0.
|
||||
#[serde(skip_serializing_if = "is_zero")]
|
||||
/// Rows of a grid by column, in place of `columns` when more than 0, up to `MAX_ARTBOARDS` (a
|
||||
/// saved or Recent preset's larger value is read as `MAX_ARTBOARDS`).
|
||||
#[serde(skip_serializing_if = "is_zero", deserialize_with = "de_rows")]
|
||||
pub rows: u32,
|
||||
/// Space between artboards, points: 0 to `MAX_SPACING` (a saved or Recent preset's value
|
||||
/// outside that range is read as the nearer end).
|
||||
@@ -380,12 +381,25 @@ impl DocSettings {
|
||||
return Ok(());
|
||||
}
|
||||
let o = l.as_object().ok_or_else(|| bad(cmd, "artboardLayout must be {layout?, columns?, spacing?, rightToLeft?}"))?;
|
||||
let count = |v: &Value| v.as_f64().filter(|c| c.is_finite() && *c >= 1.0).map(|c| c.round().min(MAX_ARTBOARDS as f64) as u32);
|
||||
for (k, v) in o {
|
||||
match k.as_str() {
|
||||
"layout" => self.layout = v.as_str().and_then(ArtboardLayout::parse).ok_or_else(bad_layout)?,
|
||||
"columns" => self.columns = count(v).ok_or_else(|| bad(cmd, "artboardLayout.columns must be 1 or more"))?,
|
||||
"rows" => self.rows = count(v).ok_or_else(|| bad(cmd, "artboardLayout.rows must be 1 or more"))?,
|
||||
"columns" => {
|
||||
self.columns = v
|
||||
.as_f64()
|
||||
.filter(|c| c.is_finite() && *c >= 1.0)
|
||||
.ok_or_else(|| bad(cmd, "artboardLayout.columns must be 1 or more"))?
|
||||
.round()
|
||||
.min(MAX_ARTBOARDS as f64) as u32
|
||||
}
|
||||
"rows" => {
|
||||
self.rows = v
|
||||
.as_f64()
|
||||
.map(f64::round)
|
||||
.filter(|r| (1.0..=MAX_ARTBOARDS as f64).contains(r))
|
||||
.map(|r| r as u32)
|
||||
.ok_or_else(|| bad(cmd, format!("artboardLayout.rows must be from 1 to {MAX_ARTBOARDS}")))?
|
||||
}
|
||||
"spacing" => {
|
||||
self.spacing = v
|
||||
.as_f64()
|
||||
@@ -590,6 +604,12 @@ fn de_artboards<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result<u
|
||||
Ok(f64::deserialize(d)?.round().clamp(1.0, MAX_ARTBOARDS as f64) as u32)
|
||||
}
|
||||
|
||||
/// A saved or Recent preset's grid rows, kept to at most [`MAX_ARTBOARDS`]; 0 (columns in their
|
||||
/// place) stays 0.
|
||||
fn de_rows<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result<u32, D::Error> {
|
||||
Ok(u32::deserialize(d)?.min(MAX_ARTBOARDS))
|
||||
}
|
||||
|
||||
/// A saved or Recent preset's artboard spacing, kept to 0 to [`MAX_SPACING`] points.
|
||||
fn de_spacing<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result<f64, D::Error> {
|
||||
Ok(f64::deserialize(d)?.clamp(0.0, MAX_SPACING))
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use vectorcraft_doc::{AppearanceItem, LiveShape, StrokeAlign};
|
||||
use vectorcraft_doc::{AppearanceItem, LiveShape, StrokeAlign, changed_nodes};
|
||||
|
||||
use super::{
|
||||
Affine, Arc, Document, EngineError, Node, NodeId, NodeKind, Paint, PathData, Rect, Result, Scaling, Session, Value, Vec2, bad, json,
|
||||
@@ -226,15 +226,7 @@ fn refresh_symbols(before: &Document, doc: &mut Document) {
|
||||
/// groups too: the instances of the symbols in `natural` (`ids`), and the objects whose opacity
|
||||
/// mask art holds such instances (`masked`).
|
||||
fn changed_instances(before: &[Arc<Node>], after: &[Arc<Node>], natural: &HashMap<String, Affine>, ids: &mut Vec<NodeId>, masked: &mut Vec<NodeId>) {
|
||||
let mut by_id: Option<HashMap<NodeId, &Arc<Node>>> = None;
|
||||
for (i, a) in after.iter().enumerate() {
|
||||
let b = match before.get(i) {
|
||||
Some(b) if b.id == a.id => Some(b),
|
||||
_ => by_id.get_or_insert_with(|| before.iter().map(|b| (b.id, b)).collect()).get(&a.id).copied(),
|
||||
};
|
||||
if b.is_some_and(|b| Arc::ptr_eq(b, a)) {
|
||||
continue;
|
||||
}
|
||||
for (_, a, b) in changed_nodes(before, after) {
|
||||
if a.extras().mask.as_ref().is_some_and(|m| holds_instance(&m.art, natural)) {
|
||||
masked.push(a.id);
|
||||
}
|
||||
@@ -423,15 +415,7 @@ pub(crate) fn keep_aligned_in(doc: &mut Document, ids: &[NodeId]) {
|
||||
/// pixel-aligned or hold pixel-aligned art in a linked opacity mask. Inside such an object the
|
||||
/// walk stops: [`keep_pixel_aligned`] visits what it holds.
|
||||
fn changed_aligned(before: &[Arc<Node>], after: &[Arc<Node>], out: &mut Vec<NodeId>) {
|
||||
let mut by_id: Option<std::collections::HashMap<NodeId, &Arc<Node>>> = None;
|
||||
for (i, a) in after.iter().enumerate() {
|
||||
let b = match before.get(i) {
|
||||
Some(b) if b.id == a.id => Some(b),
|
||||
_ => by_id.get_or_insert_with(|| before.iter().map(|b| (b.id, b)).collect()).get(&a.id).copied(),
|
||||
};
|
||||
if b.is_some_and(|b| Arc::ptr_eq(b, a)) {
|
||||
continue;
|
||||
}
|
||||
for (_, a, b) in changed_nodes(before, after) {
|
||||
if a.extras().pixel_aligned || a.extras().mask.as_ref().is_some_and(|m| m.linked && holds_aligned(&m.art)) {
|
||||
out.push(a.id);
|
||||
} else if let Some(children) = a.children() {
|
||||
|
||||
@@ -192,7 +192,11 @@ fn apply_transform_moving_guides(
|
||||
if copy { vec![] } else { ids }
|
||||
} else {
|
||||
let kept = if copy { preview_copies(s, &ids, with_guides, below)? } else { None };
|
||||
s.edit(label, |d, sel| {
|
||||
// A move of whole objects, not of copies (which `reindex` covers): the document before it,
|
||||
// and the moved objects as the transform left them, for [`moved_by`] to check after the edit.
|
||||
let from = (objects && !areas && !reindex && c[..4] == [1.0, 0.0, 0.0, 1.0]).then(|| s.doc().map(|st| st.doc.clone())).transpose()?;
|
||||
let mut held: Vec<(NodeId, Arc<Node>)> = vec![];
|
||||
let targets = s.edit(label, |d, sel| {
|
||||
let mut targets = match &kept {
|
||||
// The document becomes the snapshot with the kept copies, untransformed, and the
|
||||
// loop below transforms only the copies.
|
||||
@@ -229,6 +233,10 @@ fn apply_transform_moving_guides(
|
||||
transform_node(n, xf, sc, objects);
|
||||
}
|
||||
}
|
||||
// Holding them makes any later change to them copy them first, which `moved_by` sees.
|
||||
if from.is_some() {
|
||||
held = targets.iter().filter_map(|id| Some((*id, node_arc(d, paths.get(id)?)?))).collect();
|
||||
}
|
||||
if objects {
|
||||
for id in &targets {
|
||||
super::pixelgrid::keep_compound_aligned(d, *id, sc);
|
||||
@@ -248,7 +256,10 @@ fn apply_transform_moving_guides(
|
||||
targets.extend(d.transform_ruler_guides(sel, xf));
|
||||
}
|
||||
Ok(targets)
|
||||
})?
|
||||
})?;
|
||||
let st = s.doc_mut()?;
|
||||
st.moved = from.and_then(|from| moved_by(&from, st, &held, Vec2::new(c[4], c[5])));
|
||||
targets
|
||||
};
|
||||
let st = s.doc_mut()?;
|
||||
if st.interaction.is_none() {
|
||||
@@ -266,6 +277,47 @@ fn apply_transform_moving_guides(
|
||||
Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>() }))
|
||||
}
|
||||
|
||||
/// The node at index path `path` of `d`, shared.
|
||||
fn node_arc(d: &Document, path: &[usize]) -> Option<Arc<Node>> {
|
||||
let (first, rest) = path.split_first()?;
|
||||
let mut cur = d.layers.get(*first)?;
|
||||
for &i in rest {
|
||||
cur = cur.children()?.get(i)?;
|
||||
}
|
||||
Some(cur.clone())
|
||||
}
|
||||
|
||||
/// The [`crate::Moved`] of a move by `by` that took `from` to the document of `st`, given the moved
|
||||
/// objects as the transform left them (`held`). `None` unless every moved object is still that
|
||||
/// node, none is a member of a blend (whose spine follows its members), and every object the
|
||||
/// selection shows, the key object and the key anchor's object included, is a moved object or
|
||||
/// inside one. A pass after the transform that changes a moved object, such as the one that snaps
|
||||
/// moved pixel-aligned objects to the pixel grid again ([`super::pixelgrid::refresh`]), copies it
|
||||
/// first, so it is no longer that node.
|
||||
fn moved_by(from: &Arc<Document>, st: &crate::DocState, held: &[(NodeId, Arc<Node>)], by: Vec2) -> Option<crate::Moved> {
|
||||
let d = &st.doc;
|
||||
let unchanged = |(id, n): &(NodeId, Arc<Node>)| d.node(*id).is_some_and(|now| std::ptr::eq(now, Arc::as_ptr(n)));
|
||||
if held.is_empty() || !held.iter().all(unchanged) {
|
||||
return None;
|
||||
}
|
||||
let in_blend = |id: NodeId| d.parent_of(id).and_then(|p| d.node(p)).is_some_and(|p| matches!(p.kind, NodeKind::Blend { .. }));
|
||||
if held.iter().any(|(id, _)| in_blend(*id)) {
|
||||
return None;
|
||||
}
|
||||
let mut moved = std::collections::HashSet::new();
|
||||
for (_, n) in held {
|
||||
n.walk(&mut |c| {
|
||||
moved.insert(c.id);
|
||||
});
|
||||
}
|
||||
let sel = &st.selection;
|
||||
let mut shown = sel.objects.iter().copied().chain(sel.key).chain(sel.key_anchor.map(|(id, _)| id));
|
||||
if !shown.all(|id| moved.contains(&id)) {
|
||||
return None;
|
||||
}
|
||||
Some(crate::Moved { from: Arc::downgrade(from), to: Arc::downgrade(d), by, selection: sel.clone() })
|
||||
}
|
||||
|
||||
/// Returns the copies of `roots` for a transform or a perspective edit with `copy` in an interaction
|
||||
/// whose document is still its snapshot, as in a preview ([`Session::preview`] puts the snapshot
|
||||
/// back first). These are the copies the interaction keeps when they were made of that snapshot for
|
||||
|
||||
@@ -25,12 +25,12 @@
|
||||
//! the objects squared to the path; Pivot and Rotate; path edits realign the objects; Detach and
|
||||
//! the objects that move up the path after it; Expand).
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::collections::HashSet;
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::objects_on_path::{CENTER, Held, ObjectsOnPath, attachable_path, held, is_objects_on_path, place};
|
||||
use vectorcraft_doc::{Document, Node, NodeId, NodeKind};
|
||||
use vectorcraft_doc::{Document, Node, NodeId, NodeKind, changed_nodes};
|
||||
use vectorcraft_geom::Rect;
|
||||
|
||||
use super::edit::{roots_of, selected_roots};
|
||||
@@ -499,15 +499,7 @@ fn place_in(doc: &mut Document, id: NodeId) -> bool {
|
||||
/// The Objects on Path groups among `after` and inside them that are not the same nodes as before
|
||||
/// (`before`: the same list before the edit), outer ones first.
|
||||
fn changed_groups(before: &[Arc<Node>], after: &[Arc<Node>], out: &mut Vec<NodeId>) {
|
||||
let mut by_id: Option<HashMap<NodeId, &Arc<Node>>> = None;
|
||||
for (i, a) in after.iter().enumerate() {
|
||||
let b = match before.get(i) {
|
||||
Some(b) if b.id == a.id => Some(b),
|
||||
_ => by_id.get_or_insert_with(|| before.iter().map(|b| (b.id, b)).collect()).get(&a.id).copied(),
|
||||
};
|
||||
if b.is_some_and(|b| Arc::ptr_eq(b, a)) {
|
||||
continue;
|
||||
}
|
||||
for (_, a, b) in changed_nodes(before, after) {
|
||||
if is_objects_on_path(a) {
|
||||
out.push(a.id);
|
||||
}
|
||||
|
||||
@@ -105,7 +105,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Transparency Info",
|
||||
[],
|
||||
None,
|
||||
"{id?|ids?} → {ids, opacity: 0..100, blend, isolate, knockout: \"on\"|\"off\"|\"neutral\", knockoutShape, editingMask, pageIsolatedBlending, pageKnockoutGroup} the Transparency panel's values for `ids`, the selection, or the object whose mask is being edited. A value is null where those objects differ (or there are none); editingMask is the id of the object whose mask is being edited, or null; the page values are the document's",
|
||||
"{id?|ids?} → {ids, opacity: 0..100, blend, isolate, knockout: \"on\"|\"off\"|\"neutral\", knockoutShape, editingMask, pageIsolatedBlending, pageKnockoutGroup} the Transparency panel's values for `ids`, the selection, or the object whose mask is being edited. A value is null where those objects differ (or there are none). Without ids or id, with an object of a dynamic symbol instance selected by Direct Selection, opacity and blend are that object's for this instance, as transparency.set changes them; editingMask is the id of the object whose mask is being edited, or null; the page values are the document's",
|
||||
has_doc,
|
||||
info
|
||||
),
|
||||
@@ -489,10 +489,16 @@ impl Session {
|
||||
|
||||
fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let st = s.doc()?;
|
||||
let ids = transparency_targets(s, p)?;
|
||||
// The points `transparency.set` with the same `ids` (or none) fades.
|
||||
let points = if p.get("ids").is_none() && p.get("id").is_none() { s.mesh_points_picked() } else { super::paint::picked_mesh_points_of(s, &ids) };
|
||||
let i = TransparencyInfo::of(&st.doc, ids).with_mesh_points(&st.doc, points);
|
||||
// Without `ids` or `id`, the values `transparency.set` without them edits: those of the panel,
|
||||
// whose picked mesh points and selected dynamic symbol part take the opacity (and the part the
|
||||
// blend mode).
|
||||
let i = if p.get("ids").is_none() && p.get("id").is_none() {
|
||||
s.transparency_info()
|
||||
} else {
|
||||
let ids = transparency_targets(s, p)?;
|
||||
let points = super::paint::picked_mesh_points_of(s, &ids);
|
||||
TransparencyInfo::of(&st.doc, ids).with_mesh_points(&st.doc, points)
|
||||
};
|
||||
Ok(json!({
|
||||
"ids": i.ids.iter().map(|id| id.0).collect::<Vec<_>>(),
|
||||
"opacity": i.opacity,
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
//! Language packs as commands (#4936): list, install and remove the packs that spell-check and
|
||||
//! hyphenate languages other than English ([`crate::packs`]). They open nothing and never turn
|
||||
//! downloading on: an install needs the Craft apps' shared download setting, which only the person
|
||||
//! using an app turns on.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::{CommandSpec, EngineError, Result, Session, always, bad, cmd, text_param};
|
||||
use crate::packs::{self, Outcome};
|
||||
|
||||
/// The Language pack commands.
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!(
|
||||
query "proof.packs",
|
||||
"Language Packs",
|
||||
[],
|
||||
None,
|
||||
"{refresh?: bool (fetch the pinned pack index again; needs downloading on; refused under automation roots; in the desktop app it runs in the background: see refreshing)} the Language packs that spell-check and hyphenate languages other than English, shared by the Craft apps → {packs: [{locale, name, size: bytes, licence: SPDX, class, spelling: bool, hyphenation: bool, installed: bool}…] (the index fetched last; empty before the first fetch), installed: [{locale, name, licence}…] (the packs spelling and hyphenation use), installing: [{locale, done, total}…] (bytes), refreshing: bool, errors: {locale: message} (the last failure of each install or removal; \"\": of the index fetch), downloads: bool (the person allowed downloading), indexOverride: string|null (a test index used instead of the pinned one), available: bool (there is a font store folder to install into)}",
|
||||
always,
|
||||
list
|
||||
),
|
||||
cmd!(
|
||||
query "proof.installPack",
|
||||
"Install Language Pack",
|
||||
[],
|
||||
None,
|
||||
"{locale: language tag (a pack's locale from proof.packs, like nl or pt-br)} downloads the pack, checks its sha256 and installs it; spelling and hyphenation in that language use it at once, in every open document. Needs downloading on, which only the person using a Craft app can turn on. Refused under automation roots (the store is outside them). Opens nothing. In the desktop app it runs in the background → {locale, started: true}: follow it with proof.packs (installing, then installed or errors); elsewhere it returns once installed → {locale, installed: true}",
|
||||
always,
|
||||
install
|
||||
),
|
||||
cmd!(
|
||||
query "proof.removePack",
|
||||
"Remove Language Pack",
|
||||
[],
|
||||
None,
|
||||
"{locale} removes the installed pack (not while it installs; refused under automation roots); that language is no longer checked with it → {locale, installed: false}",
|
||||
always,
|
||||
remove
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
fn locale_param(p: &Value, command: &str) -> Result<String> {
|
||||
let raw = text_param(p, "locale", command)?.ok_or_else(|| bad(command, "`locale` (a language tag like nl) is required"))?;
|
||||
packs::parse_locale(raw).map_err(|e| bad(command, e))
|
||||
}
|
||||
|
||||
fn list(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "proof.packs";
|
||||
match p.get("refresh") {
|
||||
None | Some(Value::Null) | Some(Value::Bool(false)) => {}
|
||||
Some(Value::Bool(true)) => {
|
||||
not_confined(C)?;
|
||||
packs::refresh().map_err(EngineError::Other)?;
|
||||
}
|
||||
Some(_) => return Err(bad(C, "`refresh` must be true or false")),
|
||||
}
|
||||
// The jobs before the installed packs: an install makes craft-proof read its pack before it
|
||||
// leaves the jobs, so one that ends between the two reads is in one list or the other.
|
||||
let packs::Status { installing, refreshing, errors } = packs::status();
|
||||
let installed = craft_proof::packs::installed();
|
||||
let backend = packs::backend();
|
||||
let rows: Vec<Value> = packs::available()
|
||||
.iter()
|
||||
.map(|p| {
|
||||
json!({
|
||||
"locale": p.locale, "name": p.name, "size": p.size, "licence": p.licence, "class": p.class,
|
||||
"spelling": p.spelling, "hyphenation": p.hyphenation,
|
||||
"installed": installed.iter().any(|i| i.locale == p.locale),
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
// An install that ended since the last frame shows in every document's layout.
|
||||
s.poll_language_packs();
|
||||
Ok(json!({
|
||||
"packs": rows,
|
||||
"installed": installed.iter().map(|i| json!({"locale": i.locale, "name": i.name, "licence": i.licence})).collect::<Vec<_>>(),
|
||||
"installing": installing.iter().map(|(l, done, total)| json!({"locale": l, "done": done, "total": total})).collect::<Vec<_>>(),
|
||||
"refreshing": refreshing,
|
||||
"errors": errors,
|
||||
"downloads": backend.as_ref().is_some_and(|b| b.downloads_on()),
|
||||
"indexOverride": backend.as_ref().and_then(|b| b.index_override()),
|
||||
"available": backend.is_some(),
|
||||
}))
|
||||
}
|
||||
|
||||
/// Refuses `command` for a caller confined to automation roots: the packs are written into the font
|
||||
/// store the Craft apps share, which is outside them.
|
||||
fn not_confined(command: &str) -> Result<()> {
|
||||
if crate::file_access::current().is_some() {
|
||||
return Err(EngineError::Other(format!(
|
||||
"automation path rejected: {command} writes the Language packs into the font store the Craft apps share, outside the automation roots"
|
||||
)));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn install(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let locale = locale_param(p, "proof.installPack")?;
|
||||
not_confined("proof.installPack")?;
|
||||
match packs::install(&locale).map_err(EngineError::Other)? {
|
||||
Outcome::Started => Ok(json!({"locale": locale, "started": true})),
|
||||
Outcome::Done => {
|
||||
s.poll_language_packs();
|
||||
Ok(json!({"locale": locale, "installed": true}))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn remove(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let locale = locale_param(p, "proof.removePack")?;
|
||||
not_confined("proof.removePack")?;
|
||||
packs::remove(&locale).map_err(EngineError::Other)?;
|
||||
s.poll_language_packs();
|
||||
Ok(json!({"locale": locale, "installed": false}))
|
||||
}
|
||||
@@ -398,21 +398,26 @@ pub(crate) fn painted<'a>(n: &'a Node, top: bool, stroke: bool, out: &mut Vec<&'
|
||||
thread_local! {
|
||||
/// Tests: how many fills [`SelectionPaints`] read or took out on this thread.
|
||||
pub(crate) static PAINTS_READ: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
/// Tests: how many stroke weights [`SelectionPaints`] read or took out on this thread.
|
||||
pub(crate) static WEIGHTS_READ: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// The objects that reading objects `ids` meets, one item each ([`SelectionPaints::reads_no_more_than`]):
|
||||
/// each id, and the contents of a group, a layer, a Live Paint group or a container inside a group,
|
||||
/// as [`painted`] expands them. An id with no object and a ruler guide count once each.
|
||||
/// as [`painted`] expands them. An id with no object and a ruler guide count once each. A type
|
||||
/// object counts once for each of its runs, since the stroke weights are read run by run.
|
||||
struct Reads<'a> {
|
||||
doc: &'a Document,
|
||||
ids: std::slice::Iter<'a, NodeId>,
|
||||
/// The contents not counted yet of the objects met, innermost last.
|
||||
left: Vec<std::slice::Iter<'a, std::sync::Arc<Node>>>,
|
||||
/// The runs not counted yet of the type object met last.
|
||||
runs: usize,
|
||||
}
|
||||
|
||||
impl<'a> Reads<'a> {
|
||||
fn new(doc: &'a Document, ids: &'a [NodeId]) -> Self {
|
||||
Self { doc, ids: ids.iter(), left: vec![] }
|
||||
Self { doc, ids: ids.iter(), left: vec![], runs: 0 }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -420,6 +425,10 @@ impl Iterator for Reads<'_> {
|
||||
type Item = ();
|
||||
|
||||
fn next(&mut self) -> Option<()> {
|
||||
if self.runs > 0 {
|
||||
self.runs -= 1;
|
||||
return Some(());
|
||||
}
|
||||
loop {
|
||||
let (n, top) = match self.left.last_mut() {
|
||||
Some(contents) => match contents.next() {
|
||||
@@ -447,6 +456,9 @@ impl Iterator for Reads<'_> {
|
||||
if let Some(contents) = n.children().filter(|_| expand) {
|
||||
self.left.push(contents.iter());
|
||||
}
|
||||
if let NodeKind::Text(t) = &n.kind {
|
||||
self.runs = t.runs.len().saturating_sub(1);
|
||||
}
|
||||
return Some(());
|
||||
}
|
||||
}
|
||||
@@ -618,6 +630,8 @@ impl SelectionPaints {
|
||||
NodeKind::Text(t) => t.runs.iter().map(|r| r.style.stroke_layer().width).collect(),
|
||||
_ => n.appearance.stroke().map(|s| s.width).into_iter().collect(),
|
||||
};
|
||||
#[cfg(test)]
|
||||
WEIGHTS_READ.with(|c| c.set(c.get() + widths.len()));
|
||||
for w in widths {
|
||||
if add {
|
||||
self.weight.add(w, |a, b| a == b);
|
||||
@@ -899,9 +913,9 @@ fn set_paint(s: &mut Session, p: &Value, fill: bool) -> Result<Value> {
|
||||
apply_paint_opacity(s, p, paint, opacity, fill)
|
||||
}
|
||||
|
||||
/// The `opacity` param of `paint.setFill` and `paint.setStroke` (a percentage) as 0..1; `None`
|
||||
/// when it is left out or null.
|
||||
fn opacity_param(p: &Value, cmd: &str) -> Result<Option<f32>> {
|
||||
/// The `opacity` param of `paint.setFill`, `paint.setStroke` and `color.format` (a percentage) as
|
||||
/// 0..1; `None` when it is left out or null.
|
||||
pub(crate) fn opacity_param(p: &Value, cmd: &str) -> Result<Option<f32>> {
|
||||
match p.get("opacity") {
|
||||
None | Some(Value::Null) => Ok(None),
|
||||
Some(v) => match v.as_f64() {
|
||||
@@ -1986,6 +2000,8 @@ fn proxy_recolor(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn(
|
||||
Some(ids) => ids,
|
||||
None => super::edit::selected_roots(s)?,
|
||||
};
|
||||
// Read before the default is recolored, so that a bad `target` or `aligned` is refused with nothing selected too.
|
||||
let item = item_target(s, p, cmd)?;
|
||||
if ids.is_empty() {
|
||||
let def = if stroke { &mut s.paint.stroke } else { &mut s.paint.fill };
|
||||
let changed = super::colorcmds::map_paint(def, f);
|
||||
@@ -1993,7 +2009,7 @@ fn proxy_recolor(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn(
|
||||
s.remember_paint(&shown);
|
||||
return Ok(json!({ "changed": changed as usize }));
|
||||
}
|
||||
let item = item_target(s, p, cmd)?.of_kind(s, !stroke);
|
||||
let item = item.of_kind(s, !stroke);
|
||||
// Read before the check below, so that a bad param (such as `target` or `aligned`, or an explicit `item` the art has
|
||||
// no row for) is still an error.
|
||||
let targets = super::appearance::drop_design_art_rows(s, item.targets_for(s, p, !stroke)?, item, !stroke, cmd)?;
|
||||
|
||||
@@ -59,7 +59,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Move Direction Handles",
|
||||
[],
|
||||
None,
|
||||
"{handles: [{id, subpath?, anchor, which: \"in\"|\"out\"}, ...], dx, dy, independent?: bool} move several direction handles by (dx, dy) as one undo step; an anchor with one handle listed moves it as path.setHandle does (a smooth anchor turns its other handle in line at its own length), and an anchor with both handles listed moves both and becomes a corner; independent (default false) makes every listed handle's anchor a corner and leaves its other handle; a handle listed twice moves once; an empty list, a missing or unknown path, subpath or anchor, or a which other than \"in\" or \"out\" is refused",
|
||||
"{handles: [{id, subpath?, anchor, which: \"in\"|\"out\"}, ...], dx, dy, independent?: bool} move several direction handles by (dx, dy) as one undo step; an anchor with one handle listed moves it as path.setHandle does (a smooth anchor turns its other handle in line at its own length), and an anchor with both handles listed moves both and becomes a corner; independent (default false) makes every listed handle's anchor a corner and leaves its other handle; a handle listed twice moves once; a move by 0, 0 changes only the anchors it makes corners, so a live shape with no such anchor stays live and one with such an anchor becomes a plain path, and with none it changes nothing and records no undo step; an empty list, a missing or unknown path, subpath or anchor, or a which other than \"in\" or \"out\" is refused",
|
||||
has_doc,
|
||||
move_handles
|
||||
),
|
||||
@@ -77,7 +77,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Set Anchors",
|
||||
[],
|
||||
None,
|
||||
"{id, subpaths: [{anchors: [{x,y,in?,out?}], closed}]} replace a path's geometry",
|
||||
"{id, subpaths: [{anchors: [{x,y,in?,out?,smooth?: bool (left out: smooth when both handles are pulled out and in line)}], closed}]} replace a path's geometry",
|
||||
has_doc,
|
||||
set_anchors
|
||||
),
|
||||
@@ -643,8 +643,9 @@ fn move_handles(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
// A move by nothing changes only the kind of anchors that become corners: those with both
|
||||
// handles listed, or every listed one with `independent`.
|
||||
// The other anchors are left out, so a live shape that only they lie on is not expanded.
|
||||
if d == Vec2::ZERO {
|
||||
let corners = anchors.iter().any(|(&(id, si, ai), &(inn, out))| {
|
||||
anchors.retain(|&(id, si, ai), &mut (inn, out)| {
|
||||
(independent || (inn && out))
|
||||
&& doc
|
||||
.node(id)
|
||||
@@ -652,7 +653,7 @@ fn move_handles(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
.and_then(|pd| pd.subpaths.get(si)?.anchors.get(ai))
|
||||
.is_some_and(|a| a.kind != AnchorKind::Corner)
|
||||
});
|
||||
if !corners {
|
||||
if anchors.is_empty() {
|
||||
return ok();
|
||||
}
|
||||
}
|
||||
@@ -1593,6 +1594,91 @@ fn join_pair(d: &mut Document, (a, sa): (NodeId, usize), (b, sb): (NodeId, usize
|
||||
Ok(compound_or_self(d, a))
|
||||
}
|
||||
|
||||
/// An end of an open subpath of an editable path (not a guide) at `at`: the path, the subpath and
|
||||
/// whether the end is the subpath's first anchor. In isolation mode (`scope`), only a path inside
|
||||
/// the isolated node counts. Among several, one in or inside the selection `selected` comes first,
|
||||
/// then the last in paint order.
|
||||
pub(super) fn open_end_at(d: &Document, scope: Option<NodeId>, selected: &[NodeId], at: Point) -> Option<(NodeId, usize, bool)> {
|
||||
let editable = d.editable();
|
||||
let mut found: Option<((NodeId, usize, bool), bool)> = None;
|
||||
d.walk(|n| {
|
||||
let NodeKind::Path { path, guide: false, .. } = &n.kind else { return };
|
||||
if !editable(n.id) {
|
||||
return;
|
||||
}
|
||||
let chain = d.ancestry(n.id).unwrap_or_default();
|
||||
if scope.is_some_and(|s| !chain.contains(&s)) {
|
||||
return;
|
||||
}
|
||||
let chosen = chain.iter().any(|id| selected.contains(id));
|
||||
for (si, sp) in path.subpaths.iter().enumerate().filter(|(_, sp)| !sp.closed) {
|
||||
let Some((first, last)) = end_points(sp) else { continue };
|
||||
let end = if last.distance(at) < 1e-6 {
|
||||
false
|
||||
} else if first.distance(at) < 1e-6 {
|
||||
true
|
||||
} else {
|
||||
continue;
|
||||
};
|
||||
if found.is_none_or(|(_, was)| chosen || !was) {
|
||||
found = Some(((n.id, si, end), chosen));
|
||||
}
|
||||
}
|
||||
});
|
||||
found.map(|(end, _)| end)
|
||||
}
|
||||
|
||||
/// `sp`, an open subpath whose end (its first anchor when `at_first`) lies on an end of `arc`
|
||||
/// (its first anchor when `arc_at_start`), with `arc` added there: one subpath running the way
|
||||
/// `sp` runs. The anchor where they meet is `sp`'s, with its handle on the arc's side taken from
|
||||
/// the arc.
|
||||
fn splice(sp: &SubPath, at_first: bool, arc: &SubPath, arc_at_start: bool) -> SubPath {
|
||||
let mut arc = arc.clone();
|
||||
if arc_at_start == at_first {
|
||||
arc.reverse();
|
||||
}
|
||||
let mut out = sp.clone();
|
||||
if at_first {
|
||||
let meet = arc.anchors.pop();
|
||||
if let (Some(meet), Some(first)) = (meet, out.anchors.first_mut()) {
|
||||
first.h_in = meet.h_in;
|
||||
}
|
||||
arc.anchors.extend(out.anchors);
|
||||
out.anchors = arc.anchors;
|
||||
} else {
|
||||
if !arc.anchors.is_empty() {
|
||||
let meet = arc.anchors.remove(0);
|
||||
if let Some(last) = out.anchors.last_mut() {
|
||||
last.h_out = meet.h_out;
|
||||
}
|
||||
}
|
||||
out.anchors.extend(arc.anchors);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The arc `arc` joined to the open path ends `start` (at its first anchor) and `end` (at its
|
||||
/// last), as [`open_end_at`] gives them, at least one of them. The arc joins the path at `start`
|
||||
/// first, keeping that path's direction and look, and then, when `end` is an end of another open
|
||||
/// subpath, that subpath joins it as Join joins two paths; when `end` is the other end of the same
|
||||
/// subpath, the subpath closes. Returns what to select: the joined path, or its compound path.
|
||||
pub(super) fn join_arc(d: &mut Document, arc: &SubPath, start: Option<(NodeId, usize, bool)>, end: Option<(NodeId, usize, bool)>) -> Result<NodeId> {
|
||||
let err = || EngineError::Other("join needs open paths".into());
|
||||
let ((id, si, at_first), arc_at_start, rest) = match (start, end) {
|
||||
(Some(s), e) => (s, true, e),
|
||||
(None, Some(e)) => (e, false, None),
|
||||
(None, None) => return Err(err()),
|
||||
};
|
||||
let path = path_mut(d, id)?;
|
||||
let sp = path.subpaths.get_mut(si).filter(|sp| !sp.closed && !sp.anchors.is_empty()).ok_or_else(err)?;
|
||||
*sp = splice(sp, at_first, arc, arc_at_start);
|
||||
match rest {
|
||||
// The arc's far end is the first anchor of the joined subpath when it was added before it.
|
||||
Some((other, osi, other_first)) => join_pair(d, (id, si), (other, osi), (at_first, !other_first), None),
|
||||
None => Ok(compound_or_self(d, id)),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) type AnchorTargets = Vec<(NodeId, Vec<(usize, usize)>)>;
|
||||
|
||||
pub(super) fn anchor_targets(s: &Session) -> Result<AnchorTargets> {
|
||||
|
||||
@@ -8,7 +8,7 @@ use std::sync::Arc;
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::BlendMode;
|
||||
use vectorcraft_doc::appearance::{AppearanceItem, StrokeLayer};
|
||||
use vectorcraft_doc::{AnchorRef, Appearance, Document, Node, NodeId, NodeKind, SegmentRef, TextObject};
|
||||
use vectorcraft_doc::{AnchorRef, Appearance, Document, LockedArtboards, Node, NodeId, NodeKind, SegmentRef, TextObject};
|
||||
use vectorcraft_geom::{FillRule, PathData, SubPath};
|
||||
use vectorcraft_pathops as po;
|
||||
use vectorcraft_pathops::{BoolOp, PathfinderOp};
|
||||
@@ -190,7 +190,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Clean Up…",
|
||||
["Object", "Path"],
|
||||
None,
|
||||
"{strayPoints?: true, unpaintedObjects?: true, emptyTextPaths?: true} remove them, except the clipping paths of groups and layers and what a group or compound path used as one holds → {removed}",
|
||||
"{strayPoints?: true, unpaintedObjects?: true, emptyTextPaths?: true, hairlineSlivers?: false (closed paths and compound paths outside template layers with a visible fill, no visible stroke and no effect, whose fill no circle `sliverWidth` across fits inside; a compound path counts as one object, and guides, the clipping paths of groups and layers, objects at 0% opacity and their members, and the members of live and generated art stay), sliverWidth?: pt 0.001..3 (0.03 mm, VectorCraft's own default)} remove them from the visible, unlocked objects (not those on a locked artboard), as one undo step, except the clipping paths of groups and layers and what a group or compound path used as one holds → {removed, warning?: how many shapes hairlineSlivers could not measure (too complex, or past the run's limit of work) and left as they are}",
|
||||
has_doc,
|
||||
clean_up
|
||||
),
|
||||
@@ -1715,12 +1715,152 @@ fn is_painted(a: &Appearance) -> bool {
|
||||
})
|
||||
}
|
||||
|
||||
/// Hairline Slivers' width by default, in points: 0.03 mm, VectorCraft's own value.
|
||||
pub const HAIRLINE_SLIVER_WIDTH: f64 = 0.03 * 72.0 / 25.4;
|
||||
/// The widths Hairline Slivers takes, in points.
|
||||
pub const HAIRLINE_SLIVER_WIDTH_RANGE: std::ops::RangeInclusive<f64> = 0.001..=3.0;
|
||||
|
||||
/// The Hairline Slivers width `p` gives as `key` (by default [`HAIRLINE_SLIVER_WIDTH`]; a string
|
||||
/// with a unit reads too): an error when it is not a distance in [`HAIRLINE_SLIVER_WIDTH_RANGE`].
|
||||
pub(crate) fn sliver_width(p: &Value, key: &str, cmd: &str) -> Result<f64> {
|
||||
let w = length_given(p, key, cmd)?.unwrap_or(HAIRLINE_SLIVER_WIDTH);
|
||||
if !HAIRLINE_SLIVER_WIDTH_RANGE.contains(&w) {
|
||||
let (lo, hi) = (HAIRLINE_SLIVER_WIDTH_RANGE.start(), HAIRLINE_SLIVER_WIDTH_RANGE.end());
|
||||
return Err(bad(cmd, format!("`{key}` must be from {lo} to {hi} pt")));
|
||||
}
|
||||
Ok(w)
|
||||
}
|
||||
|
||||
/// Hairline Slivers: is `n` a path or compound path (not a guide or clipping path) whose subpaths
|
||||
/// are all closed, with a visible fill, no visible stroke and no effect (on the object or on a fill or stroke),
|
||||
/// whose fill no circle `width` across fits inside? A compound path is measured as one fill.
|
||||
/// `None` when the fill can't be measured with what is left of `budget` ([`po::thinner_than_within`]).
|
||||
/// A hidden member of a compound path is measured too, since the compound path paints it.
|
||||
fn is_hairline_sliver(n: &Node, width: f64, budget: &mut po::ThicknessBudget) -> Option<bool> {
|
||||
// A shape with no fill that paints is left to Unpainted Objects.
|
||||
if !n.appearance.has_drawn_fill() || draws_beyond_its_fill(&n.appearance) {
|
||||
return Some(false);
|
||||
}
|
||||
let (subpaths, rule): (Vec<&SubPath>, FillRule) = match &n.kind {
|
||||
NodeKind::Path { path, rule, guide: false, clipping: false, .. } => (path.subpaths.iter().collect(), *rule),
|
||||
NodeKind::Compound { children, rule } => {
|
||||
let mut all = vec![];
|
||||
for c in children {
|
||||
let NodeKind::Path { path, guide: false, .. } = &c.kind else { return Some(false) };
|
||||
all.extend(path.subpaths.iter());
|
||||
}
|
||||
(all, *rule)
|
||||
}
|
||||
_ => return Some(false),
|
||||
};
|
||||
// Paths of one anchor are stray points, and open paths are lines.
|
||||
if subpaths.is_empty() || subpaths.iter().any(|sp| !sp.closed || sp.anchors.len() < 2) {
|
||||
return Some(false);
|
||||
}
|
||||
po::thinner_than_within(&PathData::new(subpaths.into_iter().cloned().collect()), rule, width, budget)
|
||||
}
|
||||
|
||||
/// Does `a` paint anything beyond the fill of the geometry it is on: a stroke that draws, or an
|
||||
/// effect on the object or on one of its fills and strokes?
|
||||
fn draws_beyond_its_fill(a: &Appearance) -> bool {
|
||||
a.has_drawn_stroke() || !a.effects.is_empty() || a.items.iter().any(|i| !i.effects().is_empty())
|
||||
}
|
||||
|
||||
/// A group that stands for live or generated art (Live Paint, a graph, a dimension, a flare, a
|
||||
/// tracing result, objects on a path, a compound shape, type's glyph outlines, the pieces a clipping
|
||||
/// path paints and the like), as Artwork Cleanup's checks find most of them: Hairline Slivers
|
||||
/// leaves its members alone.
|
||||
fn holds_generated_art(n: &Node) -> bool {
|
||||
let e = n.extras();
|
||||
vectorcraft_tools::builder::is_live_paint(n)
|
||||
|| e.type_outlines
|
||||
|| e.clip_pieces
|
||||
|| e.graph.is_some()
|
||||
|| e.shaper.is_some()
|
||||
|| e.dimension.is_some()
|
||||
|| e.flare.is_some()
|
||||
|| e.trace.is_some()
|
||||
|| e.objects_on_path.is_some()
|
||||
|| e.live_paint_gaps.is_some()
|
||||
|| e.compound_shape
|
||||
}
|
||||
|
||||
/// The objects Hairline Slivers finds in `d` for `width`.
|
||||
pub(crate) struct Slivers {
|
||||
pub ids: Vec<NodeId>,
|
||||
/// Closed paths and compound paths whose fill couldn't be measured, which are left as they are.
|
||||
pub unmeasured: Vec<NodeId>,
|
||||
}
|
||||
|
||||
/// The status-bar warning for `count` shapes Hairline Slivers couldn't measure, when there are any.
|
||||
pub(crate) fn unmeasured_warning(count: usize) -> Option<String> {
|
||||
(count > 0).then(|| {
|
||||
format!(
|
||||
"Hairline Slivers: {count} shapes could not be measured (too complex, or past the limit of work for one run) and were left as they are"
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
/// The hairline slivers ([`is_hairline_sliver`]) among the visible, unlocked objects of `d` (not
|
||||
/// those on a locked artboard or in a template layer) for which `within` holds, in the layers and
|
||||
/// groups of the whole document. A compound path counts as one object. The clipping paths of groups
|
||||
/// and layers (and all of a clipping group used as one), the members of live and generated art,
|
||||
/// objects at 0 % opacity and everything in a group or layer at 0 %, and the members of groups and
|
||||
/// layers whose own stroke or effect paints them are left out.
|
||||
pub(crate) fn hairline_slivers(d: &Document, width: f64, within: &dyn Fn(NodeId) -> bool) -> Slivers {
|
||||
struct Walk<'a> {
|
||||
width: f64,
|
||||
locks: LockedArtboards<'a>,
|
||||
within: &'a dyn Fn(NodeId) -> bool,
|
||||
// One budget for the whole document, so that thousands of shapes that need a search take
|
||||
// a bounded time; the shapes after it runs out count as unmeasured.
|
||||
budget: po::ThicknessBudget,
|
||||
out: Vec<(NodeId, Option<bool>)>,
|
||||
}
|
||||
fn visit(n: &Node, clip_path: bool, w: &mut Walk<'_>) {
|
||||
// An object at 0 % opacity, or anything in a group or layer at 0 %, paints nothing.
|
||||
if !n.visible || n.locked || n.is_template() || clip_path || n.opacity <= 0.0 {
|
||||
return;
|
||||
}
|
||||
match &n.kind {
|
||||
NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => {
|
||||
if holds_generated_art(n) || draws_beyond_its_fill(&n.appearance) {
|
||||
return;
|
||||
}
|
||||
let clips = n.clips();
|
||||
for (i, c) in children.iter().enumerate() {
|
||||
visit(c, clips && i == 0, w);
|
||||
}
|
||||
}
|
||||
// Art on a locked artboard, or outside `within`, is left out before it is measured.
|
||||
NodeKind::Path { .. } | NodeKind::Compound { .. } if !w.locks.holds_id(n.id) && (w.within)(n.id) => {
|
||||
match is_hairline_sliver(n, w.width, &mut w.budget) {
|
||||
Some(false) => {}
|
||||
found => w.out.push((n.id, found)),
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let mut w = Walk { width, locks: d.locked_artboards(), within, budget: po::ThicknessBudget::document(), out: vec![] };
|
||||
for l in &d.layers {
|
||||
visit(l, false, &mut w);
|
||||
}
|
||||
let mut found = w.out;
|
||||
let editable = d.editable();
|
||||
found.retain(|(id, _)| editable(*id));
|
||||
let (sure, unsure): (Vec<_>, Vec<_>) = found.into_iter().partition(|(_, f)| f.is_some());
|
||||
Slivers { ids: sure.into_iter().map(|(id, _)| id).collect(), unmeasured: unsure.into_iter().map(|(id, _)| id).collect() }
|
||||
}
|
||||
|
||||
fn clean_up(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "object.path.cleanUp";
|
||||
let stray = switch_or(p, "strayPoints", true, C)?;
|
||||
let unpainted = switch_or(p, "unpaintedObjects", true, C)?;
|
||||
let empty_text = switch_or(p, "emptyTextPaths", true, C)?;
|
||||
let found = {
|
||||
let slivers = switch_or(p, "hairlineSlivers", false, C)?;
|
||||
let width = sliver_width(p, "sliverWidth", C)?;
|
||||
let (found, warning) = {
|
||||
let d = &s.doc()?.doc;
|
||||
let mut v = vec![];
|
||||
fn visit(n: &Node, parent_compound: bool, parent_clip: bool, first: bool, v: &mut Vec<NodeId>, opts: (bool, bool, bool)) {
|
||||
@@ -1763,10 +1903,22 @@ fn clean_up(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let editable = d.editable();
|
||||
v.retain(|id| editable(*id));
|
||||
v
|
||||
let mut warning = None;
|
||||
if slivers {
|
||||
let found = hairline_slivers(d, width, &|_| true);
|
||||
let listed: BTreeSet<NodeId> = v.iter().copied().collect();
|
||||
// A shape another option removes isn't left as it is.
|
||||
warning = unmeasured_warning(found.unmeasured.iter().filter(|id| !listed.contains(id)).count());
|
||||
v.extend(found.ids.into_iter().filter(|id| !listed.contains(id)));
|
||||
}
|
||||
(v, warning)
|
||||
};
|
||||
let reply = |removed: usize| match &warning {
|
||||
Some(w) => json!({ "removed": removed, "warning": w }),
|
||||
None => json!({ "removed": removed }),
|
||||
};
|
||||
if found.is_empty() {
|
||||
return Ok(json!({ "removed": 0 }));
|
||||
return Ok(reply(0));
|
||||
}
|
||||
s.edit("Clean Up", |d, _| {
|
||||
let mut gone = Beside::replacing(d, &found);
|
||||
@@ -1777,7 +1929,7 @@ fn clean_up(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
gone.finish(d)
|
||||
})?;
|
||||
Ok(json!({ "removed": found.len() }))
|
||||
Ok(reply(found.len()))
|
||||
}
|
||||
|
||||
// ---------- Divide Objects Below ----------
|
||||
|
||||
+134
-22
@@ -57,7 +57,7 @@ use std::sync::Arc;
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::Paint;
|
||||
use vectorcraft_doc::{Appearance, Document, ImageObject, LinkInfo, Node, NodeId, NodeKind, PageBox, Scaling, SliceOptions, SymbolBoxes};
|
||||
use vectorcraft_geom::{Affine, Point, Rect, shapes};
|
||||
use vectorcraft_geom::{Affine, Homography, Point, Rect, shapes};
|
||||
use vectorcraft_pdf::CropTo;
|
||||
|
||||
use super::fileio::{self, Format, RasterImage};
|
||||
@@ -88,7 +88,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Place…",
|
||||
["File"],
|
||||
Some("Cmd+Shift+P"),
|
||||
"{path | name | dataBase64 (a file's path, or its name with its bytes), link?: true (a raster image keeps its file's path; a VectorCraft document at path becomes one locked placed document showing artboard `page`, linked to the file and read again when it changes (links.update; saving it in this app updates it at once), drawn as vectors in every output; so does a PDF/.ai page at path, showing its `crop` box, unless password or textAs: \"outlines\" is given, and an EPS file, a PostScript file or a PostScript .ai at path, showing the art false gives; false: an editable copy of its art, as from dataBase64; other files are embedded), text?: {characterSet?: \"unicode\" (UTF-8, or UTF-16 with a byte-order mark, or without one by dataset.import's rule: an even length, at least half of its two-byte units holding a NUL byte, the byte order that reads a line break, valid UTF-16 with no NUL character; other bytes as the platform's 8-bit set) | \"ansi\" (the platform's 8-bit set) | \"shiftJis\" | \"gb2312\" (read as GBK) | \"chineseBig5\" | \"cyrillic\" (windows-1251, x-mac-cyrillic on mac) | \"gb18030\" | \"greek\" (windows-1253) | \"turkish\" (windows-1254) | \"baltic\" (windows-1257) | \"centralEuropean\" (windows-1250) (the WHATWG Encoding Standard's decoders: a byte-order mark is read as ordinary bytes, a malformed sequence as U+FFFD), platform?: \"windows\" (ANSI is Windows-1252) | \"mac\" (ANSI is Mac Roman), removeLineReturns?: false (each block of lines becomes one paragraph; blank lines end paragraphs), removeParagraphReturns?: false (drop blank lines), replaceSpaces?: n (runs of n ≥ 2 spaces become a tab)} (a .txt file, placed as area type filling rect, the replaced object's bounds, or else the artboard less a 36 pt margin), template?: false (onto a new locked template layer below the current layer), replace?: false (swap the one selected object, keeping its stacking place and transform; no at/rect; refused while an object of a symbol instance's art is selected), at?: [x, y] centre (default: the first artboard's centre), rect?: [x, y, width, height] fit inside; aspect kept (wins over at), page?: 1 (PDF/.ai page, or a native document's artboard), crop?: \"crop\" (clipped to that page or artboard, default; an SVG, only when given: framed and clipped by its viewBox, else by its art's bounds) | \"bounding\" (the bounds of the art that shows, with its strokes and effects, as an export measures them: hidden objects and guides left out) | \"art\" | \"trim\" | \"bleed\" | \"media\" (a PDF page's boxes), password? (an encrypted PDF), layers?: false (a PSD or PSB file: true embeds its layers as one group named after the file, read as document.open reads them: an image for each layer and a group for each layer group, with the layer's name, visibility, opacity, blend mode and opacity mask, at the place its merged image would take and clipped to the canvas when layers, hidden ones included, reach past it; never linked: link is then false unless given, and link: true is refused; a file without layers is embedded as its merged image, and so are one whose layers are all left out and one whose layers can't be read, with a warning), hiddenLayers?: false (with layers: true, the hidden layers come in hidden instead of being left out; refused without it), importSlices?: bool (a PSD or PSB file: its slices become user slices, moved and scaled with the placed art, in the same undo step; default true when the file is embedded, false when it is linked, and true with link is refused; slices the file generated automatically are left out), dxf?: {…the DXF options of document.open} (a .dxf drawing: fit fills the artboard under at, else the first; fitted or uncentred art lands with its drawing's artboard on that artboard, else it is centred on at), showImportOptions?: true (in the app, a text file without text, a DXF drawing without dxf, a PSD or PSB file embedded without layers (with two layers or more, or with slices) and a PDF with several pages or a password and no page ask for those options first, and an encrypted PDF given page and no password asks for its password; false places them with the options last confirmed, a PDF on page 1 (or page), and asks only an encrypted PDF's password), importer?: \"plugin.<id>\" (an importer plug-in whose manifest sets place, see document.formats: it reads the file, which must have an extension it lists, also one a built-in format reads; without importer, a file no built-in format reads, by its content or its extension, is read by the first such importer by id that lists its extension; it is given the file, at most 128 MiB, with _context.mode \"place\", and its objects, guides left out, are placed as one group named after the file, in the order it returned them, embedded whatever link says), params?: {…} (the importer's own parameters, see plugin.info)} → {ids, name, format, linked, width, height, warnings, image?: the id of the image of a DCS file or PSD/PSB file placed in a c
Line truncated
|
||||
"{path | name | dataBase64 (a file's path, or its name with its bytes), link?: true (a raster image keeps its file's path; a VectorCraft document at path becomes one locked placed document showing artboard `page`, linked to the file and read again when it changes (links.update; saving it in this app updates it at once), drawn as vectors in every output; so does a PDF/.ai page at path, showing its `crop` box, unless password or textAs: \"outlines\" is given, and an EPS file, a PostScript file or a PostScript .ai at path, showing the art false gives; false: an editable copy of its art, as from dataBase64; other files are embedded), text?: {characterSet?: \"unicode\" (UTF-8, or UTF-16 with a byte-order mark, or without one by dataset.import's rule: an even length, at least half of its two-byte units holding a NUL byte, the byte order that reads a line break, valid UTF-16 with no NUL character; other bytes as the platform's 8-bit set) | \"ansi\" (the platform's 8-bit set) | \"shiftJis\" | \"gb2312\" (read as GBK) | \"chineseBig5\" | \"cyrillic\" (windows-1251, x-mac-cyrillic on mac) | \"gb18030\" | \"greek\" (windows-1253) | \"turkish\" (windows-1254) | \"baltic\" (windows-1257) | \"centralEuropean\" (windows-1250) (the WHATWG Encoding Standard's decoders: a byte-order mark is read as ordinary bytes, a malformed sequence as U+FFFD), platform?: \"windows\" (ANSI is Windows-1252) | \"mac\" (ANSI is Mac Roman), removeLineReturns?: false (each block of lines becomes one paragraph; blank lines end paragraphs), removeParagraphReturns?: false (drop blank lines), replaceSpaces?: n (runs of n ≥ 2 spaces become a tab)} (a .txt file, placed as area type filling rect, the replaced object's bounds, or else the artboard less a 36 pt margin), template?: false (onto a new locked template layer below the current layer), replace?: false (swap the one selected object, keeping its stacking place and transform; an image changed by Perspective Distort or Free Distort keeps its corners, which a raster image or a DCS file's image fills, with its file's clipping path drawn through them, and other files but text are refused; no at/rect; refused while an object of a symbol instance's art is selected), at?: [x, y] center (default: the first artboard's center; all retained geometry, including art outside a crop frame, must stay within ±4,000,000 pt on either axis after transformation, including template placement), rect?: [x, y, width, height] fit inside; aspect kept (wins over at), page?: 1 (PDF/.ai page, or a native document's artboard), crop?: \"crop\" (clipped to that page or artboard, default; an SVG, only when given: framed and clipped by its viewBox, else by its art's bounds) | \"bounding\" (the bounds of the art that shows, with its strokes and effects, as an export measures them: hidden objects and guides left out) | \"art\" | \"trim\" | \"bleed\" | \"media\" (a PDF page's boxes), password? (an encrypted PDF), layers?: false (a PSD or PSB file: true embeds its layers as one group named after the file, read as document.open reads them: an image for each layer and a group for each layer group, with the layer's name, visibility, opacity, blend mode and opacity mask, at the place its merged image would take and clipped to the canvas when layers, hidden ones included, reach past it; never linked: link is then false unless given, and link: true is refused; a file without layers is embedded as its merged image, and so are one whose layers are all left out and one whose layers can't be read, with a warning), hiddenLayers?: false (with layers: true, the hidden layers come in hidden instead of being left out; refused without it), importSlices?: bool (a PSD or PSB file: its slices become user slices, moved and scaled with the placed art, in the same undo step; default true when the file is embedded, false when it is linked, and true with link is refused; slices the file generated automatically are left out), dxf?: {…the DXF options of document.open} (a .dxf drawing: fit fills the artboard under at, else the first; fitted or uncentred art lands with its drawing's artboard on that artboard, else it is centred on at), showImportOptions?: true (in the app, a text file without text, a DXF drawing without dxf, a PSD or PSB file embedded without layers (with two layers or more, or with slices) and a PDF with several pages or a password and no page ask for those options first, and an encrypted PDF given page and no password asks for its password; false places them with the options last confirmed, a PDF on page 1 (or page), and asks only an encrypted PDF's password), importer?: \"plugin.<id>\" (an importer plug-in whose manifest sets place, see document.formats: it reads the file, which must have an extension it lists, also one a built-in format reads; without importer, a file no built-in format reads, by its content or its extension, is read by the first such importer by id that lists its extension; it is given the file, at most 12
Line truncated
|
||||
has_doc,
|
||||
place
|
||||
),
|
||||
@@ -655,7 +655,7 @@ fn at_param(p: &Value) -> Result<Option<Point>> {
|
||||
|
||||
/// The transform that puts new art with the natural box `natural` where `old` is: an image's scale
|
||||
/// and rotation relative to its 100% size (its resolution's) and its centre are kept (with
|
||||
/// `image_xf`), also for an image alone in a clip group when the new art is an image, clipped by
|
||||
/// `image_xf`), also for an image alone in a clip group when the new art is a raster or DCS image, clipped by
|
||||
/// its file's clipping path or not (`new_image`); other objects keep their centre.
|
||||
fn replace_xf(d: &Document, old: &Node, natural: Rect, image_xf: bool, new_image: bool) -> Affine {
|
||||
let image = replace_measured(d, old, new_image);
|
||||
@@ -663,7 +663,7 @@ fn replace_xf(d: &Document, old: &Node, natural: Rect, image_xf: bool, new_image
|
||||
let (sx, sy) = pt_per_px(d.images.get(&im.key).and_then(|b| fileio::ppi::resolution(&b.bytes)));
|
||||
let full = Affine::scale_non_uniform(sx, sy);
|
||||
let centre = full * Point::new(im.width as f64 / 2.0, im.height as f64 / 2.0);
|
||||
if im.xf.determinant().abs() > 1e-12 {
|
||||
if Homography::affine_is_invertible(im.xf) {
|
||||
return im.xf * full.inverse() * Affine::translate(centre - natural.center());
|
||||
}
|
||||
}
|
||||
@@ -672,8 +672,8 @@ fn replace_xf(d: &Document, old: &Node, natural: Rect, image_xf: bool, new_image
|
||||
}
|
||||
|
||||
/// The object [`replace_xf`] measures when Replace swaps `old`: an image alone in a clip group (as
|
||||
/// a PSD or PSB file's clipping path places it, [`fileio::file_clipped`]) when the new art is an
|
||||
/// image (`new_image`), except a DCS file's plates; else `old` itself.
|
||||
/// a PSD or PSB file's clipping path places it, [`fileio::file_clipped`]) when the new art is a
|
||||
/// raster or DCS image (`new_image`), except a DCS file's plates; else `old` itself.
|
||||
fn replace_measured<'a>(d: &Document, old: &'a Node, new_image: bool) -> &'a Node {
|
||||
match &old.kind {
|
||||
NodeKind::Group { children, clip: true } if new_image => match &children[..] {
|
||||
@@ -687,6 +687,60 @@ fn replace_measured<'a>(d: &Document, old: &'a Node, new_image: bool) -> &'a Nod
|
||||
}
|
||||
}
|
||||
|
||||
/// What Replace does when the image it measures, `old`, is distorted and the art placed is a
|
||||
/// raster image or a DCS file's image (`art`): the transform that puts the new pixels on `old`'s
|
||||
/// transform scaled to their size, as Update Links scales it, the corners the new image takes, and
|
||||
/// the map from the art's natural box to the page through those corners, which a PSD file's slices
|
||||
/// follow. `None` for other art, for an image with no pixels, and for corners the new pixels can't
|
||||
/// fill ([`Node::set_image_corners`]).
|
||||
fn distorted_replace(old: &Node, art: &Art) -> Option<(Affine, [Point; 4], Homography)> {
|
||||
let NodeKind::Image(im) = &old.kind else { return None };
|
||||
let q = old.image_quad()?;
|
||||
let (pixels, width, height) = match art {
|
||||
Art::Image(img, _) => {
|
||||
let (sx, sy) = pt_per_px(img.ppi);
|
||||
(Affine::scale_non_uniform(sx, sy), img.width, img.height)
|
||||
}
|
||||
Art::Dcs(a) => (a.xf, a.img.width, a.img.height),
|
||||
_ => return None,
|
||||
};
|
||||
if width == 0 || height == 0 || !Homography::affine_is_invertible(pixels) {
|
||||
return None;
|
||||
}
|
||||
let xf = im.xf * Affine::scale_non_uniform(f64::from(im.width) / f64::from(width), f64::from(im.height) / f64::from(height));
|
||||
let new = ImageObject { key: String::new(), width, height, xf, link: None, placement: Default::default(), pixels: None };
|
||||
let mut probe = Node::new(old.id, NodeKind::Image(Box::new(new)));
|
||||
probe.set_image_corners(q).ok()?;
|
||||
let page = probe.image_map()?.checked_then_after(&Homography::from_affine(pixels.inverse()))?;
|
||||
Some((xf * pixels.inverse(), q, page))
|
||||
}
|
||||
|
||||
/// Placed raster `node` (an image, or an image in a clip group of its file's clipping path, as
|
||||
/// [`build`] makes them) with the image's corners at `q`: the pixels fill them, and the clipping
|
||||
/// path is drawn through them as the pixels are. `None` when the corners can't hold the image.
|
||||
fn with_corners(mut node: Node, q: [Point; 4]) -> Option<Node> {
|
||||
match &mut node.kind {
|
||||
NodeKind::Image(_) => node.set_image_corners(q).ok()?,
|
||||
NodeKind::Group { children, clip: true } => {
|
||||
let [path, image] = &mut children[..] else { return None };
|
||||
let image = Arc::make_mut(image);
|
||||
let NodeKind::Image(im) = &image.kind else { return None };
|
||||
if !Homography::affine_is_invertible(im.xf) {
|
||||
return None;
|
||||
}
|
||||
// The clipping path in the image's pixels, which its transform placed on the page.
|
||||
let to_pixels = im.xf.inverse();
|
||||
image.set_image_corners(q).ok()?;
|
||||
let map = image.image_map()?;
|
||||
let NodeKind::Path { path: p, .. } = &mut Arc::make_mut(path).kind else { return None };
|
||||
p.transform(to_pixels);
|
||||
*p = super::links::warped(p, &map)?;
|
||||
}
|
||||
_ => return None,
|
||||
}
|
||||
Some(node)
|
||||
}
|
||||
|
||||
/// `rect` fitted with `natural`'s aspect, centred.
|
||||
fn fit(natural: Rect, r: Rect) -> Affine {
|
||||
let ratio = |a: f64, b: f64| (b > 1e-9).then(|| a / b);
|
||||
@@ -846,19 +900,24 @@ fn apply(s: &mut Session, read: PlaceRead) -> Result<Value> {
|
||||
loaded.natural = Rect::from_origin_size(Point::ORIGIN, size);
|
||||
}
|
||||
let natural = loaded.natural;
|
||||
// Replace keeps the transform of the image it measures (`replace_measured`), which a
|
||||
// distortion's corners do not follow. Type, and any other object it measures, is placed by the
|
||||
// bounds of what it replaces, so a distorted image there is not refused.
|
||||
// Replace keeps the transform of the image it measures (`replace_measured`). When that image
|
||||
// is distorted, a raster placed in its place takes its corners ([`distorted_replace`]); other
|
||||
// art is refused. Type, and any other object it measures, is placed by the bounds of what it
|
||||
// replaces, so a distorted image there is not refused.
|
||||
let mut distorted = None;
|
||||
let new_image = matches!(loaded.art, Art::Image(..) | Art::Dcs(..));
|
||||
if let Some(o) = old_node
|
||||
&& !is_text
|
||||
{
|
||||
let image = replace_measured(&st.doc, o, matches!(loaded.art, Art::Image(..)));
|
||||
let image = replace_measured(&st.doc, o, new_image);
|
||||
if image.is_distorted_image() {
|
||||
return Err(super::xform::distorted_image_error(PLACE, image.id));
|
||||
let fit = distorted_replace(image, &loaded.art).ok_or_else(|| super::xform::distorted_image_error(PLACE, image.id))?;
|
||||
distorted = Some((image.id, fit));
|
||||
}
|
||||
}
|
||||
let m = match (old_node, rect) {
|
||||
(Some(o), _) => replace_xf(&st.doc, o, natural, !is_text, matches!(loaded.art, Art::Image(..))),
|
||||
(Some(_), _) if let Some((_, (m, ..))) = distorted => m,
|
||||
(Some(o), _) => replace_xf(&st.doc, o, natural, !is_text, new_image),
|
||||
(None, Some(r)) => fit(natural, r),
|
||||
// Its artboard's bottom-left corner on the target's.
|
||||
(None, None) if let (Some(src), Some(to)) = (loaded.board, target) => Affine::translate((to.x0 - src.x0, to.y1 - src.y1)),
|
||||
@@ -867,6 +926,38 @@ fn apply(s: &mut Session, read: PlaceRead) -> Result<Value> {
|
||||
Affine::translate(c - natural.center())
|
||||
}
|
||||
};
|
||||
let mut retained = natural;
|
||||
match &loaded.art {
|
||||
Art::Vector { src, nodes, .. } => {
|
||||
let symbols = src.symbol_boxes();
|
||||
for node in nodes {
|
||||
node.walk(&mut |node| {
|
||||
if let Some(bounds) = node.geometric_bounds_with(&symbols) {
|
||||
retained = retained.union(bounds);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
Art::Image(image, _) => {
|
||||
let (sx, sy) = pt_per_px(image.ppi);
|
||||
retained = retained.union(Rect::new(0.0, 0.0, f64::from(image.width) * sx, f64::from(image.height) * sy));
|
||||
}
|
||||
Art::Dcs(art) => {
|
||||
let pixels = Rect::new(0.0, 0.0, f64::from(art.img.width), f64::from(art.img.height));
|
||||
retained = retained.union(art.xf.transform_rect_bbox(pixels));
|
||||
if let Some(clip) = &art.clip {
|
||||
clip.walk(&mut |node| {
|
||||
if let Some(bounds) = node.geometric_bounds() {
|
||||
retained = retained.union(bounds);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
Art::Text(_) | Art::Document(..) => {}
|
||||
}
|
||||
if !crate::sanity::rect_in_range(m.transform_rect_bbox(retained)) {
|
||||
return Err(bad(PLACE, "placed art lies outside the canvas"));
|
||||
}
|
||||
let parent = st.insertion_parent();
|
||||
let below = st.current_layer().or_else(|| parent.and_then(|p| st.doc.layer_of(p)));
|
||||
let link = loaded.link.take().filter(|_| bool_or(p, "link", true));
|
||||
@@ -876,13 +967,19 @@ fn apply(s: &mut Session, read: PlaceRead) -> Result<Value> {
|
||||
if let Art::Dcs(a) = &loaded.art {
|
||||
warnings.extend(dcs::swatch_notes(&st.doc, &a.spots));
|
||||
}
|
||||
// A PSD file's slices move and scale with its art; one that would leave the canvas is left out.
|
||||
// A PSD file's slices move and scale with its art, through a distorted image's corners when
|
||||
// it takes them; one that would leave the canvas is left out.
|
||||
let read_count = read_slices.len();
|
||||
let slices: Slices = read_slices
|
||||
.into_iter()
|
||||
.filter_map(|(r, o)| {
|
||||
let corners = [Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x0, r.y1), Point::new(r.x1, r.y1)].map(|c| m * c);
|
||||
let placed = corners.iter().skip(1).fold(Rect::from_points(corners[0], corners[0]), |acc, c| acc.union_pt(*c));
|
||||
let placed = match distorted {
|
||||
Some((_, (_, _, page))) => page.map_rect_bbox(r)?,
|
||||
None => {
|
||||
let corners = [Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x0, r.y1), Point::new(r.x1, r.y1)].map(|c| m * c);
|
||||
corners.iter().skip(1).fold(Rect::from_points(corners[0], corners[0]), |acc, c| acc.union_pt(*c))
|
||||
}
|
||||
};
|
||||
super::slices::slice_rect_ok(placed).then_some((placed, o))
|
||||
})
|
||||
.collect();
|
||||
@@ -892,7 +989,10 @@ fn apply(s: &mut Session, read: PlaceRead) -> Result<Value> {
|
||||
n => warnings.push(format!("{n} slices would lie outside the canvas and were left out")),
|
||||
}
|
||||
let (id, size, slice_ids) = s.edit("Place", |d, sel| {
|
||||
let node = transformed(build(d, loaded, link), m);
|
||||
let mut node = transformed(build(d, loaded, link), m);
|
||||
if let Some((old_image, (_, q, _))) = distorted {
|
||||
node = with_corners(node, q).ok_or_else(|| super::xform::distorted_image_error(PLACE, old_image))?;
|
||||
}
|
||||
let size = node.geometric_bounds_with(&d.symbol_boxes()).unwrap_or_default();
|
||||
let (into, index) = match old {
|
||||
Some(old) => {
|
||||
@@ -1131,12 +1231,24 @@ fn queue(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
// ---------- queries ----------
|
||||
|
||||
/// The colour mode an image file stores its pixels in.
|
||||
fn color_mode(bytes: &[u8]) -> &'static str {
|
||||
match craft_image_codecs::decode(bytes).ok().map(|img| img.layout()) {
|
||||
Some(craft_image_codecs::ChannelLayout::Gray | craft_image_codecs::ChannelLayout::GrayA) => "Grayscale",
|
||||
Some(craft_image_codecs::ChannelLayout::Cmyk | craft_image_codecs::ChannelLayout::CmykA) => "CMYK",
|
||||
_ => "RGB",
|
||||
/// The colour mode an image file stores its pixels in. A PNG, JPEG, TIFF, PSD, GIF or BMP file's
|
||||
/// header says it and a WebP file is always RGB, so their pixels are not decoded; the Control bar
|
||||
/// and the Properties panel ask `image.info` again after every change, each step of a drag
|
||||
/// included. A file in another format is decoded.
|
||||
pub(crate) fn color_mode(bytes: &[u8]) -> &'static str {
|
||||
use craft_image_codecs::{ChannelLayout as L, RasterColorType as T};
|
||||
match craft_image_codecs::inspect_raster(bytes) {
|
||||
Ok(Some(i)) => match i.color_type {
|
||||
T::Bitmap | T::Gray | T::GrayAlpha => "Grayscale",
|
||||
T::Cmyk | T::CmykAlpha => "CMYK",
|
||||
_ => "RGB",
|
||||
},
|
||||
_ if craft_image_codecs::detect(bytes) == Some(craft_image_codecs::Format::WebP) => "RGB",
|
||||
_ => match craft_image_codecs::decode(bytes).ok().map(|img| img.layout()) {
|
||||
Some(L::Gray | L::GrayA) => "Grayscale",
|
||||
Some(L::Cmyk | L::CmykA) => "CMYK",
|
||||
_ => "RGB",
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -119,6 +119,9 @@ pub fn describe(p: &Plugin) -> Value {
|
||||
if !m.inputs.is_empty() {
|
||||
v["inputs"] = json!(m.inputs);
|
||||
}
|
||||
if !m.output_kinds.is_empty() {
|
||||
v["outputKinds"] = json!(m.output_kinds);
|
||||
}
|
||||
if !m.writes.is_empty() {
|
||||
v["writes"] = json!(m.writes);
|
||||
}
|
||||
@@ -1465,11 +1468,11 @@ fn install(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// A heavy plug-in is installed once a person agrees.
|
||||
if plugin.manifest().budget == Budget::Heavy && !allow_heavy {
|
||||
let (minutes, times) = vectorcraft_plugins::heavy_terms();
|
||||
let name = permissions::display_text(&plugin.manifest().name, permissions::MAX_SHOWN_NAME);
|
||||
return Err(bad(
|
||||
C,
|
||||
format!(
|
||||
"“{}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants",
|
||||
plugin.manifest().name
|
||||
"“{name}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants"
|
||||
),
|
||||
));
|
||||
}
|
||||
@@ -1612,6 +1615,10 @@ fn inspect(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if !refused.is_empty() {
|
||||
v["refusedCommands"] = json!(refused);
|
||||
}
|
||||
let translations = &plugin.manifest().translations;
|
||||
if !translations.is_empty() {
|
||||
v["translations"] = serde_json::to_value(translations).unwrap_or(Value::Null);
|
||||
}
|
||||
v
|
||||
})
|
||||
}
|
||||
@@ -1907,6 +1914,9 @@ pub(crate) fn install_folder(s: &mut Session, load: &mut FolderPending, turn: &S
|
||||
/// the grants of ids whose module lists no permissions are forgotten while no `plugin.install` can
|
||||
/// record one for another module → its report; saves the disabled list when loading changed it.
|
||||
pub(crate) fn end_folder(s: &mut Session, mut load: FolderPending, turn: &StoreTurn) -> Value {
|
||||
// Only native builds load modules, so only they save the disabled list.
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
let _ = (s, turn);
|
||||
let (report, retry) = match load.load.take() {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
Some(Ok(modules)) => {
|
||||
@@ -2408,7 +2418,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"List Plug-ins",
|
||||
[],
|
||||
None,
|
||||
"{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\"|\"generator\" (a generator draws art from its parameters, see plugin.generate), author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.<id>), format? and extensions? (an exporter's or importer's format id, plugin.<id>, for document.export or document.open's importer, and its file extensions), place?: true (an importer whose files file.place also reads, see file.place's importer), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), inputs?: [\"type\"|\"image\"|\"symbolInstance\"] (the objects besides paths a filter reads, see plugin.run), writes?: [\"type\"|\"image\"|\"symbolInstance\"] (the kinds among inputs a filter may change, see plugin.run), context?: [\"settings\"|\"artboards\"|\"layers\"|\"swatches\"] (the parts of the active document a filter's runs and its or a live effect's commands are given in _context.document, with or without a selection, see docs/plugins.md), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own; commands: a filter may run the commands its commandAllowlist names, see docs/plugins.md), commandAllowlist?: [command id] (the commands a filter with the commands permission may run while it runs, with vc_call), hash (the module's SHA-256), api (the plug-in API level it was built for, 1, 2 or 3), runtime?: \"js\" and script?: its .js file name (a JavaScript filter, see docs/plugins.md), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), appearanceOutput?: true (a live effect whose pieces, fills and strokes may also have opacity, a blending mode and effects), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.<id>.<command id>, which runs it), label, params (doc), paramsSchema, menu?: {path?: [menu label], after?: item label (escaped), placed?: false (it stays in its plug-in's submenu: its label reads like a built-in item or submenu of that menu or another plug-in command placed there), context?: [{menu: \"canvas\"|\"layers\", when?: \"selection\"|\"oneObject\"|\"typeObject\"|\"layerRow\"}] (the context menus that also list it)} (the menu its manifest places it in, see docs/plugins.md)}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}], leftOut} | null (under automation read roots, a folder outside them is null, and a failed file and a plug-in's source outside them are named by their file name), failed: [{file, error, from: \"store\"|\"folder\"}] (the plug-in files that didn't load in this process and that plugin.retry loads again: those of the plug-in store that didn't install, until they install or the store is loaded again, then those of the folder report's failed, without the disabled ones and ones skipped because another install or removal of their id came first), safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}",
|
||||
"{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\"|\"generator\" (a generator draws art from its parameters, see plugin.generate), author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.<id>), format? and extensions? (an exporter's or importer's format id, plugin.<id>, for document.export or document.open's importer, and its file extensions), place?: true (an importer whose files file.place also reads, see file.place's importer), outputKinds?: [\"type\"|\"image\"|\"layer\"|\"artboard\"] (what an importer at API level 4 returns besides paths, see docs/plugins.md), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), inputs?: [\"type\"|\"image\"|\"symbolInstance\"] (the objects besides paths a filter reads, see plugin.run), writes?: [\"type\"|\"image\"|\"symbolInstance\"] (the kinds among inputs a filter may change, see plugin.run), context?: [\"settings\"|\"artboards\"|\"layers\"|\"swatches\"] (the parts of the active document a filter's runs and its or a live effect's commands are given in _context.document, with or without a selection, see docs/plugins.md), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own; commands: a filter may run the commands its commandAllowlist names, see docs/plugins.md), commandAllowlist?: [command id] (the commands a filter with the commands permission may run while it runs, with vc_call), hash (the module's SHA-256), api (the plug-in API level it was built for, 1 to 4), runtime?: \"js\" and script?: its .js file name (a JavaScript filter, see docs/plugins.md), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), appearanceOutput?: true (a live effect whose pieces, fills and strokes may also have opacity, a blending mode and effects), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.<id>.<command id>, which runs it), label, params (doc), paramsSchema, menu?: {path?: [menu label], after?: item label (escaped), placed?: false (it stays in its plug-in's submenu: its label reads like a built-in item or submenu of that menu or another plug-in command placed there), context?: [{menu: \"canvas\"|\"layers\", when?: \"selection\"|\"oneObject\"|\"typeObject\"|\"layerRow\"}] (the context menus that also list it)} (the menu its manifest places it in, see docs/plugins.md)}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}], leftOut} | null (under automation read roots, a folder outside them is null, and a failed file and a plug-in's source outside them are named by their file name), failed: [{file, error, from: \"store\"|\"folder\"}] (the plug-in files that didn't load in this process and that plugin.retry loads again: those of the plug-in store that didn't install, until they install or the store is loaded again, then those of the folder report's failed, without the disabled ones and ones skipped because another install or removal of their id came first), safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}",
|
||||
always,
|
||||
list
|
||||
),
|
||||
@@ -2444,7 +2454,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Inspect Plug-in",
|
||||
[],
|
||||
None,
|
||||
"{path: a .wasm file or a .vcplugin manifest (desktop) | dataBase64: the module or a JavaScript plug-in's JSON, name?: the file name shown as its source (with dataBase64)} validate a plug-in without installing it, running none of its code → the plugin.list entry it would have, plus needsApproval: bool (true when it lists permissions no person has granted this very module, its bytes included: it then needs a person's approval, see plugin.install) and needsReplace: bool (true when it would take the place of another module with its id: plugin.install then needs replace: true), unknownCommands?: [id] (commandAllowlist ids no command has) and refusedCommands?: [id] (commandAllowlist ids no plug-in may call: plugin.install refuses the module)",
|
||||
"{path: a .wasm file or a .vcplugin manifest (desktop) | dataBase64: the module or a JavaScript plug-in's JSON, name?: the file name shown as its source (with dataBase64)} validate a plug-in without installing it, running none of its code → the plugin.list entry it would have, plus needsApproval: bool (true when it lists permissions no person has granted this very module, its bytes included: it then needs a person's approval, see plugin.install) and needsReplace: bool (true when it would take the place of another module with its id: plugin.install then needs replace: true), unknownCommands?: [id] (commandAllowlist ids no command has), refusedCommands?: [id] (commandAllowlist ids no plug-in may call: plugin.install refuses the module) and translations?: {language: {name?, params?, groups?, commands?}} (the manifest's translations as declared, when it gives any)",
|
||||
always,
|
||||
inspect
|
||||
),
|
||||
|
||||
@@ -70,6 +70,8 @@ const DENIED_PREFIXES: &[&str] = &[
|
||||
"text.rescanFonts",
|
||||
"text.fontList",
|
||||
"text.spelling.",
|
||||
// Language packs: downloads into, and removals from, the font store the Craft apps share.
|
||||
"proof.",
|
||||
"colorTheme.",
|
||||
"magicWand.",
|
||||
"eyedropper.",
|
||||
|
||||
@@ -6,6 +6,8 @@
|
||||
pub(super) const ALLOWED: &[&str] = &[
|
||||
"addon.arrange.grid",
|
||||
"addon.arrange.groupOverlapping",
|
||||
"addon.arrange.match",
|
||||
"addon.arrange.offset",
|
||||
"addon.arrange.randomizeOpacity",
|
||||
"addon.arrange.replace",
|
||||
"addon.arrange.size",
|
||||
@@ -104,6 +106,7 @@ pub(super) const ALLOWED: &[&str] = &[
|
||||
"appearance.removeItem",
|
||||
"appearance.setActiveItem",
|
||||
"appearance.setItem",
|
||||
"appearance.setNewArt",
|
||||
"appearance.showAllHidden",
|
||||
"appearance.targetContents",
|
||||
"appearance.transfer",
|
||||
@@ -152,6 +155,7 @@ pub(super) const ALLOWED: &[&str] = &[
|
||||
"charStyle.setAttrs",
|
||||
"charStyle.unused",
|
||||
"color.convert",
|
||||
"color.format",
|
||||
"color.gamutCheck",
|
||||
"color.harmony",
|
||||
"color.parse",
|
||||
@@ -541,6 +545,7 @@ pub(super) const ALLOWED: &[&str] = &[
|
||||
"select.object.brushStrokes",
|
||||
"select.object.clippingMasks",
|
||||
"select.object.directionHandles",
|
||||
"select.object.hairlineSlivers",
|
||||
"select.object.notAlignedToPixelGrid",
|
||||
"select.object.pointText",
|
||||
"select.object.slices",
|
||||
@@ -682,6 +687,7 @@ pub(super) const ALLOWED: &[&str] = &[
|
||||
"text.thread.info",
|
||||
"text.thread.releaseSelection",
|
||||
"text.thread.remove",
|
||||
"text.thread.setNeighbor",
|
||||
"text.touchType",
|
||||
"threeD.addGraphic",
|
||||
"threeD.mapArt",
|
||||
|
||||
@@ -18,7 +18,7 @@ use crate::script;
|
||||
pub const EXTS: &[&str] = &["jsx", "jsxinc", "jsxbin"];
|
||||
|
||||
/// The extensions of the scripts `script.run` takes as a file, in any case.
|
||||
pub const RUN_EXTS: &[&str] = &["js", "jsx"];
|
||||
pub const RUN_EXTS: &[&str] = &["js", "mjs", "jsx"];
|
||||
|
||||
/// Does `path` name a file `script.run` takes?
|
||||
pub fn runs(path: &str) -> bool {
|
||||
@@ -32,7 +32,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Run Script",
|
||||
[],
|
||||
None,
|
||||
"{path?: a .js or .jsx file | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt|window, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt) | [{control, event: click} | {control, event: change, value: text, number, item index or null} | {event: close}] (window: the steps of one show(), control being a control's name, or the text of a control without a name)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; new Window(\"dialog\", title) builds a ScriptUI dialog with add(type, bounds, text or items or value, properties) for group, panel, statictext, edittext, button, checkbox, radiobutton, dropdownlist, listbox (one selection), slider and progressbar (a group takes properties third, or fourth after a third that is not an object, and a list may take them there with properties.items), at most 512 controls 16 deep, 1024 list items and 16 KiB a text (other types, palettes and windows throw that they are not available yet); new Window and add also take a resource string such as \"dialog { g: Group { b: Button { text: 'OK' } } }\" in place of the type, which adds each control it lists through add and sets it and each other value as the property of its name (properties gives the creation properties and a list's items its item texts; at most 1 MiB nested 64 deep, and a malformed one throws a SyntaxError); preferredSize, size, minimumSize and maximumSize start with width and height -1 (left to the layout), lists have find and remove, containers remove, radio buttons added one after another turn each other off, notify runs a click's or a change's handlers without closing the dialog, addEventListener and removeEventListener take click, change, changing and show (show on the dialog only; at most 256 listeners a window or control; the other documented event types throw that they are not available yet, and an unknown type throws that there is no such event), a removed control leaves the dialog (no parent or window, and its events no longer reach the containers it was in), and Window.alert, Window.confirm and Window.prompt are alert, confirm and prompt; show() waits like a dialog function, runs onClick, onChanging, onChange, onShow, onClose and the listeners in the run's fuel, and returns close(result)'s resul
Line truncated
|
||||
"{path?: a script file (.js, .mjs or .jsx) | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), module?: true or false (default true for a path ending in .mjs, false otherwise; true runs the file or source as a .mjs file runs, as a module, and a source run this way imports no files), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt|window, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt) | [{control, event: click} | {control, event: change, value: text, number, item index or null} | {event: close}] (window: the steps of one show(), control being a control's name, or the text of a control without a name)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), actions?: [{set, name, steps: [{command, params?, step?: the step's place in the action, a whole number from 1 (default its place in the list)}]}] (the actions app.doScript(action, set, dialogs?) plays, matched by their exact names; a command.batch step gives its own steps; at most 4096 actions, 10000 steps an action, 100000 steps in all and 16 MiB as JSON; in the app, the Actions panel's actions with their included steps, which a caller's list replaces), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; new Window(\"dialog\", title) builds a ScriptUI dialog with add(type, bounds, text or items or value, properties) for group, panel, statictext, edittext, button, checkbox, radiobutton, dropdownlist, listbox (one selection), slider and progressbar (a group takes properties third, or fourth after a third that is not an object, and a list may take them there with properties.items), at most 512 controls 16 deep, 1024 list items and 16 KiB a text (other types, palettes and windows throw that they are not available yet); new Window and add also take a resource string such as \"dialog { g: Group { b: Button { text: 'OK' } } }\" in place of the type, which adds each control it lists through add and sets it and each other value as the property of its name (properties gives the creation properties and a list's items its item texts; at most 1 MiB nested 64 deep, and a malformed one throws a SyntaxError); preferredSize, size, minimumSize and maximumSize start with width and height -1 (left to the layout), lists have find and remove, containers remove, radio buttons added one after another turn each other off, notify runs a click's or a change's handler
Line truncated
|
||||
always,
|
||||
run
|
||||
),
|
||||
@@ -86,7 +86,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"List Installed Scripts",
|
||||
[],
|
||||
None,
|
||||
"{} list the .js and .jsx files of the Scripts folder next to the settings, which File › Scripts lists, each subfolder as a submenu, in menu order; only names are read, never a script's text; links, hidden files, names starting with a dot and folders without a script are left out. VectorCraft's own limits: 2048 folder entries looked at, 512 scripts, 128 subfolders, 4 levels of subfolders, names of 255 bytes, labels of 128 characters, 250 ms → {folder: the Scripts folder's path | null (a session without one, and the web), scripts: [{path, label: the file name without its extension (the whole file name when another row of its folder has that label), folders: [the labels of the subfolders it is in]}], truncated: a limit was reached or a subfolder could not be read, unreadable: the folder is there and could not be read, or is a link}",
|
||||
"{} list the .js, .mjs and .jsx files of the Scripts folder next to the settings, which File › Scripts lists, each subfolder as a submenu, in menu order; only names are read, never a script's text; links, hidden files, names starting with a dot and folders without a script are left out. VectorCraft's own limits: 2048 folder entries looked at, 512 scripts, 128 subfolders, 4 levels of subfolders, names of 255 bytes, labels of 128 characters, 250 ms → {folder: the Scripts folder's path | null (a session without one, and the web), scripts: [{path, label: the file name without its extension (the whole file name when another row of its folder has that label), folders: [the labels of the subfolders it is in]}], truncated: a limit was reached or a subfolder could not be read, unreadable: the folder is there and could not be read, or is a link}",
|
||||
always,
|
||||
list_installed
|
||||
),
|
||||
@@ -195,8 +195,10 @@ fn prepare(s: &Session, p: &Value) -> Result<script::Request> {
|
||||
if s.script_frames && !answers.is_empty() {
|
||||
return Err(param("`answers` is only for a run with nobody to ask: in the app, the person answers each dialog"));
|
||||
}
|
||||
let actions = script::actions::parse(p.get("actions")).map_err(param)?;
|
||||
let fuel = max_fuel(p)?;
|
||||
let installed = switch_or(p, "installed", false, "script.run")?;
|
||||
let module = switch_or(p, "module", script::include::module_script(path), "script.run")?;
|
||||
let mut checked_real = None;
|
||||
let text = match (path, source) {
|
||||
(Some(""), None) => return Err(param("`path` is empty")),
|
||||
@@ -212,7 +214,7 @@ fn prepare(s: &Session, p: &Value) -> Result<script::Request> {
|
||||
return Err(EngineError::Other(COMPILED.to_string()));
|
||||
}
|
||||
if !runs(path) {
|
||||
return Err(param("`path` must name a .js or .jsx file"));
|
||||
return Err(param("`path` must name a .js, .mjs or .jsx file"));
|
||||
}
|
||||
// One byte more than a script may have shows that the file is too large.
|
||||
let bytes = super::fileio::read_file_head(path, script::MAX_SOURCE_BYTES + 1)?;
|
||||
@@ -241,6 +243,8 @@ fn prepare(s: &Session, p: &Value) -> Result<script::Request> {
|
||||
fuel,
|
||||
locale,
|
||||
answers,
|
||||
module,
|
||||
actions,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -442,6 +446,8 @@ impl Session {
|
||||
fuel,
|
||||
locale,
|
||||
answers: vec![],
|
||||
module: script::include::module_script(path.to_str()),
|
||||
actions: vec![],
|
||||
};
|
||||
let runs = self.script_runs;
|
||||
self.script_start(request).map_err(|e| {
|
||||
|
||||
@@ -9,6 +9,7 @@ use vectorcraft_tools::builder::is_live_paint;
|
||||
|
||||
use super::object::can_align;
|
||||
use super::panelcmds::artboard_at;
|
||||
use super::pathops::{hairline_slivers, sliver_width, unmeasured_warning};
|
||||
use super::wand::{fill_of, stroke_of};
|
||||
use super::{
|
||||
CommandSpec, Result, Session, bad, bool_or, checked_id, checked_ids_param, cmd, color_value, has_doc, has_selection, index_opt, ok, str_param,
|
||||
@@ -205,6 +206,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
cmd!("select.object.strayPoints", "Stray Points", ["Select", "Object"], None, "{}", has_doc, |s, _| by_kind(s, |n| n
|
||||
.path_data()
|
||||
.is_some_and(|p| p.anchor_count() == 1))),
|
||||
cmd!(
|
||||
"select.object.hairlineSlivers",
|
||||
"Hairline Slivers…",
|
||||
["Select", "Object"],
|
||||
None,
|
||||
"{width?: pt 0.001..3 (0.03 mm, VectorCraft's own default)} select, in the document or inside the isolated group, the closed paths and compound paths that object.path.cleanUp's hairlineSlivers removes with this sliverWidth: a visible fill, no visible stroke, no effect, and no circle `width` across fits inside the fill; a compound path counts as one object, and hidden and locked objects, objects at 0% opacity and their members, template layers, clipping paths, guides and the members of live and generated art are left out → {count, warning?: how many shapes could not be measured (too complex, or past the run's limit of work) and were left out}",
|
||||
has_doc,
|
||||
select_hairline_slivers
|
||||
),
|
||||
cmd!("select.object.openPaths", "Open Paths", ["Select", "Object"], None, "{}", has_doc, |s, _| by_kind(s, |n| n
|
||||
.path_data()
|
||||
.is_some_and(|p| !p.is_closed()))),
|
||||
@@ -1459,6 +1469,24 @@ fn by_kind(s: &mut Session, f: fn(&Node) -> bool) -> Result<Value> {
|
||||
Ok(json!({ "count": s.doc()?.selection.objects.len() }))
|
||||
}
|
||||
|
||||
/// Select › Object › Hairline Slivers: the objects Clean Up's Hairline Slivers removes
|
||||
/// ([`hairline_slivers`]), inside the isolated group while one is isolated.
|
||||
fn select_hairline_slivers(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "select.object.hairlineSlivers";
|
||||
let width = sliver_width(p, "width", C)?;
|
||||
let st = s.doc()?;
|
||||
let (d, iso) = (&st.doc, st.isolation);
|
||||
let locks = d.locked_artboards();
|
||||
let found = hairline_slivers(d, width, &|id| is_selectable(d, iso, &locks, id));
|
||||
let warning = unmeasured_warning(found.unmeasured.len());
|
||||
s.select(|_, sel| sel.set(found.ids))?;
|
||||
let count = s.doc()?.selection.objects.len();
|
||||
Ok(match warning {
|
||||
Some(w) => json!({ "count": count, "warning": w }),
|
||||
None => json!({ "count": count }),
|
||||
})
|
||||
}
|
||||
|
||||
/// Select › Object › Not Aligned to Pixel Grid: the objects that can take the pixel-aligned
|
||||
/// property ([`can_align`]) and do not have it. A compound path counts as one object, so the walk
|
||||
/// does not look at the paths inside it.
|
||||
|
||||
@@ -6,12 +6,9 @@ use super::{
|
||||
CommandSpec, EngineError, Result, Session, bad, bool_or, checked_ids_param, cmd, f64_or, has_doc, id_param, number_or, object_param, point_param,
|
||||
};
|
||||
use serde_json::{Value, json};
|
||||
use std::{
|
||||
collections::{BTreeMap, HashMap},
|
||||
sync::Arc,
|
||||
};
|
||||
use std::{collections::BTreeMap, sync::Arc};
|
||||
use vectorcraft_doc::shaper::{EdgeEdit, FILL_PREFIX, FaceEdit, FaceSelector, SOURCES, STROKE_PREFIX, ShaperSpec};
|
||||
use vectorcraft_doc::{Appearance, AppearanceItem, Document, Node, NodeId, NodeKind};
|
||||
use vectorcraft_doc::{Appearance, AppearanceItem, Document, Node, NodeId, NodeKind, changed_nodes};
|
||||
use vectorcraft_geom::{FillRule, PathData, Point, Rect, Shape as _};
|
||||
use vectorcraft_pathops as po;
|
||||
use vectorcraft_tools::builder::{self as b, BuilderMap};
|
||||
@@ -392,15 +389,7 @@ fn generated(d: &mut Document, src: &[Arc<Node>], spec: &ShaperSpec, map: &Build
|
||||
}
|
||||
|
||||
fn changed_shaper_groups(before: &[Arc<Node>], after: &[Arc<Node>], out: &mut Vec<NodeId>) {
|
||||
let mut by_id: Option<HashMap<NodeId, &Arc<Node>>> = None;
|
||||
for (i, a) in after.iter().enumerate() {
|
||||
let b = match before.get(i) {
|
||||
Some(b) if b.id == a.id => Some(b),
|
||||
_ => by_id.get_or_insert_with(|| before.iter().map(|b| (b.id, b)).collect()).get(&a.id).copied(),
|
||||
};
|
||||
if b.is_some_and(|b| Arc::ptr_eq(b, a)) {
|
||||
continue;
|
||||
}
|
||||
for (_, a, b) in changed_nodes(before, after) {
|
||||
if a.extras().shaper.is_some() {
|
||||
out.push(a.id);
|
||||
}
|
||||
|
||||
@@ -325,10 +325,11 @@ pub fn misspellings_from(t: &TextObject, ignored: &BTreeSet<String>, from: usize
|
||||
/// not, since a save takes in the words another window saved), and a dictionary file attached.
|
||||
static DICTIONARY_GENERATION: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
/// The custom dictionary's generation: what [`misspellings`] found before it last changed may be
|
||||
/// out of date (Auto Spell Check checks the type again).
|
||||
/// The dictionaries' generation: what [`misspellings`] found before it last changed may be out of
|
||||
/// date (Auto Spell Check checks the type again). It moves on with the custom dictionary and with
|
||||
/// craft-proof's own dictionaries, which change when a Language pack is installed or removed.
|
||||
pub fn dictionary_generation() -> u64 {
|
||||
DICTIONARY_GENERATION.load(Ordering::Relaxed)
|
||||
DICTIONARY_GENERATION.load(Ordering::Relaxed).wrapping_add(craft_proof::dictionary_generation())
|
||||
}
|
||||
|
||||
fn dictionary_changed() {
|
||||
|
||||
@@ -148,8 +148,11 @@ macro_rules! style_cmds {
|
||||
};
|
||||
}
|
||||
|
||||
/// The largest document `charStyle.load`, `paraStyle.load` and `textStyle.loadAll` read, in bytes.
|
||||
pub const MAX_LOAD_BYTES: usize = 64 << 20;
|
||||
|
||||
/// The params of `charStyle.load`, `paraStyle.load` and `textStyle.loadAll`.
|
||||
const LOAD_PARAMS: &str = "{path? | data?: file text | dataBase64?, name?: file name (default: the path's)} copy the styles of this kind (textStyle.loadAll: character and paragraph styles) from a document VectorCraft opens (see document.formats) into this one, after its own, in one undo step, with the swatches and patterns they paint with, the symbols and brushes those patterns use, and the styles of either kind that type in those patterns and symbols is set in, as Paste brings those of pasted type (a global or spot color whose name this document gives another color is this document's). A style that is the same as the style here of its name, or of its name with a number (`Body 2`), isn't added again; any other is added under a free name (`Body 2`). The file's Normal styles aren't loaded, and a style whose attributes don't read or are out of the range charStyle.new or paraStyle.new takes, or whose name is empty, is skipped → {added: [names here], existing: [names already here], skipped: [names in the file]} (textStyle.loadAll: {charStyles: {…}, paraStyles: {…}}); charStyle.load and paraStyle.load list only the styles of their own kind";
|
||||
const LOAD_PARAMS: &str = "{path? | data?: file text | dataBase64?, name?: file name (default: the path's)} copy the styles of this kind (textStyle.loadAll: character and paragraph styles) from a document VectorCraft opens (see document.formats; at most 64 MB) into this one, after its own, in one undo step, with the swatches and patterns they paint with, the symbols and brushes those patterns use, and the styles of either kind that type in those patterns and symbols is set in, as Paste brings those of pasted type (a global or spot color whose name this document gives another color is this document's). A style that is the same as the style here of its name, or of its name with a number (`Body 2`), isn't added again; any other is added under a free name (`Body 2`). The file's Normal styles aren't loaded, and a style whose attributes don't read or are out of the range charStyle.new or paraStyle.new takes, or whose name is empty, is skipped → {added: [names here], existing: [names already here], skipped: [names in the file]} (textStyle.loadAll: {charStyles: {…}, paraStyles: {…}}); charStyle.load and paraStyle.load list only the styles of their own kind";
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
let mut v = style_cmds!(
|
||||
@@ -1222,12 +1225,17 @@ fn load(s: &mut Session, p: &Value, kinds: &[Kind]) -> Result<Value> {
|
||||
_ => "textStyle.loadAll".to_string(),
|
||||
};
|
||||
let path = str_param(p, "path");
|
||||
let bytes = match (path, str_param(p, "data"), str_param(p, "dataBase64")) {
|
||||
(Some(path), ..) => super::fileio::read_file(path)?,
|
||||
(None, Some(text), _) => text.as_bytes().to_vec(),
|
||||
(None, None, Some(b64)) => vectorcraft_format::base64_decode(b64).ok_or_else(|| bad(c, "bad dataBase64"))?,
|
||||
let too_large = || bad(c, format!("the file is larger than {} MB", MAX_LOAD_BYTES >> 20));
|
||||
let bytes: std::borrow::Cow<[u8]> = match (path, str_param(p, "data"), str_param(p, "dataBase64")) {
|
||||
(Some(path), ..) => super::fileio::read_file_head(path, MAX_LOAD_BYTES + 1)?.into(),
|
||||
(None, Some(text), _) => text.as_bytes().into(),
|
||||
(None, None, Some(b64)) if b64.len() > MAX_LOAD_BYTES / 3 * 4 + 4 => return Err(too_large()),
|
||||
(None, None, Some(b64)) => vectorcraft_format::base64_decode(b64).ok_or_else(|| bad(c, "bad dataBase64"))?.into(),
|
||||
_ => return Err(bad(c, "give `path`, `data` or `dataBase64`")),
|
||||
};
|
||||
if bytes.len() > MAX_LOAD_BYTES {
|
||||
return Err(too_large());
|
||||
}
|
||||
let file = str_param(p, "name").or(path).unwrap_or("Styles");
|
||||
let src = super::fileio::load(file, &bytes).map_err(|e| bad(c, e.to_string()))?;
|
||||
if src.preview_only {
|
||||
|
||||
@@ -896,6 +896,27 @@ fn load_all_styles_loads_both_kinds_in_one_step() {
|
||||
assert_eq!(s.doc().unwrap().doc, before);
|
||||
}
|
||||
|
||||
/// A file or `dataBase64` larger than 64 MB loads nothing and is not read past the limit.
|
||||
#[test]
|
||||
fn loading_refuses_a_file_larger_than_64_mb() {
|
||||
let (mut s, _) = session_with_text("Title");
|
||||
let dir = std::env::temp_dir().join(format!("vc-load-styles-big-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("Big.vectorcraft");
|
||||
std::fs::File::create(&path).unwrap().set_len(MAX_LOAD_BYTES as u64 + 1).unwrap();
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let r = s.execute("charStyle.load", &json!({"path": path.to_string_lossy()}));
|
||||
std::fs::remove_dir_all(&dir).ok();
|
||||
assert!(r.as_ref().is_err_and(|e| e.to_string().contains("larger than 64 MB")), "{r:?}");
|
||||
let b64 = "A".repeat(MAX_LOAD_BYTES / 3 * 4 + 8);
|
||||
let r = s.execute("paraStyle.load", &json!({"dataBase64": b64}));
|
||||
assert!(r.as_ref().is_err_and(|e| e.to_string().contains("larger than 64 MB")), "{r:?}");
|
||||
let text = " ".repeat(MAX_LOAD_BYTES + 1);
|
||||
let r = s.execute("textStyle.loadAll", &json!({"data": text}));
|
||||
assert!(r.as_ref().is_err_and(|e| e.to_string().contains("larger than 64 MB")), "{r:?}");
|
||||
assert_eq!(s.doc().unwrap().doc, before);
|
||||
}
|
||||
|
||||
/// A loaded character style whose size, scale, leading, shift, warichu Line Gap, stroke width or
|
||||
/// miter limit, tracking, kerning or rotation is out of the range `charStyle.new` takes is skipped.
|
||||
#[test]
|
||||
|
||||
@@ -59,6 +59,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_doc,
|
||||
break_thread
|
||||
),
|
||||
cmd!(
|
||||
"text.thread.setNeighbor",
|
||||
"Thread Text",
|
||||
[],
|
||||
None,
|
||||
"{id, side: \"next\"|\"previous\", neighbor: id|null} link area type or type on a path `id` to the frame that follows it (`next`) or comes before it (`previous`) in its story, or with null break that one link, as a script's `nextFrame` and `previousFrame` assignments do. Linking joins two stories: `id` must be the last frame of its story for `next` (the first for `previous`) and `neighbor` the first (the last) of another one, and the second story's text flows on after the first's. Breaking a link makes each side of it a story of its own: no text moves across the break, and the frames after it flow their own text again from their first frame, which now starts a paragraph. An error, with nothing changed, for point type or other art, a frame linked to itself, a link that would make a loop or go to a frame inside a story, and a frame of either story that is hidden or locked; a link that is already there, or a break where there is no link, changes nothing and records no undo step; the selection is kept → {changed: bool, threads: [[id…]] (the stories of the frames involved, after the change, a one-frame story as [id])}",
|
||||
has_doc,
|
||||
set_neighbor
|
||||
),
|
||||
cmd!(query "text.thread.info", "Threads", [], None, "{} → [[id…]] every thread in order", has_doc, |s, _| {
|
||||
Ok(json!(s.doc()?.doc.text_threads.iter().map(|t| t.iter().map(|i| i.0).collect::<Vec<_>>()).collect::<Vec<_>>()))
|
||||
}),
|
||||
@@ -986,5 +995,111 @@ fn break_thread(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
ok()
|
||||
}
|
||||
|
||||
/// The frames of the story `id` is a frame of, in thread order: its thread's area type and type on
|
||||
/// a path, each once, or `id` alone when it is in no thread.
|
||||
fn chain_of(d: &Document, id: NodeId) -> Vec<NodeId> {
|
||||
let mut frames = story_of(d, id);
|
||||
let mut seen = Ids::default();
|
||||
frames.retain(|f| seen.insert(*f));
|
||||
if frames.len() < 2 { vec![id] } else { frames }
|
||||
}
|
||||
|
||||
fn chain_ids(chains: &[&[NodeId]]) -> Value {
|
||||
json!(chains.iter().filter(|c| !c.is_empty()).map(|c| c.iter().map(|i| i.0).collect::<Vec<_>>()).collect::<Vec<_>>())
|
||||
}
|
||||
|
||||
/// `text.thread.setNeighbor`: link a frame to the frame after or before it, or break that link.
|
||||
fn set_neighbor(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "text.thread.setNeighbor";
|
||||
let id = checked_id(s, p.get("id").unwrap_or(&Value::Null), C)?;
|
||||
let next = match p.get("side").and_then(Value::as_str) {
|
||||
Some("next") => true,
|
||||
Some("previous") => false,
|
||||
_ => return Err(bad(C, "`side` must be \"next\" or \"previous\"")),
|
||||
};
|
||||
let neighbor = match p.get("neighbor") {
|
||||
None => return Err(bad(C, "missing `neighbor` (an id, or null to break the link)")),
|
||||
Some(Value::Null) => None,
|
||||
Some(v) => Some(checked_id(s, v, C)?),
|
||||
};
|
||||
let d = &s.doc()?.doc;
|
||||
if text_of(d, id).is_none() {
|
||||
return Err(bad(C, "`id` must be area type or type on a path"));
|
||||
}
|
||||
let locked = |frames: &[NodeId]| {
|
||||
let editable = d.editable();
|
||||
frames.iter().any(|f| !editable(*f))
|
||||
};
|
||||
let chain = chain_of(d, id);
|
||||
let Some(n) = neighbor else {
|
||||
// Break the link on that side: the frames before it and the frames after it.
|
||||
let i = chain.iter().position(|f| *f == id).unwrap_or(0);
|
||||
let at = if next { i + 1 } else { i };
|
||||
if at == 0 || at >= chain.len() {
|
||||
return Ok(json!({"changed": false, "threads": chain_ids(&[&chain])}));
|
||||
}
|
||||
if locked(&chain) {
|
||||
return Err(bad(C, "a frame of the story is hidden or locked"));
|
||||
}
|
||||
let (head, tail) = (chain[..at].to_vec(), chain[at..].to_vec());
|
||||
let cut: Ids = chain.iter().copied().collect();
|
||||
s.edit("Break Thread", |d, _| {
|
||||
d.text_threads.retain(|t| !t.iter().any(|f| cut.contains(f)));
|
||||
for part in [&head, &tail] {
|
||||
if part.len() >= 2 {
|
||||
d.text_threads.push(part.clone());
|
||||
}
|
||||
}
|
||||
// The first frame after the break starts its story, which flows again on this edit so
|
||||
// that its numbered paragraphs count from 1.
|
||||
if let Some(f) = tail.first() {
|
||||
touch(d, *f);
|
||||
}
|
||||
if let Some(NodeKind::Text(t)) = tail.first().and_then(|f| d.node_mut(*f)).map(|n| &mut n.kind)
|
||||
&& t.first_para_continues
|
||||
{
|
||||
t.first_para_continues = false;
|
||||
refresh_bounds(t);
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
return Ok(json!({"changed": true, "threads": chain_ids(&[&head, &tail])}));
|
||||
};
|
||||
if n == id {
|
||||
return Err(bad(C, "a frame cannot be linked to itself"));
|
||||
}
|
||||
if text_of(d, n).is_none() {
|
||||
return Err(bad(C, "`neighbor` must be area type or type on a path"));
|
||||
}
|
||||
// `first` is to flow into `second`.
|
||||
let (first, second) = if next { (id, n) } else { (n, id) };
|
||||
let (a, b) = if next { (chain, chain_of(d, n)) } else { (chain_of(d, n), chain) };
|
||||
if a.contains(&second) {
|
||||
if a.windows(2).any(|w| w == [first, second]) {
|
||||
return Ok(json!({"changed": false, "threads": chain_ids(&[&a])}));
|
||||
}
|
||||
return Err(bad(C, "the two frames are already in one story: the link would make a loop or reorder it"));
|
||||
}
|
||||
if a.last() != Some(&first) {
|
||||
return Err(bad(C, format!("frame {} already has a next frame: break that link first", first.0)));
|
||||
}
|
||||
if b.first() != Some(&second) {
|
||||
return Err(bad(C, format!("frame {} already has a previous frame: break that link first", second.0)));
|
||||
}
|
||||
if locked(&a) || locked(&b) {
|
||||
return Err(bad(C, "a frame of either story is hidden or locked"));
|
||||
}
|
||||
let joined: Vec<NodeId> = a.iter().chain(&b).copied().collect();
|
||||
let affected: Ids = joined.iter().copied().collect();
|
||||
s.edit("Thread Text", |d, _| {
|
||||
d.text_threads.retain(|t| !t.iter().any(|f| affected.contains(f)));
|
||||
d.text_threads.push(joined.clone());
|
||||
// Force a re-flow of the joined story on this edit.
|
||||
touch(d, first);
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({"changed": true, "threads": chain_ids(&[&joined])}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
+126
-35
@@ -4,8 +4,9 @@ use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::Paint;
|
||||
use vectorcraft_doc::{Node, NodeKind, OrientedBox, Scaling};
|
||||
use vectorcraft_geom::{Affine, Point, Rect, Vec2};
|
||||
use vectorcraft_doc::{Node, NodeKind, OrientedBox, Scaling, SymbolBoxes};
|
||||
use vectorcraft_geom::{Affine, Homography, Point, Rect, Vec2};
|
||||
use vectorcraft_tools::distort::project_node;
|
||||
|
||||
use super::edit::{outermost, selected_roots};
|
||||
use super::{
|
||||
@@ -21,7 +22,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Free Distort",
|
||||
[],
|
||||
None,
|
||||
"{corners: [[x,y]×4] (TL, TR, BR, BL), from?: [x0,y0,x1,y1] (default: selection bounds), angle?: degrees (counter-clockwise; `from`, or the selection bounds, is then a box in the frame turned by it, as a rotated bounding box is; default 0), ids?} projective warp of anchors and handles; an image's four corners go exactly where the warp takes them and its pixels are drawn in perspective between them (an error, and nothing changes, when an image's corners would fold over, fall on one line, cross the warp's horizon or lie too close together for a perspective map); a linked opacity mask's art is warped with its object, an unlinked one stays; each warped object's bounding box (the objects inside groups and the art of linked masks too) turns as the warp turns the art at its center (object.resetBoundingBox squares it again); corners where the box already stands change nothing and add no undo step",
|
||||
"{corners: [[x,y]×4] (TL, TR, BR, BL), from?: [x0,y0,x1,y1] (default: selection bounds), angle?: degrees (counter-clockwise; `from`, or the selection bounds, is then a box in the frame turned by it, as a rotated bounding box is; default 0), ids?} projective warp of anchors and handles; an image's four corners go exactly where the warp takes them and its pixels are drawn in perspective between them (an error, and nothing changes, when an image's corners would fold over, fall on one line, cross the warp's horizon or lie too close together for a perspective map); the corners of a type object's or symbol instance's box go exactly where the warp takes them too, and it stays type or an instance, drawn through the warp after any projection it had (the same errors, naming the object); a linked opacity mask's art is warped with its object, an unlinked one stays; each warped object's bounding box (the objects inside groups and the art of linked masks too) turns as the warp turns the art at its center (object.resetBoundingBox squares it again); corners where the box already stands change nothing and add no undo step",
|
||||
has_doc,
|
||||
distort
|
||||
),
|
||||
@@ -105,6 +106,21 @@ impl Projective {
|
||||
Point::new((a * u + b * v + c) / w, (d * u + e * v + f) / w)
|
||||
}
|
||||
|
||||
/// Whether the warp is a perspective map rather than an affine one.
|
||||
fn is_projective(&self) -> bool {
|
||||
let [.., g, h] = self.m;
|
||||
g != 0.0 || h != 0.0
|
||||
}
|
||||
|
||||
/// The warp as one page-to-page map, which [`Self::apply`] matches in front of the horizon.
|
||||
fn homography(&self) -> Homography {
|
||||
let [a, b, c, d, e, f, g, h] = self.m;
|
||||
let scale = |len: f64| if len.abs() > 1e-12 { 1.0 / len } else { 0.0 };
|
||||
let (sx, sy) = (scale(self.src.width()), scale(self.src.height()));
|
||||
let to_unit = Affine::new([sx, 0.0, 0.0, sy, -self.src.x0 * sx, -self.src.y0 * sy]) * self.pre;
|
||||
Homography([[a, b, c], [d, e, f], [g, h, 1.0]]).then_after(&Homography::from_affine(to_unit))
|
||||
}
|
||||
|
||||
/// Affine approximation at a point (for objects that can't be warped: text, images, symbols).
|
||||
fn affine_near(&self, p: Point) -> Affine {
|
||||
let eps = 1.0;
|
||||
@@ -127,6 +143,8 @@ fn warp_node(n: &mut Node, pr: &Projective) -> Option<Rect> {
|
||||
n.pin_gradients();
|
||||
// The children before these are left out of a group's or compound path's bounds.
|
||||
let skip = n.children().map_or(0, Vec::len) - n.editing_children().len();
|
||||
// Type and symbol instances drawn through the warp keep their gradients in their own art.
|
||||
let mut projected = false;
|
||||
let before = match &mut n.kind {
|
||||
NodeKind::Path { path, live, .. } => {
|
||||
let b = path.bounds();
|
||||
@@ -156,6 +174,15 @@ fn warp_node(n: &mut Node, pr: &Projective) -> Option<Rect> {
|
||||
}
|
||||
b
|
||||
}
|
||||
// Type and symbol instances keep their art and are drawn through the warp, after the
|
||||
// projection they had ([`project_node`]), so the corners of their box follow it exactly;
|
||||
// [`distort`] has checked that the projection stays finite and their corners in front of
|
||||
// the horizon.
|
||||
NodeKind::Text(_) | NodeKind::SymbolInstance { .. } if pr.is_projective() => {
|
||||
let b = n.geometric_bounds();
|
||||
projected = project_node(n, &pr.homography());
|
||||
b
|
||||
}
|
||||
_ => {
|
||||
// No editable points: the affine approximation (which maps the gradients too).
|
||||
let b = n.geometric_bounds();
|
||||
@@ -171,7 +198,9 @@ fn warp_node(n: &mut Node, pr: &Projective) -> Option<Rect> {
|
||||
if let Some(m) = n.extras_if_any().and_then(|x| x.mask.as_mut()).filter(|m| m.linked) {
|
||||
warp_node(Arc::make_mut(&mut m.art), pr);
|
||||
}
|
||||
n.appearance.warp_gradients(&|p| pr.affine_near(p));
|
||||
if !projected {
|
||||
n.appearance.warp_gradients(&|p| pr.affine_near(p));
|
||||
}
|
||||
before
|
||||
}
|
||||
|
||||
@@ -199,17 +228,19 @@ fn warp_children(children: &mut [Arc<Node>], pr: &Projective, counts: impl Fn(us
|
||||
})
|
||||
}
|
||||
|
||||
/// The first image in `n` (its children and the art of linked opacity masks, as [`warp_node`]
|
||||
/// reaches them) whose corners `pr` would fold, collapse or carry past the warp's horizon, with
|
||||
/// why.
|
||||
fn unwarpable_image(n: &Node, pr: &Projective) -> Option<(vectorcraft_doc::NodeId, Unwarpable)> {
|
||||
/// The first image, type object or symbol instance in `n` (its children and the art of linked
|
||||
/// opacity masks, as [`warp_node`] reaches them) whose corners `pr` would fold, collapse or carry
|
||||
/// past the warp's horizon, or type being edited flat, with why. `symbols` measures the boxes of
|
||||
/// symbol instances.
|
||||
fn unwarpable(n: &Node, pr: &Projective, symbols: &SymbolBoxes) -> Option<(vectorcraft_doc::NodeId, Cornered, Unwarpable)> {
|
||||
if let (Some(q), NodeKind::Image(im)) = (n.image_corners(), &n.kind) {
|
||||
if !q.iter().all(|p| pr.in_front(*p)) {
|
||||
return Some((n.id, Unwarpable::Horizon));
|
||||
return Some((n.id, Cornered::Image, Unwarpable::Horizon));
|
||||
}
|
||||
if let Err(e) = vectorcraft_doc::image_quad::check_for(im, &q.map(|p| pr.apply(p))) {
|
||||
return Some((
|
||||
n.id,
|
||||
Cornered::Image,
|
||||
match e {
|
||||
vectorcraft_doc::image_quad::QuadError::NotFinite | vectorcraft_doc::image_quad::QuadError::NotConvex => Unwarpable::NotConvex,
|
||||
vectorcraft_doc::image_quad::QuadError::TooNarrow => Unwarpable::TooNarrow,
|
||||
@@ -217,24 +248,79 @@ fn unwarpable_image(n: &Node, pr: &Projective) -> Option<(vectorcraft_doc::NodeI
|
||||
));
|
||||
}
|
||||
}
|
||||
warped_parts(n).into_iter().find_map(|c| unwarpable_image(c, pr))
|
||||
// Type and symbol instances are drawn through the warp ([`warp_node`]): their box's corners
|
||||
// must stay in front of its horizon, and the projection they end with must be one that draws.
|
||||
if let Some(kind) = Cornered::of(n).filter(|k| *k != Cornered::Image && pr.is_projective()) {
|
||||
if kind == Cornered::Type && n.extras().perspective.as_deref().is_some_and(|p| p.editing) {
|
||||
return Some((n.id, kind, Unwarpable::EditingFlat));
|
||||
}
|
||||
if n.drawn_corners(symbols).is_some_and(|q| !q.iter().all(|p| pr.in_front(*p))) {
|
||||
return Some((n.id, kind, Unwarpable::Horizon));
|
||||
}
|
||||
let had = n.extras().perspective.as_deref().and_then(|p| p.homography()).unwrap_or(Homography::IDENTITY);
|
||||
let Some(after) = pr.homography().checked_then_after(&had).and_then(|h| Homography::from_array(h.to_array())) else {
|
||||
return Some((n.id, kind, Unwarpable::TooNarrow));
|
||||
};
|
||||
// The map it ends with must place its flat corners by the rules it is drawn with.
|
||||
let flat = match n.extras().perspective.is_some() {
|
||||
true => {
|
||||
let mut flat = n.clone();
|
||||
flat.extras_mut().perspective = None;
|
||||
flat.drawn_corners(symbols)
|
||||
}
|
||||
false => n.drawn_corners(symbols),
|
||||
};
|
||||
if flat.is_some_and(|q| q.iter().any(|p| after.apply(*p).is_none())) {
|
||||
return Some((n.id, kind, Unwarpable::Horizon));
|
||||
}
|
||||
}
|
||||
warped_parts(n).into_iter().find_map(|c| unwarpable(c, pr, symbols))
|
||||
}
|
||||
|
||||
/// The first image in `n` that [`warp_node`] reaches (its children and the art of linked opacity
|
||||
/// masks).
|
||||
fn first_image(n: &Node) -> Option<vectorcraft_doc::NodeId> {
|
||||
if matches!(n.kind, NodeKind::Image(_)) {
|
||||
return Some(n.id);
|
||||
/// The first image, type object or symbol instance in `n` that [`warp_node`] reaches (its children
|
||||
/// and the art of linked opacity masks), whose corners follow the warp exactly.
|
||||
fn first_cornered(n: &Node) -> Option<(vectorcraft_doc::NodeId, Cornered)> {
|
||||
if let Some(kind) = Cornered::of(n) {
|
||||
return Some((n.id, kind));
|
||||
}
|
||||
warped_parts(n).into_iter().find_map(first_cornered)
|
||||
}
|
||||
|
||||
/// The objects whose corners follow a distort exactly.
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum Cornered {
|
||||
Image,
|
||||
Type,
|
||||
Symbol,
|
||||
}
|
||||
|
||||
impl Cornered {
|
||||
fn of(n: &Node) -> Option<Self> {
|
||||
match n.kind {
|
||||
NodeKind::Image(_) => Some(Self::Image),
|
||||
NodeKind::Text(_) => Some(Self::Type),
|
||||
NodeKind::SymbolInstance { .. } => Some(Self::Symbol),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The object's name in an error.
|
||||
fn noun(self) -> &'static str {
|
||||
match self {
|
||||
Self::Image => "image",
|
||||
Self::Type => "type object",
|
||||
Self::Symbol => "symbol instance",
|
||||
}
|
||||
}
|
||||
warped_parts(n).into_iter().find_map(first_image)
|
||||
}
|
||||
|
||||
/// The objects inside `n` that [`warp_node`] warps point by point: the children of layers, groups
|
||||
/// and compound paths, and the art of a linked opacity mask on those, paths and images. Other
|
||||
/// objects (blends, envelopes, repeats and the rest) take the warp's affine approximation whole.
|
||||
/// and compound paths, and the art of a linked opacity mask on those, paths, images, type and
|
||||
/// symbol instances. Other objects (blends, envelopes, repeats and the rest) take the warp's affine
|
||||
/// approximation whole.
|
||||
fn warped_parts(n: &Node) -> Vec<&Node> {
|
||||
let inside = matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. } | NodeKind::Compound { .. });
|
||||
let mask_too = inside || matches!(n.kind, NodeKind::Path { .. } | NodeKind::Image(_));
|
||||
let mask_too = inside || matches!(n.kind, NodeKind::Path { .. } | NodeKind::Image(_) | NodeKind::Text(_) | NodeKind::SymbolInstance { .. });
|
||||
let children = n.children().filter(|_| inside).into_iter().flatten().map(|c| &**c);
|
||||
let mask = n.extras().mask.as_deref().filter(|m| mask_too && m.linked).map(|m| &*m.art);
|
||||
children.chain(mask).collect()
|
||||
@@ -246,9 +332,11 @@ pub(crate) fn distorted_image_error(command: &str, id: vectorcraft_doc::NodeId)
|
||||
bad(command, format!("object {} is an image changed by Perspective Distort or Free Distort, which this command does not work on", id.0))
|
||||
}
|
||||
|
||||
/// Why an image cannot follow the corners of a distort.
|
||||
/// Why an image, type object or symbol instance cannot follow the corners of a distort.
|
||||
#[derive(Clone, Copy)]
|
||||
enum Unwarpable {
|
||||
/// Type is being edited flat in Edit Text.
|
||||
EditingFlat,
|
||||
/// Its corners would fold over, meet or fall on one line.
|
||||
NotConvex,
|
||||
/// A corner would cross the warp's horizon.
|
||||
@@ -257,14 +345,16 @@ enum Unwarpable {
|
||||
TooNarrow,
|
||||
}
|
||||
|
||||
/// The error of `object.distort` when image `id` cannot follow its corners.
|
||||
fn unwarpable_error(id: vectorcraft_doc::NodeId, why: Unwarpable) -> EngineError {
|
||||
/// The error of `object.distort` when object `id` (`kind`) cannot follow its corners.
|
||||
fn unwarpable_error(id: vectorcraft_doc::NodeId, kind: Cornered, why: Unwarpable) -> EngineError {
|
||||
const C: &str = "object.distort";
|
||||
let noun = kind.noun();
|
||||
match why {
|
||||
Unwarpable::NotConvex => bad(C, format!("image {} cannot be distorted this way: its corners would not make a convex shape", id.0)),
|
||||
Unwarpable::Horizon => bad(C, format!("image {} cannot be distorted this way: its corners would cross the warp's horizon", id.0)),
|
||||
Unwarpable::EditingFlat => bad(C, format!("{noun} {} cannot be distorted this way: it is being edited flat in Edit Text", id.0)),
|
||||
Unwarpable::NotConvex => bad(C, format!("{noun} {} cannot be distorted this way: its corners would not make a convex shape", id.0)),
|
||||
Unwarpable::Horizon => bad(C, format!("{noun} {} cannot be distorted this way: its corners would cross the warp's horizon", id.0)),
|
||||
Unwarpable::TooNarrow => {
|
||||
bad(C, format!("image {} cannot be distorted this way: its corners would be too close together for a perspective map", id.0))
|
||||
bad(C, format!("{noun} {} cannot be distorted this way: its corners would be too close together for a perspective map", id.0))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -311,25 +401,26 @@ fn distort(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Ok(ids_json);
|
||||
}
|
||||
let pr = Projective::from_box(src, [tl, tr, br, bl]);
|
||||
// An image's corners follow the handles exactly, so they must stay a convex shape: nothing
|
||||
// changes when one would not.
|
||||
// The corners of an image, a type object or a symbol instance follow the handles exactly, so
|
||||
// they must stay a convex shape: nothing changes when one would not.
|
||||
let doc = &s.doc()?.doc;
|
||||
// Corners that do not make a convex shape give no perspective map (the warp falls back to an
|
||||
// affine one), so an image cannot follow them.
|
||||
// affine one), so such an object cannot follow them.
|
||||
if vectorcraft_doc::image_quad::check(&[tl, tr, br, bl]).is_err()
|
||||
&& let Some(id) = ids.iter().filter_map(|id| doc.node(*id)).find_map(first_image)
|
||||
&& let Some((id, kind)) = ids.iter().filter_map(|id| doc.node(*id)).find_map(first_cornered)
|
||||
{
|
||||
return Err(unwarpable_error(id, Unwarpable::NotConvex));
|
||||
return Err(unwarpable_error(id, kind, Unwarpable::NotConvex));
|
||||
}
|
||||
// Corners so close together that the map falls back to an affine one: the box's corners do
|
||||
// not reach the handles, so an image cannot follow them either.
|
||||
// not reach the handles, so such an object cannot follow them either.
|
||||
if !reaches_corners(src, [tl, tr, br, bl])
|
||||
&& let Some(id) = ids.iter().filter_map(|id| doc.node(*id)).find_map(first_image)
|
||||
&& let Some((id, kind)) = ids.iter().filter_map(|id| doc.node(*id)).find_map(first_cornered)
|
||||
{
|
||||
return Err(unwarpable_error(id, Unwarpable::TooNarrow));
|
||||
return Err(unwarpable_error(id, kind, Unwarpable::TooNarrow));
|
||||
}
|
||||
if let Some((id, why)) = ids.iter().filter_map(|id| doc.node(*id)).find_map(|n| unwarpable_image(n, &pr)) {
|
||||
return Err(unwarpable_error(id, why));
|
||||
let symbols = doc.symbol_boxes();
|
||||
if let Some((id, kind, why)) = ids.iter().filter_map(|id| doc.node(*id)).find_map(|n| unwarpable(n, &pr, &symbols)) {
|
||||
return Err(unwarpable_error(id, kind, why));
|
||||
}
|
||||
s.edit("Free Distort", |d, _| {
|
||||
for id in &ids {
|
||||
|
||||
@@ -86,6 +86,9 @@ pub struct DocState {
|
||||
/// Whether Start Global Edit supports the one selected object
|
||||
/// ([`cmd::globaledit::SupportCache`]), as of a revision. Not saved, not undoable.
|
||||
pub(crate) global_edit_support: cmd::globaledit::SupportCache,
|
||||
/// The forms Start Global Edit compared the selected object with
|
||||
/// ([`cmd::globaledit::FormCache`]). Not saved, not undoable.
|
||||
pub(crate) global_edit_forms: cmd::globaledit::FormCache,
|
||||
/// What leaving symbol editing mode goes back to ([`cmd::symboledit`]).
|
||||
pub(crate) symbol_edit_return: cmd::symboledit::Return,
|
||||
pub interaction: Option<Interaction>,
|
||||
@@ -200,6 +203,24 @@ pub struct DocState {
|
||||
/// The selected objects as [`crate::Session::select`] last checked them or the proxies last
|
||||
/// read them, with the document they were checked in ([`SelectionRecord`]). Not saved.
|
||||
pub(crate) selection_record: Option<SelectionRecord>,
|
||||
/// The last move of the selected objects that changed nothing else they show ([`Moved`]).
|
||||
/// Not saved.
|
||||
pub moved: Option<Moved>,
|
||||
}
|
||||
|
||||
/// A move of whole objects that took document `from` to document `to`: each object the selection
|
||||
/// shows, the key object and the key anchor included, is the one in `from` moved by `by`, and
|
||||
/// nothing else they are drawn from changed (no member snapped to the pixel grid, no blend spine
|
||||
/// they follow, no pass after the edit). A view that drew the selection of `from` can
|
||||
/// move what it drew by `by` instead of building it again. It holds the documents as
|
||||
/// [`SelectionRecord::doc`] holds one, so a document changed in place no longer matches.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Moved {
|
||||
pub from: std::sync::Weak<Document>,
|
||||
pub to: std::sync::Weak<Document>,
|
||||
pub by: vectorcraft_geom::Vec2,
|
||||
/// The selection the move was made with, which is also the selection after it.
|
||||
pub selection: Selection,
|
||||
}
|
||||
|
||||
/// A selection of objects alone ([`objects_only`]) with the document it was checked or read in:
|
||||
@@ -481,6 +502,7 @@ impl DocState {
|
||||
global_edit: None,
|
||||
similar_outlines: Default::default(),
|
||||
global_edit_support: Default::default(),
|
||||
global_edit_forms: Default::default(),
|
||||
symbol_edit_return: Default::default(),
|
||||
interaction: None,
|
||||
undo_group: None,
|
||||
@@ -518,6 +540,7 @@ impl DocState {
|
||||
measured_in_own: None,
|
||||
inline_resolved: None,
|
||||
selection_record: None,
|
||||
moved: None,
|
||||
}
|
||||
}
|
||||
/// The [`SelectionRecord`] of the selection now: `None` when the document or the selected
|
||||
|
||||
@@ -715,6 +715,15 @@ impl ScriptScope {
|
||||
|
||||
/// The real path of the file at `path` and its first `max` bytes, at most.
|
||||
pub(crate) fn read(&self, path: &Path, max: usize) -> Result<(PathBuf, Vec<u8>), ScriptRead> {
|
||||
match self.read_unless(path, max, |_| false)? {
|
||||
(real, Some(bytes)) => Ok((real, bytes)),
|
||||
(_, None) => Err(ScriptRead::Failed("the file was not read".to_string())),
|
||||
}
|
||||
}
|
||||
|
||||
/// [`ScriptScope::read`], except that a file whose real path `known` accepts is not opened:
|
||||
/// → its real path and no bytes.
|
||||
pub(crate) fn read_unless(&self, path: &Path, max: usize, known: impl Fn(&Path) -> bool) -> Result<(PathBuf, Option<Vec<u8>>), ScriptRead> {
|
||||
use std::io::Read;
|
||||
if self.is_empty() || Self::refused_by_name(path) || check_read(&path.to_string_lossy()).is_err() {
|
||||
return Err(ScriptRead::Refused);
|
||||
@@ -730,6 +739,9 @@ impl ScriptScope {
|
||||
if !self.allows(&real) {
|
||||
return Err(ScriptRead::Refused);
|
||||
}
|
||||
if known(&real) {
|
||||
return Ok((real, None));
|
||||
}
|
||||
let file = std::fs::File::open(&real).map_err(|e| ScriptRead::Failed(e.to_string()))?;
|
||||
let meta = file.metadata().map_err(|e| ScriptRead::Failed(e.to_string()))?;
|
||||
if !meta.is_file() {
|
||||
@@ -747,7 +759,7 @@ impl ScriptScope {
|
||||
if std::fs::canonicalize(path).ok().as_ref() != Some(&real) {
|
||||
return Err(ScriptRead::Refused);
|
||||
}
|
||||
Ok((real, bytes))
|
||||
Ok((real, Some(bytes)))
|
||||
}
|
||||
|
||||
/// The first granted folder, as people read it (`None` for a script given as text).
|
||||
@@ -966,6 +978,21 @@ mod tests {
|
||||
p.to_string_lossy().into_owned()
|
||||
}
|
||||
|
||||
/// A file the caller already has is not opened: its size is not checked and no byte is read.
|
||||
#[test]
|
||||
fn a_known_script_file_is_not_read_again() {
|
||||
let (base, _) = folders("known");
|
||||
std::fs::write(base.join("in/big.js"), "x".repeat(64)).unwrap();
|
||||
let scope = ScriptScope::of_folder(&base.join("in"));
|
||||
let path = base.join("in/big.js");
|
||||
assert_eq!(scope.read(&path, 16).map(|(_, b)| b.len()), Err(ScriptRead::TooLarge));
|
||||
let real = std::fs::canonicalize(&path).unwrap();
|
||||
assert_eq!(scope.read_unless(&path, 16, |r| r == real), Ok((real.clone(), None)));
|
||||
assert_eq!(scope.read_unless(&path, 64, |_| false).map(|(_, b)| b.map(|b| b.len())), Ok(Some(64)));
|
||||
assert_eq!(scope.read_unless(&base.join("outside/secret.svg"), 64, |_| true), Err(ScriptRead::Refused));
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// The roots both grant: the deeper of two nested roots, nothing for roots apart, and a kind
|
||||
/// only one grants is not granted.
|
||||
#[test]
|
||||
|
||||
@@ -127,6 +127,12 @@ impl HistoryEntry {
|
||||
self.effect.filter(|id| effect_step_label(id) == Some(self.label.as_str()))
|
||||
}
|
||||
|
||||
/// A number no other step takes ([`History::step`]). Undo and Redo make the step they move
|
||||
/// with a new number, and so does an edit merged into the newest step.
|
||||
pub fn serial(&self) -> u64 {
|
||||
self.serial
|
||||
}
|
||||
|
||||
/// The step that undoing (redoing) the step `costs` came from makes: it keeps `doc`, the
|
||||
/// document before the undo, whose next state is now `now` (that step's document). Its figures
|
||||
/// are that step's the other way round when `doc` is still the document they were taken
|
||||
|
||||
@@ -12,6 +12,8 @@ pub mod guard;
|
||||
pub mod inspect;
|
||||
pub mod journal;
|
||||
pub mod link_watch;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub mod packs;
|
||||
pub mod schemas;
|
||||
pub mod steps;
|
||||
pub mod store;
|
||||
@@ -33,7 +35,7 @@ pub use cmd::flare::flare_settings;
|
||||
pub use cmd::gradient::{GradientEditPaints, StopOwner};
|
||||
pub use cmd::graph::{GraphTypeSubject, calculated_axes as graph_calculated_axes, graph_type_subject};
|
||||
pub use cmd::params::{check_keys, check_params};
|
||||
pub use cmd::pathops::{auto_simplify_level, can_outline_stroke};
|
||||
pub use cmd::pathops::{HAIRLINE_SLIVER_WIDTH, HAIRLINE_SLIVER_WIDTH_RANGE, auto_simplify_level, can_outline_stroke};
|
||||
pub use cmd::rasterfx::{export_pdf, flatten_raster_effects};
|
||||
pub use cmd::select::{path_fingerprint, storable_selection, stored_path_params, stored_path_step};
|
||||
pub use cmd::textwrap::TEXT_WRAP_OFFSET_RANGE;
|
||||
@@ -220,6 +222,9 @@ pub struct Session {
|
||||
/// Whether the loads of the stored plug-ins and of the plug-ins folder go on after the call
|
||||
/// that starts them ([`Session::load_plugins_in_background`]).
|
||||
plugin_loads_in_background: bool,
|
||||
/// The Language packs' generation the documents were last laid out for
|
||||
/// ([`Session::poll_language_packs`]).
|
||||
packs_seen: u64,
|
||||
/// The Scripts folder, whose scripts File › Scripts lists; `None`: no folder
|
||||
/// ([`Session::attach_scripts_dir`]).
|
||||
scripts_dir: Option<std::path::PathBuf>,
|
||||
@@ -373,6 +378,9 @@ pub struct Session {
|
||||
pub(crate) startup_failures: Vec<(String, String)>,
|
||||
/// Each open document's highest next id a run has seen, by [`DocState::uid`].
|
||||
pub(crate) script_high_water: std::collections::HashMap<u64, u64>,
|
||||
/// The styles the steps of a batch a script runs removed or renamed and the documents they
|
||||
/// reverted ([`script::note_style_lists`]).
|
||||
pub(crate) script_style_trail: script::StyleTrail,
|
||||
/// While a slice of a script runs in this session.
|
||||
pub(crate) script_in_run: bool,
|
||||
/// The desktop app supplies each window by (document uid, runtime window identity) while a
|
||||
@@ -504,7 +512,7 @@ pub(crate) use command_sets::SELECTS_GIVEN_IDS;
|
||||
#[cfg(test)]
|
||||
use command_sets::given_ids;
|
||||
pub use command_sets::{DRAWS_SHAPE, FIT_ACTIVE_ARTBOARD, ON_ACTIVE_ARTBOARD, waits_for_plugin_loads, waits_for_tool_edit};
|
||||
pub use doc_state::{DocState, LayersReveal, OpenRows, RecalledSelection, WindowView};
|
||||
pub use doc_state::{DocState, LayersReveal, Moved, OpenRows, RecalledSelection, WindowView};
|
||||
pub use error::{EngineError, READ_ONLY_LOCATION, Result, SCRIPT_BUSY};
|
||||
#[cfg(test)]
|
||||
use history::history_budget_for;
|
||||
|
||||
@@ -0,0 +1,389 @@
|
||||
//! Language packs (#4936, RFC-0011): the spelling dictionary, hyphenation patterns and licence
|
||||
//! texts of a language other than English, published by storytold/craft-i18n and installed into the
|
||||
//! Craft apps' shared font store (craft-libs `craft-font-store`, item kind `language-pack`), where
|
||||
//! craft-proof reads them (`craft_proof::packs`). A pack installed by another Craft app is used
|
||||
//! here too, since the apps share the store.
|
||||
//!
|
||||
//! The store downloads only while its download setting is on, which only the person using an app
|
||||
//! turns on, with their own click. Nothing here turns it on: [`use_font_store`] opens the store as
|
||||
//! an agent's, so `proof.installPack` from the CLI, MCP or a script installs only after the person
|
||||
//! allowed downloads.
|
||||
//!
|
||||
//! The packs state is the process's, like craft-proof's: one backend ([`set_backend`]), one list of
|
||||
//! installs running and one error per locale. In the desktop app installs run on a thread of their
|
||||
//! own ([`run_in_background`]) and [`crate::Session::poll_language_packs`] lays out the documents
|
||||
//! again when one ends; elsewhere they return once installed.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
||||
use std::sync::{Arc, Mutex, MutexGuard, PoisonError, RwLock};
|
||||
|
||||
pub use craft_font_store::Cancel;
|
||||
|
||||
/// One pack the pack index lists.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Pack {
|
||||
/// Lowercase BCP 47 tag (`nl`, `pt-br`), also the installed pack's folder name.
|
||||
pub locale: String,
|
||||
/// The language's own name (`Nederlands`).
|
||||
pub name: String,
|
||||
/// The download's size in bytes.
|
||||
pub size: u64,
|
||||
/// SPDX licence expression of the pack's data.
|
||||
pub licence: String,
|
||||
/// The licence class: `Embeddable` or `Download-only`.
|
||||
pub class: String,
|
||||
/// Whether it has a spelling dictionary.
|
||||
pub spelling: bool,
|
||||
/// Whether it has hyphenation patterns.
|
||||
pub hyphenation: bool,
|
||||
}
|
||||
|
||||
/// Where packs come from and go to: the font store ([`use_font_store`]), or a stand-in in tests.
|
||||
pub trait Backend: Send + Sync {
|
||||
/// The installed-packs folder craft-proof reads.
|
||||
fn packs_dir(&self) -> PathBuf;
|
||||
/// Whether the person allowed downloads.
|
||||
fn downloads_on(&self) -> bool;
|
||||
/// The packs of the index fetched last, with no request; empty before the first fetch.
|
||||
fn cached_index(&self) -> Vec<Pack>;
|
||||
/// Fetches the pinned pack index (needs downloads on).
|
||||
fn fetch_index(&self, cancel: &Cancel) -> Result<Vec<Pack>, String>;
|
||||
/// Downloads, checks and installs the pack for `locale`, which the index lists (needs downloads
|
||||
/// on), calling `progress(done, total)` in bytes.
|
||||
fn install(&self, locale: &str, cancel: &Cancel, progress: &mut dyn FnMut(u64, u64)) -> Result<(), String>;
|
||||
/// Removes the installed pack for `locale`.
|
||||
fn remove(&self, locale: &str) -> Result<(), String>;
|
||||
/// The test index used instead of the pinned one (`CRAFT_LANGUAGE_PACK_INDEX`), if any.
|
||||
fn index_override(&self) -> Option<String> {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// An install running.
|
||||
struct Job {
|
||||
done: u64,
|
||||
total: u64,
|
||||
cancel: Cancel,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Jobs {
|
||||
installing: BTreeMap<String, Job>,
|
||||
/// A fetch of the index running.
|
||||
refreshing: Option<Cancel>,
|
||||
/// The last failure of each locale's install or removal, and of the index fetch (key `""`).
|
||||
errors: BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
static BACKEND: RwLock<Option<Arc<dyn Backend>>> = RwLock::new(None);
|
||||
static JOBS: Mutex<Jobs> = Mutex::new(Jobs { installing: BTreeMap::new(), refreshing: None, errors: BTreeMap::new() });
|
||||
static BACKGROUND: AtomicBool = AtomicBool::new(false);
|
||||
/// Goes up each time the installed packs change.
|
||||
static GENERATION: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
fn jobs() -> MutexGuard<'static, Jobs> {
|
||||
JOBS.lock().unwrap_or_else(PoisonError::into_inner)
|
||||
}
|
||||
|
||||
/// Use `backend` for packs (`None`: none), and have craft-proof read its installed packs.
|
||||
pub fn set_backend(backend: Option<Arc<dyn Backend>>) {
|
||||
let dir = backend.as_ref().map(|b| b.packs_dir());
|
||||
*BACKEND.write().unwrap_or_else(PoisonError::into_inner) = backend;
|
||||
craft_proof::packs::set_packs_dir(dir);
|
||||
changed();
|
||||
}
|
||||
|
||||
/// The backend [`set_backend`] set.
|
||||
pub fn backend() -> Option<Arc<dyn Backend>> {
|
||||
BACKEND.read().unwrap_or_else(PoisonError::into_inner).clone()
|
||||
}
|
||||
|
||||
/// Use the Craft apps' shared font store for packs, as an agent's store (it can't turn downloads
|
||||
/// on): the desktop app and `vectorcraft-cli` call it at startup. Without a per-user folder there
|
||||
/// are no packs.
|
||||
pub fn use_font_store() {
|
||||
let env = craft_font_catalog::FontEnv::from_process();
|
||||
set_backend(craft_font_store::FontStore::for_agent(&env).map(|store| Arc::new(FontStoreBackend::new(store)) as Arc<dyn Backend>));
|
||||
}
|
||||
|
||||
/// Run installs and index fetches on a thread of their own (the desktop app, so its window keeps
|
||||
/// working) instead of returning once they are done.
|
||||
pub fn run_in_background(on: bool) {
|
||||
BACKGROUND.store(on, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// Goes up each time the installed packs change ([`crate::Session::poll_language_packs`]).
|
||||
pub fn generation() -> u64 {
|
||||
GENERATION.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// Read the packs folder again: spelling and hyphenation in its languages change.
|
||||
fn changed() {
|
||||
craft_proof::packs::reload();
|
||||
GENERATION.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// Whether an install or an index fetch is running.
|
||||
pub fn busy() -> bool {
|
||||
let j = jobs();
|
||||
!j.installing.is_empty() || j.refreshing.is_some()
|
||||
}
|
||||
|
||||
/// `raw` as a pack locale: trimmed, lower case, `_` read as `-` (`pt_BR` is `pt-br`); a language
|
||||
/// tag of letters and digits, at most 35 bytes, in parts of at most 8.
|
||||
pub fn parse_locale(raw: &str) -> Result<String, String> {
|
||||
let l = raw.trim().to_ascii_lowercase().replace('_', "-");
|
||||
let ok = !l.is_empty()
|
||||
&& l.len() <= 35
|
||||
&& l.split('-').all(|p| !p.is_empty() && p.len() <= 8 && p.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit()));
|
||||
if ok { Ok(l) } else { Err(format!("{:?} is not a language tag like nl or pt-br", raw.chars().take(40).collect::<String>())) }
|
||||
}
|
||||
|
||||
fn no_backend() -> String {
|
||||
"Language packs aren't available: there is no font store folder for this user".into()
|
||||
}
|
||||
|
||||
fn downloads_off() -> String {
|
||||
"downloading is turned off; only the person using a Craft app can turn it on, by installing a Language pack there".into()
|
||||
}
|
||||
|
||||
/// The packs the index fetched last lists.
|
||||
pub fn available() -> Vec<Pack> {
|
||||
backend().map(|b| b.cached_index()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// What `proof.packs` reports about the jobs.
|
||||
pub struct Status {
|
||||
/// The installs running, as (locale, bytes done, bytes in all).
|
||||
pub installing: Vec<(String, u64, u64)>,
|
||||
/// Whether the index is being fetched.
|
||||
pub refreshing: bool,
|
||||
/// The last error of each locale (`""`: the index fetch).
|
||||
pub errors: BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
/// The jobs running and the last errors.
|
||||
pub fn status() -> Status {
|
||||
let j = jobs();
|
||||
Status {
|
||||
installing: j.installing.iter().map(|(l, job)| (l.clone(), job.done, job.total)).collect(),
|
||||
refreshing: j.refreshing.is_some(),
|
||||
errors: j.errors.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
/// What an install or a fetch did.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Outcome {
|
||||
/// Done.
|
||||
Done,
|
||||
/// Running in the background ([`run_in_background`]).
|
||||
Started,
|
||||
}
|
||||
|
||||
/// Runs `job` on a thread of its own in the background, else here and gives its own result (never
|
||||
/// another call's, which the shared errors also hold). `undo` takes the job's entry back when its
|
||||
/// thread can't start.
|
||||
fn run(job: impl FnOnce() -> Result<(), String> + Send + 'static, undo: impl FnOnce()) -> Result<Outcome, String> {
|
||||
if !BACKGROUND.load(Ordering::Relaxed) {
|
||||
return job().map(|()| Outcome::Done);
|
||||
}
|
||||
match std::thread::Builder::new().name("language-pack".into()).spawn(move || {
|
||||
// The result is kept in the shared errors for `proof.packs`.
|
||||
let _ = job();
|
||||
}) {
|
||||
Ok(_) => Ok(Outcome::Started),
|
||||
Err(e) => {
|
||||
undo();
|
||||
Err(format!("couldn't start the download: {e}"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Fetches the pinned pack index again. Needs downloads on.
|
||||
pub fn refresh() -> Result<Outcome, String> {
|
||||
let b = backend().ok_or_else(no_backend)?;
|
||||
if !b.downloads_on() {
|
||||
return Err(downloads_off());
|
||||
}
|
||||
let cancel = {
|
||||
let mut j = jobs();
|
||||
if j.refreshing.is_some() {
|
||||
return Ok(Outcome::Started);
|
||||
}
|
||||
let cancel = Cancel::new();
|
||||
j.refreshing = Some(cancel.clone());
|
||||
j.errors.remove("");
|
||||
cancel
|
||||
};
|
||||
run(
|
||||
move || {
|
||||
let r = b.fetch_index(&cancel).map(|_| ());
|
||||
let mut j = jobs();
|
||||
j.refreshing = None;
|
||||
if let Err(e) = &r {
|
||||
j.errors.insert(String::new(), e.clone());
|
||||
}
|
||||
r
|
||||
},
|
||||
|| jobs().refreshing = None,
|
||||
)
|
||||
}
|
||||
|
||||
/// Installs the pack for `locale` (fetching the index first when it doesn't list it). Needs
|
||||
/// downloads on. Spelling and hyphenation in that language use it once it is installed.
|
||||
pub fn install(locale: &str) -> Result<Outcome, String> {
|
||||
let b = backend().ok_or_else(no_backend)?;
|
||||
if !b.downloads_on() {
|
||||
return Err(downloads_off());
|
||||
}
|
||||
let locale = locale.to_string();
|
||||
let cancel = {
|
||||
let mut j = jobs();
|
||||
if j.installing.contains_key(&locale) {
|
||||
return Ok(Outcome::Started);
|
||||
}
|
||||
let cancel = Cancel::new();
|
||||
j.installing.insert(locale.clone(), Job { done: 0, total: 0, cancel: cancel.clone() });
|
||||
j.errors.remove(&locale);
|
||||
cancel
|
||||
};
|
||||
let l = locale.clone();
|
||||
run(
|
||||
move || {
|
||||
let r = install_now(&*b, &l, &cancel);
|
||||
// craft-proof reads the new pack before the job ends, so a caller that sees no
|
||||
// install running sees the pack installed (`proof.packs`, `busy`).
|
||||
if r.is_ok() {
|
||||
changed();
|
||||
}
|
||||
let mut j = jobs();
|
||||
j.installing.remove(&l);
|
||||
if let Err(e) = &r {
|
||||
j.errors.insert(l, e.clone());
|
||||
}
|
||||
r
|
||||
},
|
||||
|| {
|
||||
jobs().installing.remove(&locale);
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
fn install_now(b: &dyn Backend, locale: &str, cancel: &Cancel) -> Result<(), String> {
|
||||
let listed = |packs: &[Pack]| packs.iter().any(|p| p.locale == locale);
|
||||
if !listed(&b.cached_index()) && !listed(&b.fetch_index(cancel)?) {
|
||||
return Err(format!("there is no Language pack for {locale}"));
|
||||
}
|
||||
b.install(locale, cancel, &mut |done, total| {
|
||||
if let Some(job) = jobs().installing.get_mut(locale) {
|
||||
(job.done, job.total) = (done, total);
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Stops the install of `locale` (or the index fetch, for `""`) if one is running.
|
||||
pub fn cancel(locale: &str) {
|
||||
let j = jobs();
|
||||
let c = if locale.is_empty() { j.refreshing.as_ref() } else { j.installing.get(locale).map(|job| &job.cancel) };
|
||||
if let Some(c) = c {
|
||||
c.cancel();
|
||||
}
|
||||
}
|
||||
|
||||
/// Removes the installed pack for `locale`; not while it is installing.
|
||||
pub fn remove(locale: &str) -> Result<(), String> {
|
||||
let b = backend().ok_or_else(no_backend)?;
|
||||
if jobs().installing.contains_key(locale) {
|
||||
return Err(format!("the {locale} pack is still installing"));
|
||||
}
|
||||
let r = b.remove(locale);
|
||||
changed();
|
||||
let mut j = jobs();
|
||||
match &r {
|
||||
Ok(()) => j.errors.remove(locale),
|
||||
Err(e) => j.errors.insert(locale.to_string(), e.clone()),
|
||||
};
|
||||
r
|
||||
}
|
||||
|
||||
/// The pack index this build trusts: craft-i18n's Language pack release `language-packs-2` (75
|
||||
/// packs), pinned by the sha256 of its `index.json`. The font store reads
|
||||
/// `CRAFT_LANGUAGE_PACK_INDEX` itself, to try packs from a test index (testing only).
|
||||
pub const PACK_INDEX: craft_font_store::PackIndexPin = craft_font_store::PackIndexPin {
|
||||
url: "https://github.com/storytold/craft-i18n/releases/download/language-packs-2/index.json",
|
||||
sha256: "b35c7aef0591177f18233b551da16035dcd615549ff874e169ffd19f16fea74b",
|
||||
};
|
||||
|
||||
/// The font store as the packs [`Backend`].
|
||||
struct FontStoreBackend {
|
||||
store: craft_font_store::FontStore,
|
||||
/// The index read or fetched last: an install takes its entry (URL, size, sha256) from it.
|
||||
index: Mutex<Option<craft_font_store::PackIndex>>,
|
||||
}
|
||||
|
||||
impl FontStoreBackend {
|
||||
fn new(store: craft_font_store::FontStore) -> Self {
|
||||
Self { store, index: Mutex::new(None) }
|
||||
}
|
||||
|
||||
fn keep(&self, index: craft_font_store::PackIndex) -> Vec<Pack> {
|
||||
let packs = index
|
||||
.packs
|
||||
.iter()
|
||||
.map(|e| Pack {
|
||||
locale: e.locale.clone(),
|
||||
name: e.name.clone(),
|
||||
size: e.size,
|
||||
licence: e.licence.clone(),
|
||||
class: e.class.clone(),
|
||||
spelling: e.spelling,
|
||||
hyphenation: e.hyphenation,
|
||||
})
|
||||
.collect();
|
||||
*self.index.lock().unwrap_or_else(PoisonError::into_inner) = Some(index);
|
||||
packs
|
||||
}
|
||||
}
|
||||
|
||||
impl Backend for FontStoreBackend {
|
||||
fn packs_dir(&self) -> PathBuf {
|
||||
self.store.language_packs_dir()
|
||||
}
|
||||
|
||||
fn downloads_on(&self) -> bool {
|
||||
self.store.network() == craft_font_store::Network::On
|
||||
}
|
||||
|
||||
fn cached_index(&self) -> Vec<Pack> {
|
||||
self.store.cached_language_pack_index(&PACK_INDEX).map(|i| self.keep(i)).unwrap_or_default()
|
||||
}
|
||||
|
||||
fn fetch_index(&self, cancel: &Cancel) -> Result<Vec<Pack>, String> {
|
||||
let index = self.store.fetch_language_pack_index(&PACK_INDEX, cancel).map_err(|e| e.to_string())?;
|
||||
Ok(self.keep(index))
|
||||
}
|
||||
|
||||
fn install(&self, locale: &str, cancel: &Cancel, progress: &mut dyn FnMut(u64, u64)) -> Result<(), String> {
|
||||
let held = self.index.lock().unwrap_or_else(PoisonError::into_inner).clone();
|
||||
let index = held.or_else(|| self.store.cached_language_pack_index(&PACK_INDEX)).ok_or("the list of Language packs hasn't been fetched")?;
|
||||
let entry = index.pack(locale).ok_or_else(|| format!("there is no Language pack for {locale}"))?.clone();
|
||||
self.store.install_language_pack(&index, &entry, cancel, &mut |p| progress(p.done, p.total)).map(|_| ()).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
fn remove(&self, locale: &str) -> Result<(), String> {
|
||||
self.store.remove_language_pack(locale).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
fn index_override(&self) -> Option<String> {
|
||||
craft_font_store::language_pack_index_overridden()
|
||||
}
|
||||
}
|
||||
|
||||
/// The font store backend in `dir`, for tests that need the real store without a request.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn font_store_in(dir: PathBuf) -> Arc<dyn Backend> {
|
||||
Arc::new(FontStoreBackend::new(craft_font_store::FontStore::new(dir, craft_font_store::Caller::Agent)))
|
||||
}
|
||||
@@ -0,0 +1,354 @@
|
||||
//! `app.doScript(action, set, dialogs?)`: plays an action of the Actions panel inside the script's
|
||||
//! run, as the VBScript reference's `DoScript` method of the Application object describes it
|
||||
//! (<https://web.archive.org/web/20170621180804/https://wwwimages.adobe.com/content/dam/Adobe/en/devnet/illustrator/sdk/CC2015_3/Illustrator%20VBScript%20Reference.pdf>).
|
||||
//!
|
||||
//! The actions a run can play come with its request (`script.run`'s `actions`), each with the steps
|
||||
//! that playback runs: the included steps, those of a recorded `command.batch` one by one. In the app
|
||||
//! they are the Actions panel's.
|
||||
//!
|
||||
//! VectorCraft's own rules, which the reference does not state:
|
||||
//! - The action and its set are matched by their exact names; a name that matches no action, or
|
||||
//! more than one, throws before any step runs.
|
||||
//! - The call returns when every step has run, or when the run is asked to stop. Each step runs as `vc.run` runs a command: it joins
|
||||
//! the run's transaction and its one undo step for each changed document, it is counted as a host
|
||||
//! call, it reads and writes files only where the script may, and a step that fails is put back
|
||||
//! and throws an error that names the step and the action, while the steps before it stay done.
|
||||
//! - A step a script may not run ([`super::refused_to_scripts`]), a step whose command the engine
|
||||
//! does not have (a View menu step, or one that plays an action), and a stop throw before any step
|
||||
//! runs, as does such a command among those an `action.batch` step plays. An action cannot play
|
||||
//! another action, so it cannot play itself.
|
||||
//! - `dialogs` is `true` or `false` (default `false`); VectorCraft's steps open no dialogs, so it
|
||||
//! changes nothing.
|
||||
|
||||
use std::rc::Rc;
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
use vectorcraft_js::{Data, HostError, HostMember};
|
||||
|
||||
use super::{Host, Link, command, current, refused_to_scripts};
|
||||
|
||||
/// The most actions a run's request may carry.
|
||||
pub const MAX_ACTIONS: usize = 4096;
|
||||
/// The most steps one action may have, after a `command.batch` step gives its own steps.
|
||||
pub const MAX_ACTION_STEPS: usize = 10_000;
|
||||
/// The most steps the actions of one request may have in all.
|
||||
pub const MAX_ALL_STEPS: usize = 100_000;
|
||||
/// The most bytes of the request's actions, as JSON.
|
||||
pub const MAX_ACTIONS_BYTES: usize = 16 << 20;
|
||||
/// The longest name of an action or a set, in bytes.
|
||||
pub const MAX_NAME_BYTES: usize = 1024;
|
||||
/// The longest command id of a step, in bytes.
|
||||
const MAX_ID_BYTES: usize = 256;
|
||||
/// The command id of a stop, which waits for the person in the Actions panel.
|
||||
pub const STOP_STEP: &str = "action.stop";
|
||||
|
||||
/// An action a run can play: its set's name, its name and the steps playback runs.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Playable {
|
||||
set: String,
|
||||
name: String,
|
||||
steps: Vec<Step>,
|
||||
}
|
||||
|
||||
/// A step of a [`Playable`]: its place in the action as errors give it (1 for the first; a step of a
|
||||
/// `command.batch` step has the batch's place and its own, as in `3.2`), its command, its params and
|
||||
/// their size as JSON, and for a step of a `command.batch` step the `artboard` that batch names.
|
||||
#[derive(Clone, Debug)]
|
||||
struct Step {
|
||||
place: String,
|
||||
id: String,
|
||||
params: Value,
|
||||
bytes: u64,
|
||||
artboard: Option<u64>,
|
||||
}
|
||||
|
||||
/// `script.run`'s `actions`: `[{set, name, steps: [{command, params?, step?}]}]`, where `step` is the
|
||||
/// step's place in the action (1 for the first; default its place in the list), within the limits
|
||||
/// above. A `command.batch` step gives its own steps, each at the batch's place and its own.
|
||||
pub fn parse(v: Option<&Value>) -> Result<Vec<Playable>, String> {
|
||||
let Some(v) = v else { return Ok(Vec::new()) };
|
||||
let Value::Array(list) = v else { return Err("`actions` must be a list".into()) };
|
||||
if list.len() > MAX_ACTIONS {
|
||||
return Err(format!("`actions` holds more than {MAX_ACTIONS} actions"));
|
||||
}
|
||||
if let Some(place) = super::too_deep(v) {
|
||||
return Err(format!("`actions{place}` is nested more than 64 levels deep"));
|
||||
}
|
||||
if serde_json::to_vec(v).map_or(true, |b| b.len() > MAX_ACTIONS_BYTES) {
|
||||
return Err("`actions` is larger than 16 MiB".into());
|
||||
}
|
||||
let mut all = 0usize;
|
||||
let mut out = Vec::with_capacity(list.len());
|
||||
for (i, a) in list.iter().enumerate() {
|
||||
let at = format!("`actions[{i}]`");
|
||||
let Value::Object(a) = a else { return Err(format!("{at} must be an object")) };
|
||||
only_keys(a, &["set", "name", "steps"], &at)?;
|
||||
let set = name_of(a, "set", &at)?;
|
||||
let name = name_of(a, "name", &at)?;
|
||||
let Some(Value::Array(given)) = a.get("steps") else { return Err(format!("{at}.steps must be a list")) };
|
||||
let mut steps = Vec::new();
|
||||
for (j, s) in given.iter().enumerate() {
|
||||
let at = format!("{at}.steps[{j}]");
|
||||
let Value::Object(s) = s else { return Err(format!("{at} must be an object")) };
|
||||
only_keys(s, &["command", "params", "step"], &at)?;
|
||||
let place = match s.get("step") {
|
||||
None => (j + 1).to_string(),
|
||||
Some(n) => match n.as_u64().filter(|n| (1..=1_000_000).contains(n)) {
|
||||
Some(n) => n.to_string(),
|
||||
None => return Err(format!("{at}.step must be a whole number from 1 to 1000000")),
|
||||
},
|
||||
};
|
||||
let (id, params) = command_of(s, &at)?;
|
||||
match params.get("commands") {
|
||||
Some(Value::Array(inner)) if id == "command.batch" => {
|
||||
// The batch's `artboard`, for its steps that act on the active artboard, as
|
||||
// `command.batch` reads it.
|
||||
let artboard = params.get("artboard").and_then(Value::as_u64);
|
||||
for (k, c) in inner.iter().enumerate() {
|
||||
let at = format!("{at}.params.commands[{k}]");
|
||||
let Value::Object(c) = c else { return Err(format!("{at} must be an object")) };
|
||||
let (id, params) = command_of(c, &at)?;
|
||||
if id == "command.batch" {
|
||||
return Err(format!("{at} is a command.batch inside a command.batch"));
|
||||
}
|
||||
steps.push(step(format!("{place}.{}", k + 1), id, params, artboard));
|
||||
}
|
||||
}
|
||||
_ if id == "command.batch" => return Err(format!("{at}.params.commands must be a list")),
|
||||
_ => steps.push(step(place, id, params, None)),
|
||||
}
|
||||
if steps.len() > MAX_ACTION_STEPS {
|
||||
return Err(format!("{at}: the action has more than {MAX_ACTION_STEPS} steps"));
|
||||
}
|
||||
}
|
||||
all += steps.len();
|
||||
if all > MAX_ALL_STEPS {
|
||||
return Err(format!("`actions` has more than {MAX_ALL_STEPS} steps in all"));
|
||||
}
|
||||
out.push(Playable { set, name, steps });
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
impl Playable {
|
||||
/// The steps the action runs.
|
||||
pub fn len(&self) -> usize {
|
||||
self.steps.len()
|
||||
}
|
||||
|
||||
/// Whether the action runs no step.
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.steps.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
fn only_keys(o: &Map<String, Value>, keys: &[&str], at: &str) -> Result<(), String> {
|
||||
match o.keys().find(|k| !keys.contains(&k.as_str())) {
|
||||
Some(k) => Err(format!("{at} has the unknown key `{}`", shown(k))),
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
fn name_of(o: &Map<String, Value>, key: &str, at: &str) -> Result<String, String> {
|
||||
match o.get(key) {
|
||||
Some(Value::String(s)) if s.len() <= MAX_NAME_BYTES => Ok(s.clone()),
|
||||
Some(Value::String(_)) => Err(format!("{at}.{key} is longer than {MAX_NAME_BYTES} bytes")),
|
||||
_ => Err(format!("{at}.{key} must be a string")),
|
||||
}
|
||||
}
|
||||
|
||||
/// A step's `command` and `params` (default `{}`).
|
||||
fn command_of(o: &Map<String, Value>, at: &str) -> Result<(String, Value), String> {
|
||||
let id = match o.get("command") {
|
||||
Some(Value::String(id)) if !id.is_empty() && id.len() <= MAX_ID_BYTES => id.clone(),
|
||||
_ => return Err(format!("{at}.command must be a command id")),
|
||||
};
|
||||
let params = match o.get("params") {
|
||||
None => json!({}),
|
||||
Some(p @ Value::Object(_)) => p.clone(),
|
||||
Some(_) => return Err(format!("{at}.params must be an object")),
|
||||
};
|
||||
Ok((id, params))
|
||||
}
|
||||
|
||||
fn step(place: String, id: String, params: Value, artboard: Option<u64>) -> Step {
|
||||
let bytes = serde_json::to_vec(¶ms).map_or(0, |b| b.len() as u64);
|
||||
Step { place, id, params, bytes, artboard }
|
||||
}
|
||||
|
||||
/// `text` as an error shows it: at most 80 characters, with … after a cut, and control characters
|
||||
/// as U+FFFD.
|
||||
fn shown(text: &str) -> String {
|
||||
const MAX: usize = 80;
|
||||
let mut out: String = text.chars().take(MAX).map(|c| if c.is_control() { '\u{fffd}' } else { c }).collect();
|
||||
if text.chars().nth(MAX).is_some() {
|
||||
out.push('…');
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The members of `app` this module adds.
|
||||
pub(super) fn app_members(link: &Link) -> Vec<super::dom::Described> {
|
||||
let l = link.clone();
|
||||
let play = Rc::new(move |a: Vec<Data>| {
|
||||
let h = current(&l)?;
|
||||
h.charge_call(16 + a.iter().map(super::data_size).sum::<u64>())?;
|
||||
do_script(&h, &a)
|
||||
});
|
||||
let info = super::dom::returns("undefined", &[("action", "string"), ("set", "string"), ("dialogs", "boolean")]);
|
||||
let mut members = vec![("doScript".to_string(), HostMember::Method(play), info)];
|
||||
members.extend(["loadAction", "unloadAction"].map(|name| super::dom::later(link, "Application", name)));
|
||||
members
|
||||
}
|
||||
|
||||
fn arg(a: &[Data], i: usize) -> &Data {
|
||||
a.get(i).unwrap_or(&Data::Undefined)
|
||||
}
|
||||
|
||||
/// `app.doScript(action, set, dialogs?)`, its arguments after `this`.
|
||||
fn do_script(h: &Host, a: &[Data]) -> std::result::Result<Data, HostError> {
|
||||
if a.len() > 4 {
|
||||
return Err(HostError::Type("doScript takes an action's name, its set's name and dialogs".into()));
|
||||
}
|
||||
let (Data::String(action), Data::String(set)) = (arg(a, 1), arg(a, 2)) else {
|
||||
return Err(HostError::Type("doScript needs the action's name and its set's name, as strings".into()));
|
||||
};
|
||||
if action.is_empty() || set.is_empty() {
|
||||
return Err(HostError::Error("doScript needs the action's name and its set's name".into()));
|
||||
}
|
||||
if action.len() > MAX_NAME_BYTES || set.len() > MAX_NAME_BYTES {
|
||||
return Err(HostError::Range(format!("an action's or a set's name is at most {MAX_NAME_BYTES} bytes")));
|
||||
}
|
||||
if !matches!(arg(a, 3), Data::Undefined | Data::Bool(_)) {
|
||||
return Err(HostError::Type("doScript's dialogs must be true or false".into()));
|
||||
}
|
||||
let found: Vec<&Playable> = h.actions.iter().filter(|p| p.set == *set && p.name == *action).take(2).collect();
|
||||
let p = match found.as_slice() {
|
||||
[p] => *p,
|
||||
[] if !h.actions.iter().any(|p| p.set == *set) => return Err(HostError::Error(format!("there is no action set “{}”", shown(set)))),
|
||||
[] => return Err(HostError::Error(format!("the set “{}” has no action “{}”", shown(set), shown(action)))),
|
||||
_ => return Err(HostError::Error(format!("the set “{}” has more than one action “{}”", shown(set), shown(action)))),
|
||||
};
|
||||
if p.steps.is_empty() {
|
||||
return Err(HostError::Error(format!("the action “{}” has no included steps", shown(&p.name))));
|
||||
}
|
||||
// Every step is checked before the first runs, so a step that cannot run leaves the documents as
|
||||
// they were.
|
||||
for s in &p.steps {
|
||||
if let Some((place, id)) = refused_step(s) {
|
||||
let name = shown(&p.name);
|
||||
return Err(HostError::Error(if id == STOP_STEP {
|
||||
format!("step {place} of “{name}” is a stop, which a script cannot wait at")
|
||||
} else {
|
||||
format!("step {place} of “{name}” runs `{}`, which a script cannot run", shown(&id))
|
||||
}));
|
||||
}
|
||||
}
|
||||
for s in &p.steps {
|
||||
// A run asked to stop runs no further step; the realm ends it at its next instruction and
|
||||
// puts the documents back.
|
||||
if h.session.borrow().script_stop.is_set() {
|
||||
break;
|
||||
}
|
||||
h.charge_call(16 + s.id.len() as u64 + s.bytes)?;
|
||||
// Saved steps run as they run in the Actions panel: keys their commands no longer read are
|
||||
// passed over.
|
||||
let start = Start { active: &h.active_artboards, picks: h.artboard_picks.as_ref(), batch: s.artboard };
|
||||
let params = on_active_artboard(&h.session.borrow(), &start, &s.id, &s.params);
|
||||
let outer = h.session.borrow_mut().set_replaying(true);
|
||||
let r = command(h, &s.id, ¶ms);
|
||||
h.session.borrow_mut().set_replaying(outer);
|
||||
if let Err(e) = r {
|
||||
let named = |m: String| format!("action step {} of “{}” (`{}`) failed: {m}", s.place, shown(&p.name), shown(&s.id));
|
||||
return Err(match e {
|
||||
HostError::Error(m) | HostError::Type(m) | HostError::Range(m) | HostError::Syntax(m) => HostError::Error(named(m)),
|
||||
other => other,
|
||||
});
|
||||
}
|
||||
}
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
/// The place and command of the first command step `s` would run that a script may not run: the
|
||||
/// step itself, or one of the `commands` an `action.batch` step plays on each file (placed as the
|
||||
/// batch's place and its own, as in `3.2`). A stop, a command a script may not run and a command the
|
||||
/// engine does not have are refused.
|
||||
fn refused_step(s: &Step) -> Option<(String, String)> {
|
||||
let refused = |id: &str| id == STOP_STEP || refused_to_scripts(id) || crate::find_command(id).is_none();
|
||||
if refused(&s.id) {
|
||||
return Some((s.place.clone(), s.id.clone()));
|
||||
}
|
||||
if s.id != "action.batch" {
|
||||
return None;
|
||||
}
|
||||
let commands = s.params.get("commands").and_then(Value::as_array)?;
|
||||
commands.iter().enumerate().find_map(|(k, c)| {
|
||||
let id = c.get("command").and_then(Value::as_str).unwrap_or("");
|
||||
refused(id).then(|| (format!("{}.{}", s.place, k + 1), id.to_owned()))
|
||||
})
|
||||
}
|
||||
|
||||
/// `params` of step `id`, with the active artboard of the active document added as a
|
||||
/// `command.batch` given that artboard adds it when the Actions panel plays the step: `artboard` for
|
||||
/// the commands that act on the active artboard, `index` for Fit to Artwork Bounds and Fit to
|
||||
/// Selected Art. The active artboard is the index `start` gives for the document (its index as the
|
||||
/// run started, which the view keeps), past the last artboard the last one, as the view shows it
|
||||
/// after a step deletes artboards; a document the run opened has its own ([`super::dom`]'s). While
|
||||
/// the Artboard tool has several artboards selected, a Fit to Artwork Bounds step gets those as its
|
||||
/// `indices` instead, and a paste step gets none (it pastes on them). The run gives the tool fresh
|
||||
/// state, which drops its selection, so while the tool is still the Artboard tool and has none, the
|
||||
/// selection [`Start::picks`] holds for the document as the run started applies: a Fit to Artwork
|
||||
/// Bounds step gets those as its `indices` and a paste step as its `artboards`, the ones past the
|
||||
/// last artboard left out, and only while two or more remain. A step of a recorded `command.batch`
|
||||
/// that names its `artboard` ([`Start::batch`]) gets that artboard instead of the active one, past
|
||||
/// the last artboard the last one, and none in a document without artboards, as `command.batch`
|
||||
/// gives it. A paste step in a document without artboards, or one that names `artboards`, and a Fit
|
||||
/// to Artwork Bounds step that names `indices`, get none. A key the step gives is kept.
|
||||
pub(crate) fn on_active_artboard(s: &crate::Session, start: &Start<'_>, id: &str, params: &Value) -> Value {
|
||||
let mut params = params.clone();
|
||||
let Some(st) = s.active() else { return params };
|
||||
let n = st.doc.artboards.len();
|
||||
let active = match (start.batch, start.active.iter().find(|(uid, _)| *uid == st.uid)) {
|
||||
(Some(_), _) if n == 0 => return params,
|
||||
(Some(a), _) => usize::try_from(a).map_or(n - 1, |a| a.min(n - 1)),
|
||||
(None, Some((_, i))) => (*i).min(n.saturating_sub(1)),
|
||||
(None, None) => super::dom::active_artboard(st),
|
||||
};
|
||||
let paste = matches!(id, "edit.pasteInPlace" | "edit.pasteInFront" | "edit.pasteInBack");
|
||||
let fit_art = id == "artboard.fitToArt";
|
||||
let key = if crate::ON_ACTIVE_ARTBOARD.contains(&id) {
|
||||
"artboard"
|
||||
} else if crate::FIT_ACTIVE_ARTBOARD.contains(&id) {
|
||||
"index"
|
||||
} else {
|
||||
return params;
|
||||
};
|
||||
let Some(p) = params.as_object_mut() else { return params };
|
||||
if p.contains_key(key) || (fit_art && p.contains_key("indices")) || (paste && (n == 0 || p.contains_key("artboards"))) {
|
||||
return params;
|
||||
}
|
||||
let picks = if paste || fit_art { crate::cmd::artboard_tool_picks(s) } else { Vec::new() };
|
||||
let kept: Vec<usize> = match start.picks {
|
||||
Some((uid, list)) if picks.is_empty() && (paste || fit_art) && *uid == st.uid && s.tool_id() == "artboard" => {
|
||||
list.iter().copied().filter(|i| *i < n).collect()
|
||||
}
|
||||
_ => Vec::new(),
|
||||
};
|
||||
if kept.len() >= 2 {
|
||||
p.insert((if fit_art { "indices" } else { "artboards" }).into(), json!(kept));
|
||||
} else if picks.is_empty() {
|
||||
p.insert(key.into(), json!(active));
|
||||
} else if fit_art {
|
||||
p.insert("indices".into(), json!(picks));
|
||||
}
|
||||
params
|
||||
}
|
||||
|
||||
/// What [`on_active_artboard`] reads besides the session: the index of each open document's active
|
||||
/// artboard as the run started, by document uid; the Artboard tool's selection as the run started,
|
||||
/// with its document's uid; and the `artboard` a step's recorded `command.batch` names.
|
||||
pub(crate) struct Start<'a> {
|
||||
pub active: &'a [(u64, usize)],
|
||||
pub picks: Option<&'a (u64, Vec<usize>)>,
|
||||
pub batch: Option<u64>,
|
||||
}
|
||||
+344
-59
@@ -44,6 +44,9 @@
|
||||
//! the active artboard (`ARTBOARDCOORDINATESYSTEM`), as `app.coordinateSystem` says for the run.
|
||||
//! - Enumerated values are strings such as `"ZOrderMethod.BRINGTOFRONT"`.
|
||||
//! - `app.activeDocument` with no document open throws `No active document`.
|
||||
//! - `app.undo()` and `app.redo()` act on the active document and reach only the steps the run
|
||||
//! made; with no such step they change nothing, and with no document open they throw
|
||||
//! `No active document`.
|
||||
//! - Assigning `Document.selection` takes one object, a list of them, `null` or `[]`; every object
|
||||
//! must be one of that document's that can be selected, or nothing changes. `undefined` throws.
|
||||
//! - `controlBounds` is the visible bounds, widened to take in the direction points of every path
|
||||
@@ -59,11 +62,12 @@
|
||||
//! A center outside the canvas after coordinate conversion throws a `RangeError`.
|
||||
//! - Members the help pages list that are not here yet throw an error that says so, and `reflect`
|
||||
//! leaves them out.
|
||||
//! - Assigning `hidden`, `locked`, `opacity`, `position`, `left`, `top`, `width` or `height` to an
|
||||
//! object in a hidden or locked layer, and `zOrder()` on one, throw `Cannot edit` and change
|
||||
//! nothing, even for the value the object has. The exception is `opacity` given the value the
|
||||
//! object has when that changes nothing; on a graph's mark or label whose series or kind keeps
|
||||
//! another opacity it would still change the graph, so it is refused too. Its `name` and `note`
|
||||
//! - Assigning `hidden`, `locked`, `opacity`, `blendingMode`, `position`, `left`, `top`, `width` or
|
||||
//! `height` to an object in a hidden or locked layer, and `zOrder()` on one, throw `Cannot edit`
|
||||
//! and change nothing, even for the value the object has. The exception is `opacity` or
|
||||
//! `blendingMode` given the value the object has when that changes nothing; on a graph's mark or
|
||||
//! label whose series or kind keeps another opacity or blend mode it would still change the graph,
|
||||
//! so it is refused too. Its `name` and `note`
|
||||
//! still change. An object that is hidden or locked itself, or is in a hidden or locked group,
|
||||
//! takes them.
|
||||
//! - `name` and `note` take a number or a Boolean as the text `String(value)` gives.
|
||||
@@ -81,6 +85,7 @@ use std::rc::Rc;
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::BlendMode;
|
||||
use vectorcraft_geom::{Point, Rect};
|
||||
use vectorcraft_js::{
|
||||
ArgInfo, Data, HostClass, HostError, HostFunction, HostItem, HostMember, MemberInfo, Realm, RunError, host_ref, host_ref_parts,
|
||||
@@ -90,6 +95,7 @@ use super::{HISTORY_LOST, Host, Link, Savepoint, command, command_value, current
|
||||
use crate::{DocState, Document, NodeId, NodeKind, Session, WindowView};
|
||||
|
||||
mod tags;
|
||||
mod text;
|
||||
mod variables;
|
||||
|
||||
pub use variables::{MAX_HANDLES, STALE_DATASET, STALE_VARIABLE};
|
||||
@@ -105,6 +111,13 @@ pub(super) fn after_command(h: &Host, before: Option<(u64, Vec<crate::doc::DataS
|
||||
variables::after_command(h, before);
|
||||
}
|
||||
|
||||
mod colors;
|
||||
mod defaults;
|
||||
mod paths;
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) use paths::POINT_LOOKS;
|
||||
|
||||
/// The error for a member read or called with no document open.
|
||||
pub const NO_ACTIVE_DOCUMENT: &str = "No active document";
|
||||
/// The error for an object that was deleted, or that came from an earlier run.
|
||||
@@ -155,16 +168,41 @@ const ARTBOARD_COORDS: &str = "CoordinateSystem.ARTBOARDCOORDINATESYSTEM";
|
||||
|
||||
/// What the object model keeps for one run: its coordinate system, the lists of page items and the
|
||||
/// answers of which objects are on a locked artboard for the last [`ITEM_LISTS`] documents read,
|
||||
/// each kept while its document is unchanged, whether a call's own savepoint ([`atomically`]) is
|
||||
/// open, the settings of each `DocumentPreset` the run made, with the size of the values they hold
|
||||
/// now and the most they may hold (the run's heap), and the `Variable` and `Dataset` objects it
|
||||
/// gave out.
|
||||
/// each kept while its document is unchanged, the lists of paths, the point changes of a path not
|
||||
/// written yet, how many times each path's points went stale and each path as the run last saw its
|
||||
/// points, whether a call's own savepoint ([`atomically`]) is open, the settings of each
|
||||
/// `DocumentPreset` the run made, with the size of the values they hold now and the most they may
|
||||
/// hold (the run's heap), and the `Variable` and `Dataset` objects it gave out.
|
||||
#[derive(Default)]
|
||||
pub(super) struct State {
|
||||
coords: Cell<Coords>,
|
||||
items: RefCell<Vec<ItemList>>,
|
||||
/// The last list of each document's paths ([`paths`]), kept while that document is unchanged.
|
||||
paths: RefCell<Vec<ItemList>>,
|
||||
/// A path and its subpaths with the point changes the run has made to it and not written yet
|
||||
/// ([`flush`]).
|
||||
pending: RefCell<Option<(Item, Vec<vectorcraft_geom::path::SubPath>)>>,
|
||||
/// The index of the first point of each subpath of the path whose points the run read last,
|
||||
/// and what they were counted from ([`paths`]).
|
||||
point_starts: RefCell<Option<(paths::Counted, Rc<Vec<usize>>)>>,
|
||||
/// How many times the points the run read of each path went stale, by document uid and path id
|
||||
/// ([`paths`]).
|
||||
point_cuts: RefCell<std::collections::HashMap<(u64, u64), u64>>,
|
||||
/// Each path whose points the run read, as the run last saw it, by document uid and then path
|
||||
/// id ([`paths`]).
|
||||
point_nodes: RefCell<std::collections::HashMap<u64, std::collections::HashMap<u64, Arc<crate::doc::Node>>>>,
|
||||
/// The path whose points the object model is writing with `path.setAnchors`, the only path
|
||||
/// that command changes ([`paths`]).
|
||||
one_path: Cell<Option<Item>>,
|
||||
/// Each document, by uid, as it was when the run last looked at all the paths in it whose
|
||||
/// points it read ([`paths`]).
|
||||
point_docs: RefCell<std::collections::HashMap<u64, Arc<Document>>>,
|
||||
/// The item the object model is changing ([`edit_item`]), whose points stay valid through the
|
||||
/// change.
|
||||
editing: Cell<Option<Item>>,
|
||||
locked: RefCell<Vec<LockedList>>,
|
||||
saving: Cell<bool>,
|
||||
text: text::TextState,
|
||||
presets: RefCell<Vec<Vec<(String, Data)>>>,
|
||||
preset_bytes: Cell<u64>,
|
||||
preset_limit: u64,
|
||||
@@ -192,25 +230,48 @@ fn atomically<T>(h: &Host, f: impl FnOnce(&Host) -> std::result::Result<T, HostE
|
||||
return f(h);
|
||||
}
|
||||
let save = Savepoint::take(&mut h.session.borrow_mut(), "edit.duplicate");
|
||||
let styles = text::styles::mark(h);
|
||||
let mark = h.growth_mark();
|
||||
h.dom.saving.set(true);
|
||||
let r = f(h);
|
||||
h.dom.saving.set(false);
|
||||
let mut s = h.session.borrow_mut();
|
||||
if r.is_ok() {
|
||||
save.keep(&mut s);
|
||||
} else {
|
||||
{
|
||||
let mut s = h.session.borrow_mut();
|
||||
if r.is_ok() {
|
||||
save.keep(&mut s);
|
||||
return r;
|
||||
}
|
||||
h.put_growth_back(mark);
|
||||
if !save.restore(&mut s) {
|
||||
return Err(HostError::Abort(HISTORY_LOST.to_string()));
|
||||
}
|
||||
}
|
||||
// Style objects are put back with the documents.
|
||||
text::styles::put_back(h, styles);
|
||||
r
|
||||
}
|
||||
|
||||
/// A document's uid, the document as it was, and the ids of its page items then.
|
||||
type ItemList = (u64, Arc<Document>, Rc<Vec<NodeId>>);
|
||||
|
||||
/// The most documents whose lists [`State`] keeps at once, the least recently listed going first.
|
||||
const KEPT_LISTS: usize = 8;
|
||||
|
||||
/// The list kept in `lists` for the document `st`, while that document is unchanged.
|
||||
fn kept_list(lists: &RefCell<Vec<ItemList>>, st: &DocState) -> Option<Rc<Vec<NodeId>>> {
|
||||
lists.borrow().iter().find(|(uid, doc, _)| *uid == st.uid && Arc::ptr_eq(doc, &st.doc)).map(|(_, _, ids)| ids.clone())
|
||||
}
|
||||
|
||||
/// Keeps `ids` in `lists` as the list of the document `st`, in place of the one it had.
|
||||
fn keep_list(lists: &RefCell<Vec<ItemList>>, st: &DocState, ids: &Rc<Vec<NodeId>>) {
|
||||
let mut l = lists.borrow_mut();
|
||||
l.retain(|(uid, ..)| *uid != st.uid);
|
||||
if l.len() >= KEPT_LISTS {
|
||||
l.remove(0);
|
||||
}
|
||||
l.push((st.uid, st.doc.clone(), ids.clone()));
|
||||
}
|
||||
|
||||
/// A document's uid, the document and its new art ([`Document::new_art`]) as they were, and for
|
||||
/// each object of a layer or sublayer asked about then, whether it was on a locked artboard.
|
||||
type LockedList = (u64, Arc<Document>, Arc<HashSet<NodeId>>, HashMap<NodeId, bool>);
|
||||
@@ -267,15 +328,40 @@ type Answer = std::result::Result<Data, HostError>;
|
||||
/// A member function: the run's host and the call's arguments, `this` first.
|
||||
type Member = fn(&Host, &[Data]) -> Answer;
|
||||
|
||||
/// A member function that first writes the point changes waiting in [`State`] ([`flush`]).
|
||||
fn function(link: &Link, f: Member) -> HostFunction {
|
||||
call(link, f, true)
|
||||
}
|
||||
|
||||
/// A member function of the points of a path, which reads and adds to the point changes waiting in
|
||||
/// [`State`] instead of writing them first.
|
||||
fn point_function(link: &Link, f: Member) -> HostFunction {
|
||||
call(link, f, false)
|
||||
}
|
||||
|
||||
fn call(link: &Link, f: Member, flushing: bool) -> HostFunction {
|
||||
let l = link.clone();
|
||||
Rc::new(move |a: Vec<Data>| {
|
||||
let h = current(&l)?;
|
||||
h.charge_call(16 + a.iter().map(data_size).sum::<u64>())?;
|
||||
if flushing {
|
||||
flush(&h)?;
|
||||
}
|
||||
f(&h, &a)
|
||||
})
|
||||
}
|
||||
|
||||
/// Writes the point changes of a path that wait in [`State`] with one command ([`paths::flush`]).
|
||||
pub(super) fn flush(h: &Host) -> std::result::Result<(), HostError> {
|
||||
paths::flush(h)
|
||||
}
|
||||
|
||||
/// Notes the changes a command made to the points of the paths the run has read
|
||||
/// ([`paths::see_all_points`]).
|
||||
pub(super) fn see_points(h: &Host) {
|
||||
paths::see_all_points(h)
|
||||
}
|
||||
|
||||
fn get(link: &Link, f: Member) -> HostMember {
|
||||
HostMember::Get(function(link, f))
|
||||
}
|
||||
@@ -288,8 +374,21 @@ fn method(link: &Link, f: Member) -> HostMember {
|
||||
HostMember::Method(function(link, f))
|
||||
}
|
||||
|
||||
/// [`get`], [`property`] and [`method`] for a member of the points of a path ([`point_function`]).
|
||||
fn point_get(link: &Link, f: Member) -> HostMember {
|
||||
HostMember::Get(point_function(link, f))
|
||||
}
|
||||
|
||||
fn point_property(link: &Link, g: Member, s: Member) -> HostMember {
|
||||
HostMember::Property { get: point_function(link, g), set: point_function(link, s) }
|
||||
}
|
||||
|
||||
fn point_method(link: &Link, f: Member) -> HostMember {
|
||||
HostMember::Method(point_function(link, f))
|
||||
}
|
||||
|
||||
/// A member of a class with what `reflect` tells of it.
|
||||
type Described = (String, HostMember, MemberInfo);
|
||||
pub(super) type Described = (String, HostMember, MemberInfo);
|
||||
|
||||
/// A property's or a method's result's type for `reflect`.
|
||||
fn typed(data_type: &str) -> MemberInfo {
|
||||
@@ -297,15 +396,16 @@ fn typed(data_type: &str) -> MemberInfo {
|
||||
}
|
||||
|
||||
/// A method's result's type and its arguments' names and types, for `reflect`.
|
||||
fn returns(data_type: &str, arguments: &[(&str, &str)]) -> MemberInfo {
|
||||
pub(super) fn returns(data_type: &str, arguments: &[(&str, &str)]) -> MemberInfo {
|
||||
let arguments = arguments.iter().map(|(n, t)| ArgInfo { name: (*n).into(), data_type: (*t).into(), ..ArgInfo::default() }).collect();
|
||||
MemberInfo { arguments, ..typed(data_type) }
|
||||
}
|
||||
|
||||
/// A member the help pages list that is not available yet: reading or assigning it throws, after
|
||||
/// the check that a document or page item `this` is still there. `hasOwnProperty` is false for it,
|
||||
/// so a script that checks for the member first skips it, and `reflect` leaves it out.
|
||||
fn later(link: &Link, class: &'static str, name: &'static str) -> Described {
|
||||
/// the check that a document, page item, path point or text range `this` is still there.
|
||||
/// `hasOwnProperty` is false for it, so a script that checks for the member first skips it, and
|
||||
/// `reflect` leaves it out.
|
||||
pub(super) fn later(link: &Link, class: &'static str, name: &'static str) -> Described {
|
||||
let message = format!("{class}.{name} is not available yet");
|
||||
let l = link.clone();
|
||||
let f: HostFunction = Rc::new(move |a: Vec<Data>| {
|
||||
@@ -315,9 +415,15 @@ fn later(link: &Link, class: &'static str, name: &'static str) -> Described {
|
||||
"Document" => {
|
||||
doc_of(&h, arg(&a, 0), "Document")?;
|
||||
}
|
||||
"PageItem" => {
|
||||
"PageItem" | "PathItem" | "TextFrame" => {
|
||||
item_of(&h, arg(&a, 0))?;
|
||||
}
|
||||
"PathPoint" => {
|
||||
paths::this_point(&h, &a)?;
|
||||
}
|
||||
"TextRange" => {
|
||||
text::check_range(&h, arg(&a, 0))?;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
Err(HostError::Error(message.clone()))
|
||||
@@ -564,7 +670,7 @@ struct Frame {
|
||||
}
|
||||
|
||||
/// The index of the active artboard of `st`, as the view keeps it.
|
||||
fn active_artboard(st: &DocState) -> usize {
|
||||
pub(super) fn active_artboard(st: &DocState) -> usize {
|
||||
let index_of = |id: u32| st.doc.artboards.iter().position(|a| a.id == id);
|
||||
st.active_artboard.and_then(index_of).or_else(|| st.doc.opened_artboard.and_then(index_of)).unwrap_or(0)
|
||||
}
|
||||
@@ -641,6 +747,12 @@ fn restore_selection(h: &Host, doc: &Document, before: &crate::doc::Selection) -
|
||||
return Ok(());
|
||||
}
|
||||
let partial = |id: &NodeId| before.anchors.contains_key(id) || before.segments.contains_key(id);
|
||||
// Anchors and segments the change removed (a path opened or given fewer points) are left out.
|
||||
let left = |id: &NodeId, p: usize, test: &dyn Fn(&vectorcraft_geom::path::SubPath) -> bool| {
|
||||
doc.node(*id).and_then(|n| n.path_data()).is_some_and(|pd| pd.subpaths.get(p).is_some_and(test))
|
||||
};
|
||||
let anchor_left = |id: &NodeId, p: usize, k: usize| left(id, p, &|sp| k < sp.anchors.len());
|
||||
let segment_left = |id: &NodeId, p: usize, k: usize| left(id, p, &|sp| sp.has_segment(k, true));
|
||||
let kept: Vec<NodeId> = before.objects.iter().copied().filter(keep).collect();
|
||||
if kept.is_empty() {
|
||||
command(h, "select.none", &json!({}))?;
|
||||
@@ -653,7 +765,7 @@ fn restore_selection(h: &Host, doc: &Document, before: &crate::doc::Selection) -
|
||||
.iter()
|
||||
.map(|i| {
|
||||
let anchors: Vec<[usize; 2]> = match before.anchors.get(i) {
|
||||
Some(a) => a.iter().map(|(p, k)| [*p, *k]).collect(),
|
||||
Some(a) => a.iter().filter(|(p, k)| anchor_left(i, *p, *k)).map(|(p, k)| [*p, *k]).collect(),
|
||||
// A path with only segments selected gets them back below, with no anchors.
|
||||
None if before.segments.contains_key(i) => Vec::new(),
|
||||
None => doc.node(*i).and_then(|n| n.path_data()).map(|p| p.anchors().map(|(s, k, _)| [s, k]).collect()).unwrap_or_default(),
|
||||
@@ -664,7 +776,10 @@ fn restore_selection(h: &Host, doc: &Document, before: &crate::doc::Selection) -
|
||||
command(h, "select.anchorsMany", &json!({"items": items, "mode": "set"}))?;
|
||||
}
|
||||
for (i, segments) in before.segments.iter().filter(|(i, _)| keep(i)) {
|
||||
let segments: Vec<[usize; 2]> = segments.iter().map(|(p, k)| [*p, *k]).collect();
|
||||
let segments: Vec<[usize; 2]> = segments.iter().filter(|(p, k)| segment_left(i, *p, *k)).map(|(p, k)| [*p, *k]).collect();
|
||||
if segments.is_empty() {
|
||||
continue;
|
||||
}
|
||||
command(h, "select.segments", &json!({"id": i.0, "segments": segments, "mode": "add"}))?;
|
||||
}
|
||||
let guides: Vec<NodeId> = doc.ruler_guides().into_iter().filter_map(|g| g.id).collect();
|
||||
@@ -779,9 +894,20 @@ fn on_doc<T>(
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
/// Runs `id` with `params` on the item's document, its selection kept.
|
||||
/// Marks stale the style objects whose styles a command the run ran removed or renamed.
|
||||
pub(super) fn after_kept_command(h: &Host) {
|
||||
text::styles::after_command(h);
|
||||
}
|
||||
|
||||
/// Runs `id` with `params` on the item's document, its selection kept, as one change: when the
|
||||
/// selection cannot be put back, the edit is undone too. The points the run read of the item's
|
||||
/// paths stay valid through the change ([`paths::see_all_points`]).
|
||||
fn edit_item(h: &Host, item: Item, id: &str, params: &Value) -> std::result::Result<Data, HostError> {
|
||||
on_doc(h, item.doc.uid, true, |h| command(h, id, params))
|
||||
paths::see_all_points(h);
|
||||
let kept = h.dom.editing.replace(Some(item));
|
||||
let r = atomically(h, |h| on_doc(h, item.doc.uid, true, |h| command(h, id, params)));
|
||||
h.dom.editing.set(kept);
|
||||
r
|
||||
}
|
||||
|
||||
/// Reads the document of `doc` with `f`.
|
||||
@@ -810,6 +936,28 @@ fn app_set_active(h: &Host, a: &[Data]) -> Answer {
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
/// `app.undo()` and `app.redo()`: `edit.undo` or `edit.redo` in the active document, which reach
|
||||
/// only the steps the run made. With no step to undo or redo they change nothing.
|
||||
fn app_history(h: &Host, id: &str, redo: bool) -> Answer {
|
||||
let has_step = {
|
||||
let s = h.session.borrow();
|
||||
let st = s.active().ok_or_else(|| HostError::Error(NO_ACTIVE_DOCUMENT.into()))?;
|
||||
if redo { !st.history.redo.is_empty() } else { !st.history.undo.is_empty() }
|
||||
};
|
||||
if has_step {
|
||||
command(h, id, &json!({}))?;
|
||||
}
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
fn app_undo(h: &Host, _: &[Data]) -> Answer {
|
||||
app_history(h, "edit.undo", false)
|
||||
}
|
||||
|
||||
fn app_redo(h: &Host, _: &[Data]) -> Answer {
|
||||
app_history(h, "edit.redo", true)
|
||||
}
|
||||
|
||||
fn app_selection(h: &Host, _: &[Data]) -> Answer {
|
||||
let uid = h.session.borrow().active().map(|st| st.uid);
|
||||
match uid {
|
||||
@@ -944,11 +1092,19 @@ fn front_docs(s: &Session) -> impl Iterator<Item = &DocState> {
|
||||
s.front_order().into_iter().map(|i| &s.documents()[i])
|
||||
}
|
||||
|
||||
/// `documents[i]`, and `documents["name"]` as `getByName` reads it.
|
||||
/// `documents[i]`, and `documents["name"]` as `getByName` reads it. A key that is the text of a
|
||||
/// number but not an array index, such as `-1` or `1.5`, reaches the indexer as a number and is
|
||||
/// looked up as that name, giving `undefined` when no document has it.
|
||||
fn docs_at(h: &Host, a: &[Data]) -> Answer {
|
||||
let s = h.session.borrow();
|
||||
let at = match arg(a, 1) {
|
||||
Data::Number(n) => whole(*n).and_then(|i| usize::try_from(i).ok()).and_then(|i| front_docs(&s).nth(i)),
|
||||
Data::Number(n) => match position(*n) {
|
||||
Some(i) => front_docs(&s).nth(i),
|
||||
None => {
|
||||
let name = vectorcraft_js::number_to_string(*n);
|
||||
front_docs(&s).find(|d| d.title() == name)
|
||||
}
|
||||
},
|
||||
Data::String(name) => match front_docs(&s).find(|d| d.title() == *name) {
|
||||
None if !probing(a) => return Err(HostError::Error(NOT_FOUND.into())),
|
||||
found => found,
|
||||
@@ -968,10 +1124,11 @@ fn docs_by_name(h: &Host, a: &[Data]) -> Answer {
|
||||
fn docs_index(h: &Host, a: &[Data]) -> Answer {
|
||||
match arg(a, 1) {
|
||||
Data::String(_) => docs_by_name(h, a),
|
||||
Data::Number(_) => match docs_at(h, a)? {
|
||||
Data::Undefined => Err(HostError::Error(NOT_FOUND.into())),
|
||||
d => Ok(d),
|
||||
},
|
||||
Data::Number(n) => {
|
||||
let s = h.session.borrow();
|
||||
let st = position(*n).and_then(|i| front_docs(&s).nth(i)).ok_or_else(|| HostError::Error(NOT_FOUND.into()))?;
|
||||
Ok(doc_ref(h, st.uid))
|
||||
}
|
||||
_ => Err(HostError::Type("give a name or an index".into())),
|
||||
}
|
||||
}
|
||||
@@ -1157,6 +1314,22 @@ fn startup_preset(name: &str) -> Option<(Option<&'static str>, Option<&'static s
|
||||
})
|
||||
}
|
||||
|
||||
/// The `file.newPresets` fields `addDocument` gives `file.new`: those of the profile's first
|
||||
/// built-in preset with `presetSettings` over them.
|
||||
const BUILT_IN_SETTINGS: &[&str] = &[
|
||||
"width",
|
||||
"height",
|
||||
"units",
|
||||
"artboards",
|
||||
"artboardLayout",
|
||||
"bleed",
|
||||
"backgroundContents",
|
||||
"colorMode",
|
||||
"rasterEffectsPpi",
|
||||
"previewMode",
|
||||
"alignNewObjectsToPixelGrid",
|
||||
];
|
||||
|
||||
/// `documents.addDocument(startupPreset, presetSettings?, showOptionsDialog?)`: a new document from
|
||||
/// the New Document profile `startupPreset` names, with the settings `presetSettings` gives in
|
||||
/// place of the profile's.
|
||||
@@ -1203,15 +1376,25 @@ fn docs_add_document(h: &Host, a: &[Data]) -> Answer {
|
||||
Some(Data::Bool(true)) => return Err(HostError::Error(DIALOG_UNAVAILABLE.into())),
|
||||
Some(_) => return Err(HostError::Type("showOptionsDialog must be true or false".into())),
|
||||
}
|
||||
// The document starts from the first preset of the profile's category (Print: Letter).
|
||||
let first = profile.and_then(|n| crate::cmd::newdoc::category(&h.session.borrow(), n)?.into_iter().next());
|
||||
if let Some(first) = first {
|
||||
p.insert("preset".into(), json!(first.name));
|
||||
}
|
||||
p.insert("profile".into(), profile.map_or(Value::Null, |n| json!(n)));
|
||||
if let Some(m) = mode {
|
||||
p.entry("colorMode").or_insert_with(|| json!(m));
|
||||
}
|
||||
// The document starts from the first built-in preset of the profile's category (Print:
|
||||
// Letter) with `presetSettings` over it, given in full so that a saved preset of the same name
|
||||
// does not stand in for it. Settings the built-in preset refuses are an error.
|
||||
let first = profile.and_then(|n| crate::cmd::newdoc::category(&h.session.borrow(), n)?.into_iter().next());
|
||||
if let Some(first) = first {
|
||||
p.insert("preset".into(), json!(first.name));
|
||||
let full = first.with_params(&Value::Object(p.clone()), "file.new").map_err(|e| HostError::Error(e.to_string()))?;
|
||||
if let Value::Object(settings) = full.to_json() {
|
||||
for key in BUILT_IN_SETTINGS {
|
||||
if let Some(v) = settings.get(*key) {
|
||||
p.insert((*key).into(), v.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
p.insert("profile".into(), profile.map_or(Value::Null, |n| json!(n)));
|
||||
// A profile whose file could not be read throws, and the document `file.new` made with the
|
||||
// defaults is put back, with the Recent sizes as they were.
|
||||
atomically(h, |h| {
|
||||
@@ -1720,6 +1903,7 @@ fn selection_ids(h: &Host, doc: Doc, v: &Data) -> std::result::Result<Vec<NodeId
|
||||
d => vec![d],
|
||||
};
|
||||
let mut ids: Vec<NodeId> = Vec::with_capacity(list.len());
|
||||
// The ids listed so far; `ids` keeps them in the order they were first listed.
|
||||
let mut seen: HashSet<NodeId> = HashSet::with_capacity(list.len());
|
||||
// The document is read once for every object: nothing changes it while the list is checked.
|
||||
let (d, isolation, guides_locked) = with_doc(h, doc, |s, st| (st.doc.clone(), st.isolation, s.guides_locked()));
|
||||
@@ -1813,27 +1997,49 @@ fn probing(a: &[Data]) -> bool {
|
||||
matches!(arg(a, 2), Data::Bool(true))
|
||||
}
|
||||
|
||||
/// `pageItems[i]`, and `pageItems["name"]` as `getByName` reads it.
|
||||
/// The position an indexer key names when it is an array index, 0 to 2^32 - 2.
|
||||
fn position(n: f64) -> Option<usize> {
|
||||
whole(n).filter(|i| *i < u64::from(u32::MAX)).and_then(|i| usize::try_from(i).ok())
|
||||
}
|
||||
|
||||
/// `pageItems[i]`, and `pageItems["name"]` as `getByName` reads it. A key that is the text of a
|
||||
/// number but not an array index, such as `-1` or `1.5`, reaches the indexer as a number and is
|
||||
/// looked up as that name, giving `undefined` when no object has it.
|
||||
fn items_at(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = items_doc(h, a)?;
|
||||
if let Data::String(_) = arg(a, 1) {
|
||||
return match items_by_name(h, a) {
|
||||
match arg(a, 1) {
|
||||
Data::String(_) => match items_by_name(h, a) {
|
||||
Err(HostError::Error(e)) if e == NOT_FOUND && probing(a) => Ok(Data::Undefined),
|
||||
r => r,
|
||||
};
|
||||
},
|
||||
Data::Number(n) => match position(*n) {
|
||||
Some(i) => Ok(item_at(h, doc, i)),
|
||||
None => match items_named(h, doc, &vectorcraft_js::number_to_string(*n)) {
|
||||
Err(HostError::Error(e)) if e == NOT_FOUND => Ok(Data::Undefined),
|
||||
r => r,
|
||||
},
|
||||
},
|
||||
_ => Ok(Data::Undefined),
|
||||
}
|
||||
let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) };
|
||||
let Some(i) = whole(*n).and_then(|i| usize::try_from(i).ok()) else { return Ok(Data::Undefined) };
|
||||
Ok(with_doc(h, doc, |_, st| page_items(h, st).get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id))))
|
||||
}
|
||||
|
||||
/// The object at position `i` of `pageItems`, or `undefined` past the end.
|
||||
fn item_at(h: &Host, doc: Doc, i: usize) -> Data {
|
||||
with_doc(h, doc, |_, st| page_items(h, st).get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id)))
|
||||
}
|
||||
|
||||
fn items_by_name(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = items_doc(h, a)?;
|
||||
let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) };
|
||||
items_named(h, doc, name)
|
||||
}
|
||||
|
||||
/// The first object of `pageItems` named `name`, or `Not found`.
|
||||
fn items_named(h: &Host, doc: Doc, name: &str) -> Answer {
|
||||
with_doc(h, doc, |_, st| {
|
||||
let ids = page_items(h, st);
|
||||
h.charge_call(ids.len() as u64)?;
|
||||
let id = ids.iter().find(|i| st.doc.node(**i).and_then(|n| n.name.as_deref()) == Some(name.as_str()));
|
||||
let id = ids.iter().find(|i| st.doc.node(**i).and_then(|n| n.name.as_deref()) == Some(name));
|
||||
id.map(|id| item_ref(h, st, *id)).ok_or_else(|| HostError::Error(NOT_FOUND.into()))
|
||||
})
|
||||
}
|
||||
@@ -1841,10 +2047,13 @@ fn items_by_name(h: &Host, a: &[Data]) -> Answer {
|
||||
fn items_index(h: &Host, a: &[Data]) -> Answer {
|
||||
match arg(a, 1) {
|
||||
Data::String(_) => items_by_name(h, a),
|
||||
Data::Number(_) => match items_at(h, a)? {
|
||||
Data::Undefined => Err(HostError::Error(NOT_FOUND.into())),
|
||||
d => Ok(d),
|
||||
},
|
||||
Data::Number(n) => {
|
||||
let doc = items_doc(h, a)?;
|
||||
match position(*n).map(|i| item_at(h, doc, i)) {
|
||||
None | Some(Data::Undefined) => Err(HostError::Error(NOT_FOUND.into())),
|
||||
Some(d) => Ok(d),
|
||||
}
|
||||
}
|
||||
_ => Err(HostError::Type("give a name or an index".into())),
|
||||
}
|
||||
}
|
||||
@@ -1931,6 +2140,7 @@ fn text_arg(v: &Data, what: &str) -> std::result::Result<String, HostError> {
|
||||
|
||||
/// `name = value`: a number or a Boolean becomes the text `String(value)` gives.
|
||||
fn item_set_name(h: &Host, a: &[Data]) -> Answer {
|
||||
this_item(h, a)?;
|
||||
let name = &text_arg(arg(a, 1), "name")?;
|
||||
if name.len() > MAX_TEXT_BYTES {
|
||||
return Err(HostError::Range("the name is too long".into()));
|
||||
@@ -1949,11 +2159,11 @@ fn item_note(h: &Host, a: &[Data]) -> Answer {
|
||||
/// `note = text`: the Attributes panel's note, set with `attributes.set`, which trims it. A number
|
||||
/// or a Boolean becomes the text `String(value)` gives.
|
||||
fn item_set_note(h: &Host, a: &[Data]) -> Answer {
|
||||
let item = this_item(h, a)?;
|
||||
let note = &text_arg(arg(a, 1), "note")?;
|
||||
if note.len() > MAX_TEXT_BYTES {
|
||||
return Err(HostError::Range("the note is too long".into()));
|
||||
}
|
||||
let item = this_item(h, a)?;
|
||||
let same = with_doc(h, item.doc, |_, st| st.doc.node(item.id).is_some_and(|n| note_of(n) == note.trim()));
|
||||
if !same {
|
||||
edit_item(h, item, "attributes.set", &json!({"ids": [item.id.0], "note": note}))?;
|
||||
@@ -1987,8 +2197,9 @@ fn item_hidden(h: &Host, a: &[Data]) -> Answer {
|
||||
}
|
||||
|
||||
fn item_set_hidden(h: &Host, a: &[Data]) -> Answer {
|
||||
let item = this_item(h, a)?;
|
||||
let hidden = boolean(arg(a, 1), "hidden")?;
|
||||
refuse_protected_edit(h, this_item(h, a)?)?;
|
||||
refuse_protected_edit(h, item)?;
|
||||
set_props(h, a, |n| n.visible != hidden, json!({"visible": !hidden}))
|
||||
}
|
||||
|
||||
@@ -1997,8 +2208,9 @@ fn item_locked(h: &Host, a: &[Data]) -> Answer {
|
||||
}
|
||||
|
||||
fn item_set_locked(h: &Host, a: &[Data]) -> Answer {
|
||||
let item = this_item(h, a)?;
|
||||
let locked = boolean(arg(a, 1), "locked")?;
|
||||
refuse_protected_edit(h, this_item(h, a)?)?;
|
||||
refuse_protected_edit(h, item)?;
|
||||
set_props(h, a, |n| n.locked == locked, json!({"locked": locked}))
|
||||
}
|
||||
|
||||
@@ -2007,6 +2219,7 @@ fn item_opacity(h: &Host, a: &[Data]) -> Answer {
|
||||
}
|
||||
|
||||
fn item_set_opacity(h: &Host, a: &[Data]) -> Answer {
|
||||
let item = this_item(h, a)?;
|
||||
let v = number(arg(a, 1), "opacity")?;
|
||||
if !(0.0..=100.0).contains(&v) {
|
||||
return Err(HostError::Range("opacity must be from 0 to 100".into()));
|
||||
@@ -2016,7 +2229,6 @@ fn item_set_opacity(h: &Host, a: &[Data]) -> Answer {
|
||||
// replaces the one the graph keeps for its series or kind.
|
||||
// The opacity the item already has may be assigned while its layer is hidden or locked, unless
|
||||
// it would still replace the opacity a graph keeps for the item's series or kind.
|
||||
let item = this_item(h, a)?;
|
||||
let (now, keeps_other) = with_doc(h, item.doc, |_, st| {
|
||||
let d = &st.doc;
|
||||
// Only the exact number the getter reports counts as the same opacity.
|
||||
@@ -2031,6 +2243,56 @@ fn item_set_opacity(h: &Host, a: &[Data]) -> Answer {
|
||||
set_props(h, a, |_| false, json!({"opacity": now.unwrap_or(v)}))
|
||||
}
|
||||
|
||||
/// The members of `BlendModes` with the blend mode each one names.
|
||||
const BLEND_MODES: [(&str, BlendMode); 16] = [
|
||||
("COLORBLEND", BlendMode::Color),
|
||||
("COLORBURN", BlendMode::ColorBurn),
|
||||
("COLORDODGE", BlendMode::ColorDodge),
|
||||
("DARKEN", BlendMode::Darken),
|
||||
("DIFFERENCE", BlendMode::Difference),
|
||||
("EXCLUSION", BlendMode::Exclusion),
|
||||
("HARDLIGHT", BlendMode::HardLight),
|
||||
("HUE", BlendMode::Hue),
|
||||
("LIGHTEN", BlendMode::Lighten),
|
||||
("LUMINOSITY", BlendMode::Luminosity),
|
||||
("MULTIPLY", BlendMode::Multiply),
|
||||
("NORMAL", BlendMode::Normal),
|
||||
("OVERLAY", BlendMode::Overlay),
|
||||
("SATURATIONBLEND", BlendMode::Saturation),
|
||||
("SCREEN", BlendMode::Screen),
|
||||
("SOFTLIGHT", BlendMode::SoftLight),
|
||||
];
|
||||
|
||||
fn item_blending_mode(h: &Host, a: &[Data]) -> Answer {
|
||||
read_item(h, a, |_, n| {
|
||||
let name = BLEND_MODES.iter().find(|(_, m)| *m == n.blend).map_or("NORMAL", |(name, _)| name);
|
||||
Ok(text(format!("BlendModes.{name}")))
|
||||
})
|
||||
}
|
||||
|
||||
/// `blendingMode = BlendModes.<MODE>`: the object's own blend mode, as `object.setProps` sets it.
|
||||
/// The mode the object already has may be assigned while its layer is hidden or locked, unless it
|
||||
/// would still replace the blend mode a graph keeps for the item's series or kind.
|
||||
fn item_set_blending_mode(h: &Host, a: &[Data]) -> Answer {
|
||||
let item = this_item(h, a)?;
|
||||
let mode = match arg(a, 1) {
|
||||
Data::String(s) => s.strip_prefix("BlendModes.").and_then(|m| BLEND_MODES.iter().find(|(name, _)| *name == m)).map(|(_, mode)| *mode),
|
||||
_ => None,
|
||||
};
|
||||
let mode = mode.ok_or_else(|| HostError::Type("blendingMode needs a BlendModes value".into()))?;
|
||||
let (same, keeps_other) = with_doc(h, item.doc, |_, st| {
|
||||
let d = &st.doc;
|
||||
let same = d.node(item.id).is_some_and(|n| n.blend == mode);
|
||||
let keeps_other =
|
||||
crate::cmd::graph::series_object_opacity_differs(d, &[item.id]) || crate::cmd::graph::label_object_opacity_differs(d, &[item.id]);
|
||||
(same, keeps_other)
|
||||
});
|
||||
if !same || keeps_other {
|
||||
refuse_protected_edit(h, item)?;
|
||||
}
|
||||
set_props(h, a, |_| false, json!({"blend": mode.label()}))
|
||||
}
|
||||
|
||||
fn item_selected(h: &Host, a: &[Data]) -> Answer {
|
||||
let item = this_item(h, a)?;
|
||||
Ok(Data::Bool(with_doc(h, item.doc, |_, st| st.selection.objects.contains(&item.id))))
|
||||
@@ -2144,16 +2406,19 @@ fn move_to(h: &Host, a: &[Data], x: Option<f64>, y: Option<f64>) -> Answer {
|
||||
}
|
||||
|
||||
fn item_set_position(h: &Host, a: &[Data]) -> Answer {
|
||||
this_item(h, a)?;
|
||||
let p = point(arg(a, 1), "position")?;
|
||||
move_to(h, a, Some(p[0]), Some(p[1]))
|
||||
}
|
||||
|
||||
fn item_set_left(h: &Host, a: &[Data]) -> Answer {
|
||||
this_item(h, a)?;
|
||||
let x = coordinate(arg(a, 1), "left")?;
|
||||
move_to(h, a, Some(x), None)
|
||||
}
|
||||
|
||||
fn item_set_top(h: &Host, a: &[Data]) -> Answer {
|
||||
this_item(h, a)?;
|
||||
let y = coordinate(arg(a, 1), "top")?;
|
||||
move_to(h, a, None, Some(y))
|
||||
}
|
||||
@@ -2162,12 +2427,12 @@ fn item_set_top(h: &Host, a: &[Data]) -> Answer {
|
||||
/// or tall, so the page-aligned bounds that `width` and `height` read have that size, rotated
|
||||
/// objects included.
|
||||
fn resize(h: &Host, a: &[Data], width: bool) -> Answer {
|
||||
let item = this_item(h, a)?;
|
||||
let what = if width { "width" } else { "height" };
|
||||
let size = number(arg(a, 1), what)?;
|
||||
if size <= 0.0 || size > MAX_SIZE {
|
||||
return Err(HostError::Range(format!("{what} must be more than 0 and at most 3999856 points")));
|
||||
}
|
||||
let item = this_item(h, a)?;
|
||||
refuse_protected_edit(h, item)?;
|
||||
selection_ids(h, item.doc, arg(a, 0))?;
|
||||
let (Some(r), _) = item_rect(h, item, false)? else { return Ok(Data::Undefined) };
|
||||
@@ -2227,7 +2492,7 @@ fn item_remove(h: &Host, a: &[Data]) -> Answer {
|
||||
}
|
||||
|
||||
/// The error of `remove()` and `removeAll()` for an object on a locked artboard.
|
||||
const ON_LOCKED_ARTBOARD: &str = "cannot delete objects on a locked artboard";
|
||||
pub(super) const ON_LOCKED_ARTBOARD: &str = "cannot delete objects on a locked artboard";
|
||||
|
||||
/// The error of `move` and `duplicate` given an object of another document.
|
||||
pub const CROSS_DOCUMENT: &str = "Cross-document placement is not available";
|
||||
@@ -2546,11 +2811,15 @@ const ENUMS: &[(&str, &[&str])] = &[
|
||||
/// Adds `app`, its classes and the enumerations to `realm`; their members act for the run `link`
|
||||
/// holds.
|
||||
pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), RunError> {
|
||||
text::install_enums(realm)?;
|
||||
for (name, members) in ENUMS {
|
||||
let items = members.iter().map(|m| (m.to_string(), HostItem::Value(text(format!("{name}.{m}"))))).collect();
|
||||
realm.define_host_object(name, items)?;
|
||||
}
|
||||
let blend_modes = BLEND_MODES.iter().map(|(m, _)| (m.to_string(), HostItem::Value(text(format!("BlendModes.{m}"))))).collect();
|
||||
realm.define_host_object("BlendModes", blend_modes)?;
|
||||
variables::define_enums(realm)?;
|
||||
paths::install_enums(realm)?;
|
||||
realm.define_host_classes(classes(link), vec![("app".into(), host_ref("Application", &[]))])?;
|
||||
let l = link;
|
||||
// The application's members a script may name without `app.`, assigned as `app.<member>` is.
|
||||
@@ -2573,10 +2842,14 @@ fn classes(link: &Link) -> Vec<HostClass> {
|
||||
("coordinateSystem", property(l, app_coords, app_set_coords), typed("CoordinateSystem")),
|
||||
("getIsFileOpen", method(l, app_is_open), returns("boolean", &[("filePath", "string")])),
|
||||
("redraw", method(l, app_redraw), returns("undefined", &[])),
|
||||
("undo", method(l, app_undo), returns("undefined", &[])),
|
||||
("redo", method(l, app_redo), returns("undefined", &[])),
|
||||
("executeMenuCommand", method(l, app_menu_command), returns("undefined", &[("menuCommandString", "string")])),
|
||||
("toString", class_text("Application"), returns("string", &[])),
|
||||
]);
|
||||
application.push(("textFonts".into(), text::app_text_fonts(l), MemberInfo { collection: true, ..typed("TextFonts") }));
|
||||
application.push(later(l, "Application", "beep"));
|
||||
application.extend(super::actions::app_members(l));
|
||||
let preset = {
|
||||
let l = link.clone();
|
||||
let f: HostFunction = Rc::new(move |_: Vec<Data>| {
|
||||
@@ -2644,14 +2917,17 @@ fn classes(link: &Link) -> Vec<HostClass> {
|
||||
returns("Array", &[("point", "Array"), ("source", "CoordinateSystem"), ("destination", "CoordinateSystem")]),
|
||||
),
|
||||
("pageItems", get(l, doc_page_items), MemberInfo { collection: true, ..typed("PageItems") }),
|
||||
("pathItems", get(l, paths::doc_path_items), MemberInfo { collection: true, ..typed("PathItems") }),
|
||||
("textFrames", text::doc_text_frames(l), MemberInfo { collection: true, ..typed("TextFrames") }),
|
||||
("stories", text::threads::doc_stories(l), MemberInfo { collection: true, ..typed("Stories") }),
|
||||
("selection", property(l, doc_selection, doc_set_selection), typed("*")),
|
||||
("views", get(l, doc_views), MemberInfo { collection: true, ..typed("Views") }),
|
||||
("toString", method(l, doc_to_string), returns("string", &[])),
|
||||
]);
|
||||
document.extend(defaults::document_members(l));
|
||||
document.extend(text::styles::doc_members(l));
|
||||
document.extend(
|
||||
["layers", "artboards", "pathItems", "groupItems", "textFrames", "swatches", "symbols", "activeLayer", "saveAs", "close"]
|
||||
.into_iter()
|
||||
.map(|m| later(l, "Document", m)),
|
||||
["layers", "artboards", "groupItems", "swatches", "symbols", "activeLayer", "saveAs", "close"].into_iter().map(|m| later(l, "Document", m)),
|
||||
);
|
||||
document.extend(variables::document_members(l));
|
||||
document.push(("tags".into(), get(l, tags::doc_tags), MemberInfo { collection: true, ..typed("Tags") }));
|
||||
@@ -2706,6 +2982,7 @@ fn classes(link: &Link) -> Vec<HostClass> {
|
||||
("locked", property(l, item_locked, item_set_locked), typed("boolean")),
|
||||
("selected", property(l, item_selected, item_set_selected), typed("boolean")),
|
||||
("opacity", property(l, item_opacity, item_set_opacity), MemberInfo { min: Some(0.0), max: Some(100.0), ..typed("number") }),
|
||||
("blendingMode", property(l, item_blending_mode, item_set_blending_mode), typed("BlendModes")),
|
||||
("position", property(l, item_position, item_set_position), typed("Array")),
|
||||
("left", property(l, item_left, item_set_left), typed("number")),
|
||||
("top", property(l, item_top, item_set_top), typed("number")),
|
||||
@@ -2731,7 +3008,6 @@ fn classes(link: &Link) -> Vec<HostClass> {
|
||||
page_item.extend(
|
||||
[
|
||||
"artworkKnockout",
|
||||
"blendingMode",
|
||||
"isIsolated",
|
||||
"layer",
|
||||
"pixelAligned",
|
||||
@@ -2752,7 +3028,16 @@ fn classes(link: &Link) -> Vec<HostClass> {
|
||||
);
|
||||
page_item.extend(variables::page_item_members(l));
|
||||
classes.push(class("PageItem", None, page_item, None));
|
||||
classes.extend(ITEM_CLASSES.iter().map(|c| class(c, Some("PageItem"), variables::item_members(l, c), None)));
|
||||
classes.extend(ITEM_CLASSES.iter().filter(|c| **c != "TextFrame").map(|c| {
|
||||
let mut members = variables::item_members(l, c);
|
||||
if *c == "PathItem" {
|
||||
members.extend(paths::path_item_members(l));
|
||||
}
|
||||
class(c, Some("PageItem"), members, None)
|
||||
}));
|
||||
classes.extend(paths::classes(l));
|
||||
classes.extend(colors::classes(l));
|
||||
classes.extend(text::classes(l));
|
||||
classes.extend(variables::classes(l));
|
||||
classes.push(class(
|
||||
"Layer",
|
||||
|
||||
@@ -0,0 +1,189 @@
|
||||
//! The color classes of the script object model, as the help pages
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/RGBColor/>,
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/CMYKColor/>,
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/GrayColor/>,
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/LabColor/> and
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/NoColor/> describe them.
|
||||
//!
|
||||
//! A color is plain data: `new RGBColor()` gives an object with `typename` and its components,
|
||||
//! which the script can change, and reading `fillColor` or `strokeColor` gives a new one each time.
|
||||
//! Components are checked when a color is assigned to an object, and a value out of range throws a
|
||||
//! `RangeError` with nothing changed.
|
||||
//!
|
||||
//! VectorCraft's own rules, which the help pages do not state: components left out count as 0;
|
||||
//! `new cmykColor()` is the same as `new CMYKColor()`; `LabColor.l` is 0 to 100 and `a` and `b`
|
||||
//! are -128 to 128. `GrayColor.gray` runs from 0 (black) to 100 (white), as the GrayColor page
|
||||
//! says. `GradientColor`, `SpotColor` and `PatternColor` can be read from an object but not
|
||||
//! assigned yet.
|
||||
|
||||
use std::rc::Rc;
|
||||
|
||||
use serde_json::Value;
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_js::{Data, HostClass, HostError, HostFunction};
|
||||
|
||||
use super::{Link, current, num, text};
|
||||
|
||||
/// The classes whose objects can be read from a fill or stroke but not assigned yet.
|
||||
const LATER: &[&str] = &["GradientColor", "SpotColor", "PatternColor"];
|
||||
|
||||
/// The components of each color class, with the value `new` gives them.
|
||||
const CLASSES: &[(&str, &[&str])] = &[
|
||||
("RGBColor", &["red", "green", "blue"]),
|
||||
("CMYKColor", &["cyan", "magenta", "yellow", "black"]),
|
||||
("GrayColor", &["gray"]),
|
||||
("LabColor", &["l", "a", "b"]),
|
||||
("NoColor", &[]),
|
||||
("GradientColor", &[]),
|
||||
("SpotColor", &["tint"]),
|
||||
("PatternColor", &[]),
|
||||
];
|
||||
|
||||
fn color_object(class: &str, values: &[(&str, f64)]) -> Data {
|
||||
let mut items = vec![("typename".to_string(), text(class))];
|
||||
items.extend(values.iter().map(|(k, v)| ((*k).to_string(), num(*v))));
|
||||
Data::Object(items)
|
||||
}
|
||||
|
||||
/// A component as the script sees it: `exact` rounded to the fewest decimals, from 4 to 9, that
|
||||
/// `back` turns into the stored `v` again, else `exact` itself, so that assigning a color read
|
||||
/// from an object gives that object the same color.
|
||||
fn shown_as(exact: f64, v: f32, back: impl Fn(f64) -> f32) -> f64 {
|
||||
let mut scale = 1e4;
|
||||
for _ in 4..=9 {
|
||||
let r = (exact * scale).round() / scale;
|
||||
if back(r) == v {
|
||||
return r;
|
||||
}
|
||||
scale *= 10.0;
|
||||
}
|
||||
exact
|
||||
}
|
||||
|
||||
/// A component stored as `v`, from 0 to 1, that the script sees times `scale`.
|
||||
fn shown(v: f32, scale: f64) -> f64 {
|
||||
shown_as(f64::from(v) * scale, v, |r| unit(r, scale))
|
||||
}
|
||||
|
||||
/// The color object for a solid color.
|
||||
fn of_color(c: &Color) -> Data {
|
||||
match *c {
|
||||
Color::Rgb { r, g, b } => color_object("RGBColor", &[("red", shown(r, 255.0)), ("green", shown(g, 255.0)), ("blue", shown(b, 255.0))]),
|
||||
Color::Cmyk { c, m, y, k } => color_object(
|
||||
"CMYKColor",
|
||||
&[("cyan", shown(c, 100.0)), ("magenta", shown(m, 100.0)), ("yellow", shown(y, 100.0)), ("black", shown(k, 100.0))],
|
||||
),
|
||||
Color::Gray { k } => color_object("GrayColor", &[("gray", shown_as((1.0 - f64::from(k)) * 100.0, k, |g| unit(100.0 - g, 100.0)))]),
|
||||
Color::Lab { l, a, b } => color_object("LabColor", &[("l", shown(l, 1.0)), ("a", shown(a, 1.0)), ("b", shown(b, 1.0))]),
|
||||
}
|
||||
}
|
||||
|
||||
/// What reading `fillColor` or `strokeColor` gives for `paint`: a new color object, a `SpotColor`
|
||||
/// with its `tint` for a color linked to a global or spot swatch.
|
||||
pub(super) fn of_paint(paint: &Paint) -> Data {
|
||||
match paint {
|
||||
Paint::None => color_object("NoColor", &[]),
|
||||
Paint::Solid { swatch: Some(_), tint, .. } => color_object("SpotColor", &[("tint", shown(*tint, 100.0))]),
|
||||
Paint::Solid { color, .. } => of_color(color),
|
||||
Paint::Gradient(_) => color_object("GradientColor", &[]),
|
||||
Paint::Pattern { .. } => color_object("PatternColor", &[]),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether assigning the color object `d`, read as `assigned`, leaves the paint `now` as it is: a
|
||||
/// `NoColor` on no paint, or on an unlinked color either a color equal to it once `store` makes
|
||||
/// it what the document stores, or the components reading `now` gives (a Gray value read back can
|
||||
/// stand for an ink amount that no Gray value names exactly).
|
||||
pub(super) fn unchanged(d: &Data, assigned: Option<Color>, now: &Paint, store: impl FnOnce(Color) -> Color) -> bool {
|
||||
match (assigned, now) {
|
||||
(None, Paint::None) => true,
|
||||
(Some(c), Paint::Solid { color, swatch: None, .. }) => store(c) == *color || shows(d, &of_color(color)),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the color object `d` has the class and every component of `shown`.
|
||||
fn shows(d: &Data, shown: &Data) -> bool {
|
||||
let (Data::Object(a), Data::Object(b)) = (d, shown) else { return false };
|
||||
b.iter().all(|(k, v)| a.iter().any(|(n, w)| n == k && w == v))
|
||||
}
|
||||
|
||||
/// The component `key` of color object `o`, from `min` to `max` (0 when it is left out).
|
||||
fn component(o: &[(String, Data)], class: &str, key: &str, min: f64, max: f64) -> std::result::Result<f64, HostError> {
|
||||
match o.iter().find(|(k, _)| k == key).map(|(_, v)| v) {
|
||||
None | Some(Data::Undefined) => Ok(0.0),
|
||||
Some(Data::Number(n)) if n.is_finite() && (min..=max).contains(n) => Ok(*n),
|
||||
Some(Data::Number(_)) => Err(HostError::Range(format!("{class}.{key} must be from {min} to {max}"))),
|
||||
Some(_) => Err(HostError::Type(format!("{class}.{key} must be a number"))),
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::cast_possible_truncation)]
|
||||
fn unit(v: f64, scale: f64) -> f32 {
|
||||
(v / scale) as f32
|
||||
}
|
||||
|
||||
/// The color a script assigned, checked: `None` for a `NoColor`. `what` names the property.
|
||||
pub(super) fn assigned(d: &Data, what: &str) -> std::result::Result<Option<Color>, HostError> {
|
||||
let Data::Object(o) = d else { return Err(HostError::Type(format!("{what} must be a color object"))) };
|
||||
let class = match o.iter().find(|(k, _)| k == "typename").map(|(_, v)| v) {
|
||||
Some(Data::String(s)) => s.as_str(),
|
||||
_ => return Err(HostError::Type(format!("{what} must be a color object"))),
|
||||
};
|
||||
let c = |key: &str, min: f64, max: f64| component(o, class, key, min, max);
|
||||
Ok(Some(match class {
|
||||
"NoColor" => return Ok(None),
|
||||
"RGBColor" => {
|
||||
Color::Rgb { r: unit(c("red", 0.0, 255.0)?, 255.0), g: unit(c("green", 0.0, 255.0)?, 255.0), b: unit(c("blue", 0.0, 255.0)?, 255.0) }
|
||||
}
|
||||
"CMYKColor" => Color::Cmyk {
|
||||
c: unit(c("cyan", 0.0, 100.0)?, 100.0),
|
||||
m: unit(c("magenta", 0.0, 100.0)?, 100.0),
|
||||
y: unit(c("yellow", 0.0, 100.0)?, 100.0),
|
||||
k: unit(c("black", 0.0, 100.0)?, 100.0),
|
||||
},
|
||||
"GrayColor" => Color::Gray { k: unit(100.0 - c("gray", 0.0, 100.0)?, 100.0) },
|
||||
"LabColor" => Color::Lab { l: unit(c("l", 0.0, 100.0)?, 1.0), a: unit(c("a", -128.0, 128.0)?, 1.0), b: unit(c("b", -128.0, 128.0)?, 1.0) },
|
||||
l if LATER.contains(&l) => return Err(HostError::Error(format!("assigning a {l} is not available yet"))),
|
||||
_ => return Err(HostError::Type(format!("{what} must be a color object"))),
|
||||
}))
|
||||
}
|
||||
|
||||
/// `color` as `paint.setFill` and `paint.setStroke` take it.
|
||||
pub(super) fn param(color: &Color) -> Value {
|
||||
serde_json::to_value(color).unwrap_or(Value::Null)
|
||||
}
|
||||
|
||||
/// The constructors of the color classes, and `cmykColor`.
|
||||
pub(super) fn classes(link: &Link) -> Vec<HostClass> {
|
||||
let make = |name: &str, components: &'static [&'static str]| {
|
||||
let l = link.clone();
|
||||
let class = name.to_string();
|
||||
let f: HostFunction = Rc::new(move |_| {
|
||||
current(&l)?.charge_call(64)?;
|
||||
let zeros: Vec<(&str, f64)> = components.iter().map(|k| (*k, if *k == "tint" { 100.0 } else { 0.0 })).collect();
|
||||
Ok(color_object(&class, &zeros))
|
||||
});
|
||||
f
|
||||
};
|
||||
let mut out: Vec<HostClass> = CLASSES
|
||||
.iter()
|
||||
.map(|(name, components)| HostClass {
|
||||
name: (*name).into(),
|
||||
parent: None,
|
||||
members: Vec::new(),
|
||||
info: Vec::new(),
|
||||
index: None,
|
||||
construct: Some(make(name, components)),
|
||||
})
|
||||
.collect();
|
||||
out.push(HostClass {
|
||||
name: "cmykColor".into(),
|
||||
parent: None,
|
||||
members: Vec::new(),
|
||||
info: Vec::new(),
|
||||
index: None,
|
||||
construct: Some(make("CMYKColor", CLASSES[1].1)),
|
||||
});
|
||||
out
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
//! A document's default fill and stroke in the script object model, the `Document` members whose
|
||||
//! names start with `default` that the help page
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/Document/> describes, and `scaleFactor`.
|
||||
//!
|
||||
//! The defaults are what the next object drawn gets ([`crate::Session::new_art`]), the same for
|
||||
//! every open document, as the help page says of these global settings. Reading one reads new
|
||||
//! art's top fill or stroke, and assigning one runs `appearance.setNewArt`, which leaves the
|
||||
//! selection, its art, the active proxy and the recent colors as they were. A value that changes
|
||||
//! nothing runs no command, and a bad value throws an error with nothing changed.
|
||||
//!
|
||||
//! VectorCraft's own rules, which the help page does not state:
|
||||
//! - A color is new art's fill or stroke itself: assigning a color also makes `defaultFilled` or
|
||||
//! `defaultStroked` true, and assigning a `NoColor` makes it false. `defaultFilled` or
|
||||
//! `defaultStroked` set to true with no default fill or stroke gives black.
|
||||
//! - An RGB color is stored in the color mode of the document in front, as `paint.setFill` stores
|
||||
//! it.
|
||||
//! - `defaultStrokeWidth` is 0 to 1000 points, a dash or gap 0 to 1,000,000 points (at most 64 of
|
||||
//! them, not all 0), and `defaultStrokeDashOffset` -1,000,000 to 1,000,000 points, which needs a
|
||||
//! dash pattern unless it is 0.
|
||||
//! - While New Art Has Basic Appearance is off and an object is selected, assigning a default
|
||||
//! throws an error, since new art then takes that object's appearance.
|
||||
//! - `scaleFactor` is 1: VectorCraft draws every document at its own size.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, LineCap, LineJoin};
|
||||
use vectorcraft_js::{Data, HostError, MemberInfo};
|
||||
|
||||
use super::paths::{CAPS, JOINS, MAX_STROKE_WIDTH, dash_lengths};
|
||||
use super::{Answer, Described, Host, Link, arg, boolean, colors, command, get, named, num, number, property, this_doc, typed};
|
||||
|
||||
/// New art's appearance, after the check that the document `this` names is still open.
|
||||
fn new_art(h: &Host, a: &[Data]) -> std::result::Result<Appearance, HostError> {
|
||||
this_doc(h, a)?;
|
||||
Ok(h.session.borrow().new_art())
|
||||
}
|
||||
|
||||
/// Runs `appearance.setNewArt` with `params`, unless `same`.
|
||||
fn set(h: &Host, same: bool, params: Value) -> Answer {
|
||||
if !same {
|
||||
command(h, "appearance.setNewArt", ¶ms)?;
|
||||
}
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
fn top_paint(ap: &Appearance, fill: bool) -> Paint {
|
||||
if fill { ap.fill_paint() } else { ap.stroke_paint() }
|
||||
}
|
||||
|
||||
fn default_color(h: &Host, a: &[Data], fill: bool) -> Answer {
|
||||
Ok(colors::of_paint(&top_paint(&new_art(h, a)?, fill)))
|
||||
}
|
||||
|
||||
fn set_default_color(h: &Host, a: &[Data], fill: bool) -> Answer {
|
||||
let what = if fill { "defaultFillColor" } else { "defaultStrokeColor" };
|
||||
let color = colors::assigned(arg(a, 1), what)?;
|
||||
let now = top_paint(&new_art(h, a)?, fill);
|
||||
let same = colors::unchanged(arg(a, 1), color, &now, |c| crate::cmd::newart::stored_color(&h.session.borrow(), c));
|
||||
let paint = match color {
|
||||
Some(c) => json!({"color": colors::param(&c)}),
|
||||
None => json!({"none": true}),
|
||||
};
|
||||
let key = if fill { "fill" } else { "stroke" };
|
||||
set(h, same, json!({ key: paint }))
|
||||
}
|
||||
|
||||
fn default_painted(h: &Host, a: &[Data], fill: bool) -> Answer {
|
||||
Ok(Data::Bool(!top_paint(&new_art(h, a)?, fill).is_none()))
|
||||
}
|
||||
|
||||
fn set_default_painted(h: &Host, a: &[Data], fill: bool) -> Answer {
|
||||
let on = boolean(arg(a, 1), if fill { "defaultFilled" } else { "defaultStroked" })?;
|
||||
let now = !top_paint(&new_art(h, a)?, fill).is_none();
|
||||
let paint = if on { json!({"color": colors::param(&Color::BLACK)}) } else { json!({"none": true}) };
|
||||
let key = if fill { "fill" } else { "stroke" };
|
||||
set(h, now == on, json!({ key: paint }))
|
||||
}
|
||||
|
||||
fn default_overprint(h: &Host, a: &[Data], fill: bool) -> Answer {
|
||||
let ap = new_art(h, a)?;
|
||||
Ok(Data::Bool(if fill { ap.fill().is_some_and(|f| f.overprint) } else { ap.stroke().is_some_and(|s| s.overprint) }))
|
||||
}
|
||||
|
||||
fn set_default_overprint(h: &Host, a: &[Data], fill: bool) -> Answer {
|
||||
let (key, what) = if fill { ("fillOverprint", "defaultFillOverprint") } else { ("strokeOverprint", "defaultStrokeOverprint") };
|
||||
let on = boolean(arg(a, 1), what)?;
|
||||
let now = default_overprint(h, a, fill)? == Data::Bool(on);
|
||||
set(h, now, json!({ key: on }))
|
||||
}
|
||||
|
||||
/// New art's top stroke option `f` reads, or `none` when new art has no stroke.
|
||||
fn stroke_option<T>(h: &Host, a: &[Data], none: T, f: impl FnOnce(&vectorcraft_doc::StrokeLayer) -> T) -> std::result::Result<T, HostError> {
|
||||
Ok(new_art(h, a)?.stroke().map_or(none, f))
|
||||
}
|
||||
|
||||
fn default_stroke_width(h: &Host, a: &[Data]) -> Answer {
|
||||
this_doc(h, a)?;
|
||||
Ok(num(h.session.borrow().paint.stroke_width))
|
||||
}
|
||||
|
||||
fn set_default_stroke_width(h: &Host, a: &[Data]) -> Answer {
|
||||
let w = number(arg(a, 1), "defaultStrokeWidth")?;
|
||||
if !(0.0..=MAX_STROKE_WIDTH).contains(&w) {
|
||||
return Err(HostError::Range("defaultStrokeWidth must be from 0 to 1000 points".into()));
|
||||
}
|
||||
this_doc(h, a)?;
|
||||
let now = h.session.borrow().paint.stroke_width;
|
||||
set(h, now == w, json!({"weight": w}))
|
||||
}
|
||||
|
||||
fn default_cap(h: &Host, a: &[Data]) -> Answer {
|
||||
let cap = stroke_option(h, a, LineCap::default(), |s| s.cap)?;
|
||||
Ok(Data::String(CAPS.iter().find(|c| c.0 == cap).map_or("StrokeCap.BUTTENDCAP", |c| c.1).into()))
|
||||
}
|
||||
|
||||
fn set_default_cap(h: &Host, a: &[Data]) -> Answer {
|
||||
let found = match arg(a, 1) {
|
||||
Data::String(s) => CAPS.iter().find(|c| c.1 == s),
|
||||
_ => None,
|
||||
};
|
||||
let Some(&(cap, _, name)) = found else { return Err(HostError::Type("defaultStrokeCap must be a StrokeCap value".into())) };
|
||||
let now = stroke_option(h, a, LineCap::default(), |s| s.cap)?;
|
||||
set(h, now == cap, json!({"cap": name}))
|
||||
}
|
||||
|
||||
fn default_join(h: &Host, a: &[Data]) -> Answer {
|
||||
let join = stroke_option(h, a, LineJoin::default(), |s| s.join)?;
|
||||
Ok(Data::String(JOINS.iter().find(|j| j.0 == join).map_or("StrokeJoin.MITERENDJOIN", |j| j.1).into()))
|
||||
}
|
||||
|
||||
fn set_default_join(h: &Host, a: &[Data]) -> Answer {
|
||||
let found = match arg(a, 1) {
|
||||
Data::String(s) => JOINS.iter().find(|j| j.1 == s),
|
||||
_ => None,
|
||||
};
|
||||
let Some(&(join, _, name)) = found else { return Err(HostError::Type("defaultStrokeJoin must be a StrokeJoin value".into())) };
|
||||
let now = stroke_option(h, a, LineJoin::default(), |s| s.join)?;
|
||||
set(h, now == join, json!({"join": name}))
|
||||
}
|
||||
|
||||
fn default_miter(h: &Host, a: &[Data]) -> Answer {
|
||||
Ok(num(stroke_option(h, a, 10.0, |s| s.miter_limit)?))
|
||||
}
|
||||
|
||||
fn set_default_miter(h: &Host, a: &[Data]) -> Answer {
|
||||
let v = number(arg(a, 1), "defaultStrokeMiterLimit")?;
|
||||
if !(1.0..=500.0).contains(&v) {
|
||||
return Err(HostError::Range("defaultStrokeMiterLimit must be from 1 to 500".into()));
|
||||
}
|
||||
let now = stroke_option(h, a, 10.0, |s| s.miter_limit)?;
|
||||
set(h, now == v, json!({"miterLimit": v}))
|
||||
}
|
||||
|
||||
fn dashes(h: &Host, a: &[Data]) -> std::result::Result<Vec<f64>, HostError> {
|
||||
stroke_option(h, a, Vec::new(), |s| s.dash.as_ref().map_or_else(Vec::new, |d| d.pattern.clone()))
|
||||
}
|
||||
|
||||
fn default_dashes(h: &Host, a: &[Data]) -> Answer {
|
||||
Ok(Data::Array(dashes(h, a)?.into_iter().map(num).collect()))
|
||||
}
|
||||
|
||||
fn set_default_dashes(h: &Host, a: &[Data]) -> Answer {
|
||||
let lengths = dash_lengths(arg(a, 1), "defaultStrokeDashes")?;
|
||||
let now = dashes(h, a)?;
|
||||
let dash = if lengths.is_empty() { Value::Null } else { json!(lengths) };
|
||||
set(h, now == lengths, json!({"dash": dash}))
|
||||
}
|
||||
|
||||
fn default_dash_offset(h: &Host, a: &[Data]) -> Answer {
|
||||
Ok(num(stroke_option(h, a, 0.0, |s| s.dash.as_ref().map_or(0.0, |d| d.offset))?))
|
||||
}
|
||||
|
||||
fn set_default_dash_offset(h: &Host, a: &[Data]) -> Answer {
|
||||
let v = number(arg(a, 1), "defaultStrokeDashOffset")?;
|
||||
if v.abs() > MAX_STROKE_WIDTH * 1000.0 {
|
||||
return Err(HostError::Range("defaultStrokeDashOffset must be from -1000000 to 1000000 points".into()));
|
||||
}
|
||||
if dashes(h, a)?.is_empty() && v != 0.0 {
|
||||
return Err(HostError::Error("defaultStrokeDashOffset needs defaultStrokeDashes first".into()));
|
||||
}
|
||||
let now = stroke_option(h, a, 0.0, |s| s.dash.as_ref().map_or(0.0, |d| d.offset))?;
|
||||
set(h, now == v, json!({"dashOffset": v}))
|
||||
}
|
||||
|
||||
fn scale_factor(h: &Host, a: &[Data]) -> Answer {
|
||||
this_doc(h, a)?;
|
||||
Ok(num(1.0))
|
||||
}
|
||||
|
||||
/// The `Document` members of this module.
|
||||
pub(super) fn document_members(l: &Link) -> Vec<Described> {
|
||||
named(vec![
|
||||
("defaultFillColor", property(l, |h, a| default_color(h, a, true), |h, a| set_default_color(h, a, true)), typed("Color")),
|
||||
("defaultFilled", property(l, |h, a| default_painted(h, a, true), |h, a| set_default_painted(h, a, true)), typed("boolean")),
|
||||
("defaultFillOverprint", property(l, |h, a| default_overprint(h, a, true), |h, a| set_default_overprint(h, a, true)), typed("boolean")),
|
||||
("defaultStrokeColor", property(l, |h, a| default_color(h, a, false), |h, a| set_default_color(h, a, false)), typed("Color")),
|
||||
("defaultStroked", property(l, |h, a| default_painted(h, a, false), |h, a| set_default_painted(h, a, false)), typed("boolean")),
|
||||
("defaultStrokeOverprint", property(l, |h, a| default_overprint(h, a, false), |h, a| set_default_overprint(h, a, false)), typed("boolean")),
|
||||
(
|
||||
"defaultStrokeWidth",
|
||||
property(l, default_stroke_width, set_default_stroke_width),
|
||||
MemberInfo { min: Some(0.0), max: Some(MAX_STROKE_WIDTH), ..typed("number") },
|
||||
),
|
||||
("defaultStrokeCap", property(l, default_cap, set_default_cap), typed("StrokeCap")),
|
||||
("defaultStrokeJoin", property(l, default_join, set_default_join), typed("StrokeJoin")),
|
||||
("defaultStrokeMiterLimit", property(l, default_miter, set_default_miter), typed("number")),
|
||||
("defaultStrokeDashes", property(l, default_dashes, set_default_dashes), typed("Array")),
|
||||
("defaultStrokeDashOffset", property(l, default_dash_offset, set_default_dash_offset), typed("number")),
|
||||
("scaleFactor", get(l, scale_factor), typed("number")),
|
||||
])
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,802 @@
|
||||
//! Character and paragraph styles in the script object model: `document.characterStyles` and
|
||||
//! `document.paragraphStyles`, each `CharacterStyle` and `ParagraphStyle`, and the styles the text
|
||||
//! of a `TextRange` uses, as the help pages
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/CharacterStyles/>,
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/CharacterStyle/>,
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/ParagraphStyles/>,
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/ParagraphStyle/> and
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/> describe them.
|
||||
//!
|
||||
//! VectorCraft's own rules, which the help pages do not state:
|
||||
//! - A document's collection lists its Normal style first, then its other styles in the order the
|
||||
//! panel lists them.
|
||||
//! - A style object names its style for the rest of the run, also after the script renames it
|
||||
//! through `name`. Once the style is removed, or renamed or removed other than through the object
|
||||
//! model, or its document is closed or reverted with File › Revert, every member throws
|
||||
//! `Stale style`; a style added later under the same name is another style.
|
||||
//! - A style name is trimmed, and must then be 1 to 256 characters long with no control
|
||||
//! characters.
|
||||
//! - A style's `characterAttributes` and `paragraphAttributes` read `undefined` for an attribute the
|
||||
//! style does not set. Setting one redefines the style: text in the style takes the new value
|
||||
//! where it had the style's old one and keeps its other changes.
|
||||
//! - `applyTo(text, clearingOverrides)` takes a text range, a text frame, or the characters, words
|
||||
//! or paragraphs of one, in the style's document. A character style styles exactly that text and
|
||||
//! changes nothing on an empty range; a paragraph style styles every paragraph the text touches.
|
||||
//! `clearingOverrides` left out is false; true resets the text to the Normal style first.
|
||||
//! - A range's `characterStyles` and `paragraphStyles` list each style its characters or
|
||||
//! paragraphs are in once, in the order the text first uses it, with the Normal style for text in
|
||||
//! no other style. They do not add or remove styles.
|
||||
//! - `remove()` and `removeAll()` never remove a Normal style. Text in a removed style keeps its
|
||||
//! look and is in the Normal style after.
|
||||
//! - A script loads the styles of another document with `vc.run('charStyle.load', {path: ...})`,
|
||||
//! `paraStyle.load` or `textStyle.loadAll`, which read only a file the script may read.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
use vectorcraft_doc::{CharStyle, Shared, TextObject, TextStyleDef};
|
||||
use vectorcraft_geom::Point;
|
||||
use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostMember, MemberInfo, host_ref};
|
||||
|
||||
use super::{
|
||||
ATTRS, Answer, Attr, Doc, Host, Link, NOT_FOUND, PARA_ATTRS, ParaAttr, Span, arg, attr_param, class, command, doc_of, doc_ref, float, font_ref,
|
||||
function, get, handle_of, item_of, method, named, num, on_doc, para_param, para_range, property, range_ref, resolve, span_of, styles_in, text,
|
||||
text_of, this_range, typename_of, usize_of, whole_span, with_doc,
|
||||
};
|
||||
use crate::DocState;
|
||||
use crate::cmd::textstyles::{NORMAL_CHAR, NORMAL_PARA, style_attrs};
|
||||
use crate::script::dom::{Described, returns, typed};
|
||||
|
||||
/// The error of a style object whose style is gone.
|
||||
pub const STALE_STYLE: &str = "Stale style";
|
||||
/// The longest style name, in characters, after trimming.
|
||||
pub const MAX_STYLE_NAME: usize = 256;
|
||||
/// The most styles one run's style objects name.
|
||||
pub const MAX_HELD: usize = 4096;
|
||||
|
||||
/// A style that a run's style objects name: its document and the document's revert count then, its
|
||||
/// kind and its name now.
|
||||
struct Slot {
|
||||
uid: u64,
|
||||
reverts: u64,
|
||||
para: bool,
|
||||
name: String,
|
||||
live: bool,
|
||||
}
|
||||
|
||||
/// A document's uid and its character and paragraph style lists when the slots were last checked.
|
||||
type Seen = (u64, Shared<Vec<TextStyleDef>>, Shared<Vec<TextStyleDef>>);
|
||||
|
||||
/// The styles a run's style objects name; an object holds its slot's number.
|
||||
#[derive(Default)]
|
||||
pub(super) struct StyleState {
|
||||
slots: RefCell<Vec<Slot>>,
|
||||
seen: RefCell<Vec<Seen>>,
|
||||
}
|
||||
|
||||
/// Marks stale each style object whose style the command just run removed or renamed, so a style
|
||||
/// removed and made again under its name by later commands, or by later steps of the same batch,
|
||||
/// is another style. A document whose style lists did not change is not checked again. A live
|
||||
/// slot's style was in its document's list when the command started, so a step that removed or
|
||||
/// renamed it is in the trail's removed names.
|
||||
pub(in crate::script) fn after_command(h: &Host) {
|
||||
let trail = std::mem::take(&mut h.session.borrow_mut().script_style_trail);
|
||||
let mut slots = h.dom.text.styles.slots.borrow_mut();
|
||||
if !slots.iter().any(|s| s.live) {
|
||||
return;
|
||||
}
|
||||
for slot in slots.iter_mut().filter(|x| x.live) {
|
||||
if trail.reverted.contains(&slot.uid)
|
||||
|| (!trail.gone.is_empty() && slot.name != normal(slot.para) && trail.gone.contains(&(slot.uid, slot.para, slot.name.clone())))
|
||||
{
|
||||
slot.live = false;
|
||||
}
|
||||
}
|
||||
let s = h.session.borrow();
|
||||
let mut seen = h.dom.text.styles.seen.borrow_mut();
|
||||
seen.retain(|(uid, ..)| s.documents().iter().any(|d| d.uid == *uid));
|
||||
for st in s.documents() {
|
||||
let same = seen.iter().any(|(uid, c, p)| *uid == st.uid && Shared::ptr_eq(c, &st.doc.char_styles) && Shared::ptr_eq(p, &st.doc.para_styles));
|
||||
if same {
|
||||
continue;
|
||||
}
|
||||
seen.retain(|(uid, ..)| *uid != st.uid);
|
||||
seen.push((st.uid, st.doc.char_styles.clone(), st.doc.para_styles.clone()));
|
||||
for slot in slots.iter_mut().filter(|x| x.live && x.uid == st.uid) {
|
||||
slot.live = slot.reverts == st.reverts && has_style(st, slot.para, &slot.name);
|
||||
}
|
||||
}
|
||||
for slot in slots.iter_mut().filter(|x| x.live) {
|
||||
if !s.documents().iter().any(|d| d.uid == slot.uid) {
|
||||
slot.live = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The style objects' state when a savepoint was taken: each slot's name and whether it was
|
||||
/// live, and the style lists last checked.
|
||||
pub(in crate::script) struct Mark {
|
||||
slots: Vec<(String, bool)>,
|
||||
seen: Vec<Seen>,
|
||||
}
|
||||
|
||||
/// The style objects' state now, for [`put_back`] when the savepoint taken with it is restored.
|
||||
pub(in crate::script) fn mark(h: &Host) -> Mark {
|
||||
let styles = &h.dom.text.styles;
|
||||
let slots = styles.slots.borrow().iter().map(|s| (s.name.clone(), s.live)).collect();
|
||||
Mark { slots, seen: styles.seen.borrow().clone() }
|
||||
}
|
||||
|
||||
/// Puts the style objects back as they were at `mark`, after the documents were put back to the
|
||||
/// savepoint taken with it. A slot added since then stays live only while its document has the
|
||||
/// style and no older live slot names it.
|
||||
pub(in crate::script) fn put_back(h: &Host, mark: Mark) {
|
||||
let styles = &h.dom.text.styles;
|
||||
let mut slots = styles.slots.borrow_mut();
|
||||
let kept = mark.slots.len();
|
||||
for (slot, (name, live)) in slots.iter_mut().zip(mark.slots) {
|
||||
slot.name = name;
|
||||
slot.live = live;
|
||||
}
|
||||
let s = h.session.borrow();
|
||||
for i in kept..slots.len() {
|
||||
let (older, newer) = slots.split_at_mut(i);
|
||||
let Some(slot) = newer.first_mut() else { break };
|
||||
let named = older.iter().any(|o| o.live && o.uid == slot.uid && o.para == slot.para && o.name == slot.name);
|
||||
slot.live = !named && s.documents().iter().any(|st| st.uid == slot.uid && st.reverts == slot.reverts && has_style(st, slot.para, &slot.name));
|
||||
}
|
||||
*styles.seen.borrow_mut() = mark.seen;
|
||||
}
|
||||
|
||||
fn normal(para: bool) -> &'static str {
|
||||
if para { NORMAL_PARA } else { NORMAL_CHAR }
|
||||
}
|
||||
|
||||
fn cmd(para: bool, verb: &str) -> String {
|
||||
format!("{}.{verb}", if para { "paraStyle" } else { "charStyle" })
|
||||
}
|
||||
|
||||
fn style_class(para: bool) -> &'static str {
|
||||
if para { "ParagraphStyle" } else { "CharacterStyle" }
|
||||
}
|
||||
|
||||
fn list_class(para: bool) -> &'static str {
|
||||
if para { "ParagraphStyles" } else { "CharacterStyles" }
|
||||
}
|
||||
|
||||
fn defs(st: &DocState, para: bool) -> &Vec<TextStyleDef> {
|
||||
if para { &st.doc.para_styles } else { &st.doc.char_styles }
|
||||
}
|
||||
|
||||
/// The document's style names of a kind, the Normal style first.
|
||||
fn names(st: &DocState, para: bool) -> Vec<String> {
|
||||
let mut out = vec![normal(para).to_string()];
|
||||
out.extend(defs(st, para).iter().map(|d| d.name.clone()).filter(|n| n != normal(para)));
|
||||
out
|
||||
}
|
||||
|
||||
fn has_style(st: &DocState, para: bool, name: &str) -> bool {
|
||||
name == normal(para) || defs(st, para).iter().any(|d| d.name == name)
|
||||
}
|
||||
|
||||
fn stale() -> HostError {
|
||||
HostError::Error(STALE_STYLE.into())
|
||||
}
|
||||
|
||||
fn held_too_many() -> HostError {
|
||||
HostError::Range(format!("a script can name at most {MAX_HELD} styles in one run"))
|
||||
}
|
||||
|
||||
/// The style object for the style `name` of the document `uid`: the same slot as every other
|
||||
/// object naming it in this run.
|
||||
fn style_ref(h: &Host, uid: u64, para: bool, name: &str) -> Answer {
|
||||
let reverts = h.session.borrow().documents().iter().find(|d| d.uid == uid).map_or(0, |d| d.reverts);
|
||||
let mut slots = h.dom.text.styles.slots.borrow_mut();
|
||||
let i = match slots.iter().position(|s| s.live && s.uid == uid && s.reverts == reverts && s.para == para && s.name == name) {
|
||||
Some(i) => i,
|
||||
None => {
|
||||
if slots.len() >= MAX_HELD {
|
||||
return Err(held_too_many());
|
||||
}
|
||||
slots.push(Slot { uid, reverts, para, name: name.to_string(), live: true });
|
||||
slots.len() - 1
|
||||
}
|
||||
};
|
||||
Ok(host_ref(style_class(para), &[float(h.run), float(uid), float(i as u64)]))
|
||||
}
|
||||
|
||||
/// A style a style object names.
|
||||
struct Style {
|
||||
doc: Doc,
|
||||
para: bool,
|
||||
slot: usize,
|
||||
name: String,
|
||||
}
|
||||
|
||||
/// The style `d` names, when it is an object of one of `classes` (with the kind each names).
|
||||
fn style_of(h: &Host, d: &Data, classes: &[(&str, bool)]) -> std::result::Result<Style, HostError> {
|
||||
let found = classes.iter().find_map(|(c, para)| handle_of(d, c).map(|handle| (handle, *para)));
|
||||
let Some((handle, para)) = found else {
|
||||
return Err(HostError::Type(format!("this is not a {}", classes.first().map_or("CharacterStyle", |c| c.0))));
|
||||
};
|
||||
let [run, uid, slot] = handle.as_slice() else { return Err(stale()) };
|
||||
let doc = super::super::find_doc(h, *run, *uid).ok_or_else(stale)?;
|
||||
let slot = usize_of(*slot).ok_or_else(stale)?;
|
||||
let mut slots = h.dom.text.styles.slots.borrow_mut();
|
||||
let s = slots.get_mut(slot).filter(|s| s.live && s.uid == doc.uid && s.para == para).ok_or_else(stale)?;
|
||||
if !with_doc(h, doc, |_, st| st.reverts == s.reverts && has_style(st, para, &s.name)) {
|
||||
s.live = false;
|
||||
return Err(stale());
|
||||
}
|
||||
Ok(Style { doc, para, slot, name: s.name.clone() })
|
||||
}
|
||||
|
||||
fn this_style(h: &Host, a: &[Data]) -> std::result::Result<Style, HostError> {
|
||||
style_of(h, arg(a, 0), &[("CharacterStyle", false), ("ParagraphStyle", true)])
|
||||
}
|
||||
|
||||
/// Marks the slots of the styles `names` of the document `uid` as removed.
|
||||
fn forget(h: &Host, uid: u64, para: bool, names: &[String]) {
|
||||
for s in h.dom.text.styles.slots.borrow_mut().iter_mut() {
|
||||
if s.uid == uid && s.para == para && names.contains(&s.name) {
|
||||
s.live = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A style name a script gave, trimmed.
|
||||
fn style_name(v: &Data) -> std::result::Result<String, HostError> {
|
||||
let Data::String(s) = v else { return Err(HostError::Type("a style name must be a string".into())) };
|
||||
if s.len() > super::super::MAX_TEXT_BYTES {
|
||||
return Err(HostError::Range(format!("a style name must be at most {MAX_STYLE_NAME} characters")));
|
||||
}
|
||||
let t = s.trim();
|
||||
if t.is_empty() {
|
||||
return Err(HostError::Range("a style name must not be empty".into()));
|
||||
}
|
||||
if t.chars().count() > MAX_STYLE_NAME {
|
||||
return Err(HostError::Range(format!("a style name must be at most {MAX_STYLE_NAME} characters")));
|
||||
}
|
||||
if t.chars().any(char::is_control) {
|
||||
return Err(HostError::Range("a style name must not hold control characters".into()));
|
||||
}
|
||||
Ok(t.to_string())
|
||||
}
|
||||
|
||||
/// Runs the style command `verb` of the kind on the document of `doc`.
|
||||
fn run(h: &Host, doc: Doc, para: bool, verb: &str, params: &Value) -> std::result::Result<Data, HostError> {
|
||||
on_doc(h, doc.uid, true, |h| command(h, &cmd(para, verb), params))
|
||||
}
|
||||
|
||||
// ---- CharacterStyle and ParagraphStyle ----
|
||||
|
||||
fn style_name_get(h: &Host, a: &[Data]) -> Answer {
|
||||
Ok(text(this_style(h, a)?.name))
|
||||
}
|
||||
|
||||
/// `name = …`: renames the style; the Normal style keeps its name.
|
||||
fn style_name_set(h: &Host, a: &[Data]) -> Answer {
|
||||
let style = this_style(h, a)?;
|
||||
let to = style_name(arg(a, 1))?;
|
||||
if to == style.name {
|
||||
return Ok(Data::Undefined);
|
||||
}
|
||||
if style.name == normal(style.para) {
|
||||
return Err(HostError::Error(format!("{} cannot be renamed", style.name)));
|
||||
}
|
||||
if with_doc(h, style.doc, |_, st| has_style(st, style.para, &to)) {
|
||||
return Err(HostError::Error(format!("a style named {to} already exists")));
|
||||
}
|
||||
run(h, style.doc, style.para, "rename", &json!({"name": style.name, "to": to}))?;
|
||||
forget(h, style.doc.uid, style.para, std::slice::from_ref(&to));
|
||||
if let Some(s) = h.dom.text.styles.slots.borrow_mut().get_mut(style.slot) {
|
||||
s.name = to;
|
||||
s.live = true;
|
||||
}
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
fn style_parent(h: &Host, a: &[Data]) -> Answer {
|
||||
Ok(doc_ref(h, this_style(h, a)?.doc.uid))
|
||||
}
|
||||
|
||||
fn style_typename(h: &Host, a: &[Data]) -> Answer {
|
||||
Ok(text(style_class(this_style(h, a)?.para)))
|
||||
}
|
||||
|
||||
fn attributes(h: &Host, a: &[Data], class: &str) -> Answer {
|
||||
let style = this_style(h, a)?;
|
||||
Ok(host_ref(class, &[float(h.run), float(style.doc.uid), float(style.slot as u64)]))
|
||||
}
|
||||
|
||||
fn style_character_attributes(h: &Host, a: &[Data]) -> Answer {
|
||||
attributes(h, a, "CharacterStyleAttributes")
|
||||
}
|
||||
|
||||
fn style_paragraph_attributes(h: &Host, a: &[Data]) -> Answer {
|
||||
attributes(h, a, "ParagraphStyleAttributes")
|
||||
}
|
||||
|
||||
/// `remove()`: deletes the style; its text keeps its look and is in the Normal style after.
|
||||
fn style_remove(h: &Host, a: &[Data]) -> Answer {
|
||||
let style = this_style(h, a)?;
|
||||
if style.name == normal(style.para) {
|
||||
return Err(HostError::Error(format!("{} cannot be removed", style.name)));
|
||||
}
|
||||
run(h, style.doc, style.para, "delete", &json!({"name": style.name}))?;
|
||||
forget(h, style.doc.uid, style.para, &[style.name]);
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
/// The text a style is applied to: a text range, a text frame, or the characters, words or
|
||||
/// paragraphs of one.
|
||||
fn target_span(h: &Host, d: &Data) -> std::result::Result<Span, HostError> {
|
||||
if handle_of(d, "TextFrame").is_some() {
|
||||
return Ok(whole_span(h, item_of(h, d)?)?.1);
|
||||
}
|
||||
const TEXT: [&str; 4] = ["TextRange", "Characters", "Words", "Paragraphs"];
|
||||
if !TEXT.iter().any(|c| handle_of(d, c).is_some()) {
|
||||
return Err(HostError::Type("applyTo takes a TextRange or a TextFrame".into()));
|
||||
}
|
||||
span_of(h, d, &TEXT)
|
||||
}
|
||||
|
||||
/// `applyTo(textItem, clearingOverrides?)`.
|
||||
fn style_apply_to(h: &Host, a: &[Data]) -> Answer {
|
||||
let style = this_style(h, a)?;
|
||||
let target = target_span(h, arg(a, 1))?;
|
||||
let clear = match arg(a, 2) {
|
||||
Data::Undefined => false,
|
||||
Data::Bool(b) => *b,
|
||||
_ => return Err(HostError::Type("clearingOverrides must be true or false".into())),
|
||||
};
|
||||
if target.item.doc.uid != style.doc.uid {
|
||||
return Err(HostError::Error("the text is in another document than the style".into()));
|
||||
}
|
||||
let (index, s, e, _) = resolve(h, target)?;
|
||||
h.charge_call(16 + (e - s) as u64)?;
|
||||
let (start, end) = if style.para {
|
||||
let (_, ba, bb) = para_range(&index, s, e);
|
||||
(ba, bb)
|
||||
} else {
|
||||
// An empty range inside text changes nothing; empty text takes the style on its runs.
|
||||
if s == e && index.len() > 0 {
|
||||
return Ok(Data::Undefined);
|
||||
}
|
||||
(index.byte(s, false), index.byte(e, true))
|
||||
};
|
||||
let p = json!({"name": style.name, "clearOverrides": clear, "id": target.item.id.0, "start": start, "end": end});
|
||||
run(h, style.doc, style.para, "apply", &p)?;
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
// ---- the attributes of a style ----
|
||||
|
||||
/// The style attribute each `text.setRangeStyle` parameter `attr_param` gives sets.
|
||||
const CHAR_KEYS: [(&str, &str); 11] = [
|
||||
("size", "size"),
|
||||
("leading", "leading"),
|
||||
("tracking", "tracking"),
|
||||
("baselineShift", "baseline_shift"),
|
||||
("hScale", "h_scale"),
|
||||
("vScale", "v_scale"),
|
||||
("rotation", "rotation"),
|
||||
("underline", "underline"),
|
||||
("strikethrough", "strikethrough"),
|
||||
("font", "font_family"),
|
||||
("style", "font_style"),
|
||||
];
|
||||
|
||||
/// The script's `Justification` members and the alignments a paragraph style stores.
|
||||
const JUSTIFY: [(&str, &str); 7] = [
|
||||
("LEFT", "Left"),
|
||||
("CENTER", "Center"),
|
||||
("RIGHT", "Right"),
|
||||
("FULLJUSTIFYLASTLINELEFT", "JustifyLeft"),
|
||||
("FULLJUSTIFYLASTLINECENTER", "JustifyCenter"),
|
||||
("FULLJUSTIFYLASTLINERIGHT", "JustifyRight"),
|
||||
("FULLJUSTIFY", "JustifyAll"),
|
||||
];
|
||||
|
||||
/// The style an attributes object belongs to and the attributes it sets.
|
||||
fn attrs_of(h: &Host, a: &[Data], para: bool) -> std::result::Result<(Style, Map<String, Value>), HostError> {
|
||||
let class = if para { "ParagraphStyleAttributes" } else { "CharacterStyleAttributes" };
|
||||
let style = style_of(h, arg(a, 0), &[(class, para)])?;
|
||||
let attrs = with_doc(h, style.doc, |_, st| style_attrs(&st.doc, para, &style.name)).ok_or_else(stale)?;
|
||||
Ok((style, attrs))
|
||||
}
|
||||
|
||||
fn char_value(h: &Host, attr: Attr, m: &Map<String, Value>) -> Data {
|
||||
let n = |k: &str| m.get(k).and_then(Value::as_f64).map_or(Data::Undefined, num);
|
||||
let b = |k: &str| m.get(k).and_then(Value::as_bool).map_or(Data::Undefined, Data::Bool);
|
||||
match attr {
|
||||
Attr::Size => n("size"),
|
||||
Attr::Leading => n("leading"),
|
||||
Attr::AutoLeading => match m.get("leading") {
|
||||
Some(Value::Null) => Data::Bool(true),
|
||||
Some(v) if v.is_number() => Data::Bool(false),
|
||||
_ => Data::Undefined,
|
||||
},
|
||||
Attr::Tracking => n("tracking"),
|
||||
Attr::BaselineShift => n("baseline_shift"),
|
||||
Attr::HorizontalScale => n("h_scale"),
|
||||
Attr::VerticalScale => n("v_scale"),
|
||||
Attr::Rotation => n("rotation"),
|
||||
Attr::Underline => b("underline"),
|
||||
Attr::StrikeThrough => b("strikethrough"),
|
||||
Attr::TextFont => match m.get("font_family").and_then(Value::as_str) {
|
||||
Some(family) => font_ref(h, family, m.get("font_style").and_then(Value::as_str).unwrap_or("Regular")),
|
||||
None => Data::Undefined,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// The `typename` of a style's `characterAttributes`, which throws once the style is gone.
|
||||
fn attrs_typename_char(h: &Host, a: &[Data]) -> Answer {
|
||||
attrs_of(h, a, false)?;
|
||||
Ok(text("CharacterAttributes"))
|
||||
}
|
||||
|
||||
/// The `typename` of a style's `paragraphAttributes`, which throws once the style is gone.
|
||||
fn attrs_typename_para(h: &Host, a: &[Data]) -> Answer {
|
||||
attrs_of(h, a, true)?;
|
||||
Ok(text("ParagraphAttributes"))
|
||||
}
|
||||
|
||||
fn read_char(h: &Host, a: &[Data], attr: Attr) -> Answer {
|
||||
let (_, m) = attrs_of(h, a, false)?;
|
||||
Ok(char_value(h, attr, &m))
|
||||
}
|
||||
|
||||
/// Redefines the style with `attrs`, unless they are what it has.
|
||||
fn redefine(h: &Host, style: &Style, old: &Map<String, Value>, attrs: Map<String, Value>) -> Answer {
|
||||
if attrs == *old {
|
||||
return Ok(Data::Undefined);
|
||||
}
|
||||
run(h, style.doc, style.para, "setAttrs", &json!({"name": style.name, "attrs": attrs}))?;
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
fn write_char(h: &Host, a: &[Data], attr: Attr, name: &str) -> Answer {
|
||||
let (style, old) = attrs_of(h, a, false)?;
|
||||
// `autoLeading = false` keeps the leading auto leading gives the style's size in a paragraph
|
||||
// with the default justification.
|
||||
let base = CharStyle::default();
|
||||
let size = old.get("size").and_then(Value::as_f64).unwrap_or(base.size);
|
||||
let leading = old.get("leading").and_then(Value::as_f64);
|
||||
let sample = CharStyle { size, leading, ..base };
|
||||
let t = TextObject::point(Point::default(), "", sample.clone());
|
||||
let (param, _) = attr_param(h, attr, name, arg(a, 1), (&t, &sample, 0))?;
|
||||
let mut attrs = old.clone();
|
||||
for (k, v) in param.as_object().into_iter().flatten() {
|
||||
let Some((_, key)) = CHAR_KEYS.iter().find(|(p, _)| *p == k.as_str()) else { continue };
|
||||
let v = if *key == "leading" && v == "auto" { Value::Null } else { v.clone() };
|
||||
attrs.insert((*key).to_string(), v);
|
||||
}
|
||||
redefine(h, &style, &old, attrs)
|
||||
}
|
||||
|
||||
fn para_key(attr: ParaAttr) -> &'static str {
|
||||
match attr {
|
||||
ParaAttr::Justification => "justify",
|
||||
ParaAttr::FirstLineIndent => "first_line_indent",
|
||||
ParaAttr::LeftIndent => "left_indent",
|
||||
ParaAttr::RightIndent => "right_indent",
|
||||
ParaAttr::SpaceBefore => "space_before",
|
||||
ParaAttr::SpaceAfter => "space_after",
|
||||
}
|
||||
}
|
||||
|
||||
fn read_para(h: &Host, a: &[Data], attr: ParaAttr) -> Answer {
|
||||
let (_, m) = attrs_of(h, a, true)?;
|
||||
let v = m.get(para_key(attr));
|
||||
Ok(match attr {
|
||||
ParaAttr::Justification => match v.and_then(Value::as_str) {
|
||||
Some("Auto") => text("Justification.LEFT"),
|
||||
Some(s) => JUSTIFY.iter().find(|(_, j)| *j == s).map_or(Data::Undefined, |(k, _)| text(format!("Justification.{k}"))),
|
||||
None => Data::Undefined,
|
||||
},
|
||||
_ => v.and_then(Value::as_f64).map_or(Data::Undefined, num),
|
||||
})
|
||||
}
|
||||
|
||||
fn write_para(h: &Host, a: &[Data], attr: ParaAttr, name: &str) -> Answer {
|
||||
let (style, old) = attrs_of(h, a, true)?;
|
||||
let (_, _, wants) = para_param(attr, name, arg(a, 1))?;
|
||||
let value = match (&wants, attr) {
|
||||
(Data::String(s), ParaAttr::Justification) => {
|
||||
let m = s.strip_prefix("Justification.").unwrap_or(s);
|
||||
let found = JUSTIFY.iter().find(|(k, _)| *k == m).map(|(_, j)| *j);
|
||||
json!(found.ok_or_else(|| HostError::Type("justification must be a Justification value".into()))?)
|
||||
}
|
||||
(Data::Number(n), _) => json!(n),
|
||||
_ => return Err(HostError::Type(format!("{name} must be a finite number"))),
|
||||
};
|
||||
let mut attrs = old.clone();
|
||||
attrs.insert(para_key(attr).to_string(), value);
|
||||
redefine(h, &style, &old, attrs)
|
||||
}
|
||||
|
||||
/// The body of a member that captures what it reads or sets.
|
||||
type Body = Rc<dyn Fn(&Host, &[Data]) -> Answer>;
|
||||
|
||||
/// Members whose getter and setter each charge the call, as [`function`] does.
|
||||
fn charged(link: &Link, g: impl Fn(&Host, &[Data]) -> Answer + 'static, s: impl Fn(&Host, &[Data]) -> Answer + 'static) -> HostMember {
|
||||
let wrap = |f: Body| -> HostFunction {
|
||||
let l = link.clone();
|
||||
Rc::new(move |a: Vec<Data>| {
|
||||
let h = super::super::current(&l)?;
|
||||
h.charge_call(16 + a.iter().map(super::super::data_size).sum::<u64>())?;
|
||||
f(&h, &a)
|
||||
})
|
||||
};
|
||||
HostMember::Property { get: wrap(Rc::new(g)), set: wrap(Rc::new(s)) }
|
||||
}
|
||||
|
||||
fn char_members(link: &Link) -> Vec<Described> {
|
||||
ATTRS
|
||||
.iter()
|
||||
.map(|&(name, attr)| {
|
||||
let data_type = match attr {
|
||||
Attr::AutoLeading | Attr::Underline | Attr::StrikeThrough => "boolean",
|
||||
Attr::TextFont => "TextFont",
|
||||
_ => "number",
|
||||
};
|
||||
(name.to_string(), charged(link, move |h, a| read_char(h, a, attr), move |h, a| write_char(h, a, attr, name)), typed(data_type))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn para_members(link: &Link) -> Vec<Described> {
|
||||
PARA_ATTRS
|
||||
.iter()
|
||||
.map(|&(name, attr)| {
|
||||
let data_type = if matches!(attr, ParaAttr::Justification) { "Justification" } else { "number" };
|
||||
(name.to_string(), charged(link, move |h, a| read_para(h, a, attr), move |h, a| write_para(h, a, attr, name)), typed(data_type))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
// ---- CharacterStyles and ParagraphStyles ----
|
||||
|
||||
/// What a collection of styles lists: a document's styles, or those a text range uses.
|
||||
enum Of {
|
||||
Doc(Doc),
|
||||
Range(Span),
|
||||
}
|
||||
|
||||
fn list_of(h: &Host, d: &Data) -> std::result::Result<(Of, bool), HostError> {
|
||||
let para = match (handle_of(d, "CharacterStyles"), handle_of(d, "ParagraphStyles")) {
|
||||
(Some(_), _) => false,
|
||||
(_, Some(_)) => true,
|
||||
_ => return Err(HostError::Type("this is not a CharacterStyles".into())),
|
||||
};
|
||||
let class = list_class(para);
|
||||
let len = handle_of(d, class).map_or(0, |v| v.len());
|
||||
Ok((if len == 2 { Of::Doc(doc_of(h, d, class)?) } else { Of::Range(span_of(h, d, &[class])?) }, para))
|
||||
}
|
||||
|
||||
/// The document and the names of the styles a collection lists.
|
||||
fn listed(h: &Host, of: &Of, para: bool) -> std::result::Result<(Doc, Vec<String>), HostError> {
|
||||
match of {
|
||||
Of::Doc(doc) => {
|
||||
let names = with_doc(h, *doc, |_, st| names(st, para));
|
||||
h.charge_call(names.len() as u64)?;
|
||||
Ok((*doc, names))
|
||||
}
|
||||
Of::Range(r) => {
|
||||
let (index, s, e, _) = resolve(h, *r)?;
|
||||
let used = with_doc(h, r.item.doc, |_, st| {
|
||||
let t = text_of(st, r.item.id).ok_or_else(|| HostError::Error(super::STALE_ITEM.into()))?;
|
||||
let used: Vec<Option<String>> = if para {
|
||||
let (paras, _, _) = para_range(&index, s, e);
|
||||
paras.map(|i| t.para_at(i).style_name.clone()).collect()
|
||||
} else {
|
||||
styles_in(t, index.byte(s, false), index.byte(e, true), false)?.into_iter().map(|(c, _)| c.style_name).collect()
|
||||
};
|
||||
h.charge_call(used.len() as u64)?;
|
||||
let mut out: Vec<String> = Vec::new();
|
||||
for n in used {
|
||||
let n = n.filter(|n| has_style(st, para, n)).unwrap_or_else(|| normal(para).to_string());
|
||||
if !out.contains(&n) {
|
||||
out.push(n);
|
||||
}
|
||||
}
|
||||
if out.is_empty() {
|
||||
out.push(normal(para).to_string());
|
||||
}
|
||||
Ok::<_, HostError>(out)
|
||||
})?;
|
||||
Ok((r.item.doc, used))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn list_length(h: &Host, a: &[Data]) -> Answer {
|
||||
let (of, para) = list_of(h, arg(a, 0))?;
|
||||
Ok(num(float(listed(h, &of, para)?.1.len() as u64)))
|
||||
}
|
||||
|
||||
fn list_parent(h: &Host, a: &[Data]) -> Answer {
|
||||
let (of, _) = list_of(h, arg(a, 0))?;
|
||||
match of {
|
||||
Of::Doc(doc) => Ok(doc_ref(h, doc.uid)),
|
||||
Of::Range(r) => {
|
||||
let (_, s, e, stamp) = resolve(h, r)?;
|
||||
Ok(range_ref(h, r.item, s, e, stamp, "TextRange"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn list_at(h: &Host, a: &[Data]) -> Answer {
|
||||
let (of, para) = list_of(h, arg(a, 0))?;
|
||||
let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) };
|
||||
let Some(i) = usize_of(*n) else { return Ok(Data::Undefined) };
|
||||
let found = match &of {
|
||||
Of::Doc(doc) => with_doc(h, *doc, |_, st| match i {
|
||||
0 => Some(normal(para).to_string()),
|
||||
_ => defs(st, para).iter().map(|d| &d.name).filter(|n| *n != normal(para)).nth(i - 1).cloned(),
|
||||
})
|
||||
.map(|n| (*doc, n)),
|
||||
Of::Range(_) => {
|
||||
let (doc, names) = listed(h, &of, para)?;
|
||||
names.get(i).cloned().map(|n| (doc, n))
|
||||
}
|
||||
};
|
||||
match found {
|
||||
Some((doc, name)) => style_ref(h, doc.uid, para, &name),
|
||||
None => Ok(Data::Undefined),
|
||||
}
|
||||
}
|
||||
|
||||
fn list_by_name(h: &Host, a: &[Data]) -> Answer {
|
||||
let (of, para) = list_of(h, arg(a, 0))?;
|
||||
let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) };
|
||||
if name.len() > super::super::MAX_TEXT_BYTES {
|
||||
return Err(HostError::Range("the name is too long".into()));
|
||||
}
|
||||
let (doc, names) = listed(h, &of, para)?;
|
||||
match names.iter().find(|n| *n == name) {
|
||||
Some(n) => style_ref(h, doc.uid, para, n),
|
||||
None => Err(HostError::Error(NOT_FOUND.into())),
|
||||
}
|
||||
}
|
||||
|
||||
fn list_index(h: &Host, a: &[Data]) -> Answer {
|
||||
match arg(a, 1) {
|
||||
Data::String(_) => list_by_name(h, a),
|
||||
Data::Number(_) => match list_at(h, a)? {
|
||||
Data::Undefined => Err(HostError::Error(NOT_FOUND.into())),
|
||||
d => Ok(d),
|
||||
},
|
||||
_ => Err(HostError::Type("give a name or an index".into())),
|
||||
}
|
||||
}
|
||||
|
||||
/// The document of a document's collection; a range's collection cannot be changed.
|
||||
fn changed_doc(h: &Host, a: &[Data]) -> std::result::Result<(Doc, bool), HostError> {
|
||||
match list_of(h, arg(a, 0))? {
|
||||
(Of::Doc(doc), para) => Ok((doc, para)),
|
||||
(Of::Range(_), _) => Err(HostError::Error("the styles of a text range cannot be added or removed".into())),
|
||||
}
|
||||
}
|
||||
|
||||
/// `add(name)`: a new style that sets no attributes.
|
||||
fn list_add(h: &Host, a: &[Data]) -> Answer {
|
||||
let (doc, para) = changed_doc(h, a)?;
|
||||
let name = style_name(arg(a, 1))?;
|
||||
if with_doc(h, doc, |_, st| has_style(st, para, &name)) {
|
||||
return Err(HostError::Error(format!("a style named {name} already exists")));
|
||||
}
|
||||
// The new style needs a slot of its own: a run that names as many styles as it may adds none.
|
||||
if h.dom.text.styles.slots.borrow().len() >= MAX_HELD {
|
||||
return Err(held_too_many());
|
||||
}
|
||||
run(h, doc, para, "new", &json!({"name": name, "attrs": {}}))?;
|
||||
// An object of a removed style of this name stays stale.
|
||||
forget(h, doc.uid, para, std::slice::from_ref(&name));
|
||||
style_ref(h, doc.uid, para, &name)
|
||||
}
|
||||
|
||||
/// `removeAll()`: deletes every style but the Normal style, in one command.
|
||||
fn list_remove_all(h: &Host, a: &[Data]) -> Answer {
|
||||
let (doc, para) = changed_doc(h, a)?;
|
||||
let gone: Vec<String> = with_doc(h, doc, |_, st| names(st, para)).into_iter().skip(1).collect();
|
||||
if gone.is_empty() {
|
||||
return Ok(Data::Undefined);
|
||||
}
|
||||
run(h, doc, para, "delete", &json!({"names": gone}))?;
|
||||
forget(h, doc.uid, para, &gone);
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
fn doc_char_styles(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = doc_of(h, arg(a, 0), "Document")?;
|
||||
Ok(host_ref("CharacterStyles", &[float(h.run), float(doc.uid)]))
|
||||
}
|
||||
|
||||
fn doc_para_styles(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = doc_of(h, arg(a, 0), "Document")?;
|
||||
Ok(host_ref("ParagraphStyles", &[float(h.run), float(doc.uid)]))
|
||||
}
|
||||
|
||||
fn range_styles(h: &Host, a: &[Data], para: bool) -> Answer {
|
||||
let r = this_range(h, a)?;
|
||||
let (_, s, e, stamp) = resolve(h, r)?;
|
||||
Ok(range_ref(h, r.item, s, e, stamp, list_class(para)))
|
||||
}
|
||||
|
||||
fn range_char_styles(h: &Host, a: &[Data]) -> Answer {
|
||||
range_styles(h, a, false)
|
||||
}
|
||||
|
||||
fn range_para_styles(h: &Host, a: &[Data]) -> Answer {
|
||||
range_styles(h, a, true)
|
||||
}
|
||||
|
||||
/// `document.characterStyles` and `document.paragraphStyles`.
|
||||
pub(in crate::script) fn doc_members(l: &Link) -> Vec<Described> {
|
||||
named(vec![
|
||||
("characterStyles", get(l, doc_char_styles), MemberInfo { collection: true, ..typed("CharacterStyles") }),
|
||||
("paragraphStyles", get(l, doc_para_styles), MemberInfo { collection: true, ..typed("ParagraphStyles") }),
|
||||
])
|
||||
}
|
||||
|
||||
/// `TextRange.characterStyles` and `TextRange.paragraphStyles`.
|
||||
pub(super) fn range_members(l: &Link) -> Vec<Described> {
|
||||
named(vec![
|
||||
("characterStyles", get(l, range_char_styles), MemberInfo { collection: true, ..typed("CharacterStyles") }),
|
||||
("paragraphStyles", get(l, range_para_styles), MemberInfo { collection: true, ..typed("ParagraphStyles") }),
|
||||
])
|
||||
}
|
||||
|
||||
/// The style classes.
|
||||
pub(super) fn classes(l: &Link) -> Vec<HostClass> {
|
||||
let style = |para: bool| {
|
||||
let mut members = named(vec![
|
||||
("typename", get(l, style_typename), typed("string")),
|
||||
("name", property(l, style_name_get, style_name_set), typed("string")),
|
||||
("parent", get(l, style_parent), typed("Document")),
|
||||
("applyTo", method(l, style_apply_to), returns("undefined", &[("textItem", "*"), ("clearingOverrides", "boolean")])),
|
||||
("remove", method(l, style_remove), returns("undefined", &[])),
|
||||
]);
|
||||
if para {
|
||||
members.push(("paragraphAttributes".into(), get(l, style_paragraph_attributes), typed("ParagraphStyleAttributes")));
|
||||
members.push(super::super::later(l, "ParagraphStyle", "characterAttributes"));
|
||||
} else {
|
||||
members.push(("characterAttributes".into(), get(l, style_character_attributes), typed("CharacterStyleAttributes")));
|
||||
}
|
||||
class(style_class(para), None, members, None)
|
||||
};
|
||||
let list = |para: bool| {
|
||||
let name = list_class(para);
|
||||
let item = style_class(para);
|
||||
class(
|
||||
name,
|
||||
None,
|
||||
named(vec![
|
||||
("typename", typename_of(name), typed("string")),
|
||||
("length", get(l, list_length), typed("number")),
|
||||
("parent", get(l, list_parent), typed("*")),
|
||||
("index", method(l, list_index), returns(item, &[("itemKey", "*")])),
|
||||
("getByName", method(l, list_by_name), returns(item, &[("name", "string")])),
|
||||
("add", method(l, list_add), returns(item, &[("name", "string")])),
|
||||
("removeAll", method(l, list_remove_all), returns("undefined", &[])),
|
||||
]),
|
||||
Some(function(l, list_at)),
|
||||
)
|
||||
};
|
||||
let mut chars = named(vec![("typename", get(l, attrs_typename_char), typed("string"))]);
|
||||
chars.extend(char_members(l));
|
||||
let mut paras = named(vec![("typename", get(l, attrs_typename_para), typed("string"))]);
|
||||
paras.extend(para_members(l));
|
||||
vec![
|
||||
style(false),
|
||||
style(true),
|
||||
list(false),
|
||||
list(true),
|
||||
class("CharacterStyleAttributes", None, chars, None),
|
||||
class("ParagraphStyleAttributes", None, paras, None),
|
||||
]
|
||||
}
|
||||
Loaded 100 of 474 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user