Merge main into feat/scripts-api-layer-path-items

This commit is contained in:
dotCooCoo
2026-12-01 09:03:00 -08:00
218 changed files with 12153 additions and 1083 deletions
+10 -4
View File
@@ -47,6 +47,9 @@ jobs:
test-shards: 6
shard-command: cargo xtask ci shard
warm-command: cargo xtask ci warm
# The warm build runs as one `cache warm <k>/6` leg per shard, in parallel (each builds what
# its shard builds), and `cache warm` puts their files into the one entry it saves.
warm-split: true
# The dependency cache also keeps the compiled workspace crates and test executables, so a
# pull request's shards rebuild only the crates its changes reach. Each main run's `cache
# warm` leg saves a rolling entry of its own, every leg restores the newest one, and
@@ -65,14 +68,17 @@ jobs:
# the old entries when the `cache warm` leg starts saving (scripts/ci-clear-rolling-cache.py).
# When the leg fails or is canceled, before its save or during it, this job fails too, so "Re-run
# failed jobs" runs it again beside the re-run leg. The leg starts after `gate / select legs` and a
# free runner: the script fails when the leg has not started within 120 minutes, and then waits
# up to 160 minutes from the leg's start. This job's timeout is longer than both together, so the
# script reports a leg that starts late with its own error before the job times out.
# free runner, and with `warm-split` after every `cache warm <k>/6` leg. The script suspends its
# start deadline while any split leg is queued or running, then allows 180 minutes from the last
# split completion for the saving leg to start. Without split legs, it allows 180 minutes from
# the script's start. A failed split leg fails this job too. The script then waits up to 160
# minutes from the saving leg's start. GitHub's 360-minute job limit can end this job before the
# script's deadlines expire when split builds or runner waits take too long.
cold-cache-clear:
name: cold cache clear
if: github.event_name == 'schedule'
runs-on: ubuntu-24.04
timeout-minutes: 290
timeout-minutes: 360
permissions:
actions: write
steps:
Generated
+86 -87
View File
@@ -1231,7 +1231,7 @@ dependencies = [
[[package]]
name = "craft"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
dependencies = [
"craft-automation",
"craft-behavior",
@@ -1272,7 +1272,7 @@ dependencies = [
[[package]]
name = "craft-affinity"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
dependencies = [
"crc32fast",
"flate2",
@@ -1283,7 +1283,7 @@ dependencies = [
[[package]]
name = "craft-appkit"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
dependencies = [
"block2 0.6.2",
"objc2 0.6.5",
@@ -1295,7 +1295,7 @@ dependencies = [
[[package]]
name = "craft-atomic"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
dependencies = [
"rustix 1.1.6",
]
@@ -1303,7 +1303,7 @@ dependencies = [
[[package]]
name = "craft-automation"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
dependencies = [
"base64 0.23.1",
"craft-behavior",
@@ -1328,7 +1328,7 @@ dependencies = [
[[package]]
name = "craft-behavior"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
dependencies = [
"accesskit",
"bitflags 2.13.2",
@@ -1346,7 +1346,7 @@ dependencies = [
[[package]]
name = "craft-browse"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
dependencies = [
"craft-behavior",
"craft-docpath",
@@ -1364,7 +1364,7 @@ dependencies = [
[[package]]
name = "craft-cdr"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
dependencies = [
"crc32fast",
"flate2",
@@ -1373,7 +1373,7 @@ dependencies = [
[[package]]
name = "craft-cloud-ui"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
dependencies = [
"egui",
]
@@ -1381,7 +1381,7 @@ dependencies = [
[[package]]
name = "craft-cms"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
dependencies = [
"md-5",
"rayon",
@@ -1390,12 +1390,12 @@ dependencies = [
[[package]]
name = "craft-codepage"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
[[package]]
name = "craft-color-ui"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
dependencies = [
"craft-behavior",
"craft-cms",
@@ -1415,7 +1415,7 @@ dependencies = [
[[package]]
name = "craft-control"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
dependencies = [
"craft-control-protocol",
"craft-platform",
@@ -1426,7 +1426,7 @@ dependencies = [
[[package]]
name = "craft-control-protocol"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
dependencies = [
"getrandom 0.3.4",
"serde_json",
@@ -1436,7 +1436,7 @@ dependencies = [
[[package]]
name = "craft-dds"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
dependencies = [
"rayon",
]
@@ -1444,7 +1444,7 @@ dependencies = [
[[package]]
name = "craft-dialogs"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
dependencies = [
"block2 0.6.2",
"craft-appkit",
@@ -1470,7 +1470,7 @@ dependencies = [
[[package]]
name = "craft-doc"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
dependencies = [
"blake3",
"craft-ecproj-format",
@@ -1486,7 +1486,7 @@ dependencies = [
[[package]]
name = "craft-docpath"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
dependencies = [
"serde",
]
@@ -1494,7 +1494,7 @@ dependencies = [
[[package]]
name = "craft-draw"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
dependencies = [
"craft-behavior",
"craft-color-ui",
@@ -1513,7 +1513,7 @@ dependencies = [
[[package]]
name = "craft-dxf"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
dependencies = [
"craft-codepage",
"encoding_rs",
@@ -1525,7 +1525,7 @@ dependencies = [
[[package]]
name = "craft-ecproj-format"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
dependencies = [
"serde",
"serde_json",
@@ -1535,12 +1535,12 @@ dependencies = [
[[package]]
name = "craft-eps"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
[[package]]
name = "craft-font-catalog"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
dependencies = [
"fontique",
"harfrust 0.13.3",
@@ -1555,7 +1555,7 @@ dependencies = [
[[package]]
name = "craft-font-manager"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
dependencies = [
"craft-behavior",
"craft-font-catalog",
@@ -1574,7 +1574,7 @@ dependencies = [
[[package]]
name = "craft-font-os-windows"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
dependencies = [
"windows-registry",
"windows-sys 0.61.2",
@@ -1583,7 +1583,7 @@ dependencies = [
[[package]]
name = "craft-font-store"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
dependencies = [
"cap-primitives",
"craft-atomic",
@@ -1606,12 +1606,12 @@ dependencies = [
[[package]]
name = "craft-fonts-build"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
[[package]]
name = "craft-gif"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
dependencies = [
"gif",
]
@@ -1619,7 +1619,7 @@ dependencies = [
[[package]]
name = "craft-gzip"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
dependencies = [
"flate2",
]
@@ -1627,7 +1627,7 @@ dependencies = [
[[package]]
name = "craft-host"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
dependencies = [
"bitflags 2.13.2",
"craft-i18n",
@@ -1640,7 +1640,7 @@ dependencies = [
[[package]]
name = "craft-i18n"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
dependencies = [
"brotli 9.1.3",
"brotli-decompressor 6.3.2",
@@ -1670,7 +1670,7 @@ dependencies = [
[[package]]
name = "craft-image-codecs"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
dependencies = [
"craft-dds",
"craft-jpeg",
@@ -1697,7 +1697,7 @@ dependencies = [
[[package]]
name = "craft-imaging"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
dependencies = [
"craft-behavior",
"craft-color-ui",
@@ -1715,7 +1715,7 @@ dependencies = [
[[package]]
name = "craft-jpeg"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
dependencies = [
"thiserror 2.0.21",
]
@@ -1723,7 +1723,7 @@ dependencies = [
[[package]]
name = "craft-jxl"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
dependencies = [
"brotli-decompressor 5.0.3",
"jixel",
@@ -1734,7 +1734,7 @@ dependencies = [
[[package]]
name = "craft-keymap"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
dependencies = [
"craft-host",
"craft-i18n",
@@ -1749,7 +1749,7 @@ dependencies = [
[[package]]
name = "craft-layers"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
dependencies = [
"craft-behavior",
"craft-i18n",
@@ -1763,7 +1763,7 @@ dependencies = [
[[package]]
name = "craft-menu"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
dependencies = [
"craft-behavior",
"craft-host",
@@ -1781,7 +1781,7 @@ dependencies = [
[[package]]
name = "craft-metadata"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
dependencies = [
"brotli-decompressor 6.3.2",
"chrono",
@@ -1793,7 +1793,7 @@ dependencies = [
[[package]]
name = "craft-metafile"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
dependencies = [
"encoding_rs",
"image",
@@ -1804,7 +1804,7 @@ dependencies = [
[[package]]
name = "craft-mime"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
dependencies = [
"chrono",
"craft-codepage",
@@ -1814,7 +1814,7 @@ dependencies = [
[[package]]
name = "craft-nightly"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
dependencies = [
"uds_windows",
"winsafe",
@@ -1823,7 +1823,7 @@ dependencies = [
[[package]]
name = "craft-pages"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
dependencies = [
"craft-behavior",
"craft-keymap",
@@ -1839,7 +1839,7 @@ dependencies = [
[[package]]
name = "craft-pcraft-format"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
dependencies = [
"flate2",
"serde",
@@ -1850,7 +1850,7 @@ dependencies = [
[[package]]
name = "craft-pdf"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
dependencies = [
"hayro-interpret",
"hayro-syntax",
@@ -1862,7 +1862,7 @@ dependencies = [
[[package]]
name = "craft-platform"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
dependencies = [
"async-channel",
"async-io",
@@ -1895,7 +1895,7 @@ dependencies = [
[[package]]
name = "craft-plotter"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
dependencies = [
"kurbo 0.13.1",
"thiserror 2.0.21",
@@ -1904,7 +1904,7 @@ dependencies = [
[[package]]
name = "craft-print"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
dependencies = [
"craft-behavior",
"craft-host",
@@ -1928,7 +1928,7 @@ dependencies = [
[[package]]
name = "craft-proof"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
dependencies = [
"log",
"miniz_oxide 0.9.1",
@@ -1939,7 +1939,7 @@ dependencies = [
[[package]]
name = "craft-ps"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
dependencies = [
"craft-eps",
"flate2",
@@ -1953,7 +1953,7 @@ dependencies = [
[[package]]
name = "craft-psd"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
dependencies = [
"encoding_rs",
"flate2",
@@ -1964,7 +1964,7 @@ dependencies = [
[[package]]
name = "craft-quit"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
dependencies = [
"dispatch2",
"egui",
@@ -1977,7 +1977,7 @@ dependencies = [
[[package]]
name = "craft-review"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
dependencies = [
"base64 0.23.1",
"craft-behavior",
@@ -1996,7 +1996,7 @@ dependencies = [
[[package]]
name = "craft-settings"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
dependencies = [
"craft-atomic",
"craft-host",
@@ -2013,7 +2013,7 @@ dependencies = [
[[package]]
name = "craft-stream-codecs"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
dependencies = [
"fax",
"hayro-ccitt",
@@ -2024,7 +2024,7 @@ dependencies = [
[[package]]
name = "craft-svg"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
dependencies = [
"craft-image-codecs",
"craft-xml",
@@ -2045,7 +2045,7 @@ dependencies = [
[[package]]
name = "craft-table"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
dependencies = [
"craft-behavior",
"craft-keymap",
@@ -2057,7 +2057,7 @@ dependencies = [
[[package]]
name = "craft-text"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
dependencies = [
"craft-behavior",
"craft-font-manager",
@@ -2082,7 +2082,7 @@ dependencies = [
[[package]]
name = "craft-theme"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
dependencies = [
"bitflags 2.13.2",
"craft-tracked",
@@ -2097,7 +2097,7 @@ dependencies = [
[[package]]
name = "craft-theme-store"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
dependencies = [
"craft-atomic",
"craft-behavior",
@@ -2112,7 +2112,7 @@ dependencies = [
[[package]]
name = "craft-tiff"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
dependencies = [
"serde",
"thiserror 2.0.21",
@@ -2122,7 +2122,7 @@ dependencies = [
[[package]]
name = "craft-time"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
dependencies = [
"serde",
"thiserror 2.0.21",
@@ -2131,7 +2131,7 @@ dependencies = [
[[package]]
name = "craft-timeline"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
dependencies = [
"craft-behavior",
"craft-keymap",
@@ -2146,12 +2146,12 @@ dependencies = [
[[package]]
name = "craft-tracked"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
[[package]]
name = "craft-ui"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
dependencies = [
"craft-cloud-ui",
"craft-ui-canvas",
@@ -2165,7 +2165,7 @@ dependencies = [
[[package]]
name = "craft-ui-canvas"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
dependencies = [
"craft-behavior",
"craft-i18n",
@@ -2181,7 +2181,7 @@ dependencies = [
[[package]]
name = "craft-ui-contract"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
dependencies = [
"accesskit",
"craft-behavior",
@@ -2219,7 +2219,7 @@ dependencies = [
[[package]]
name = "craft-ui-macros"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
dependencies = [
"proc-macro-crate",
"proc-macro2",
@@ -2230,7 +2230,7 @@ dependencies = [
[[package]]
name = "craft-ui-panels"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
dependencies = [
"craft-behavior",
"craft-host",
@@ -2248,7 +2248,7 @@ dependencies = [
[[package]]
name = "craft-ui-patterns"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
dependencies = [
"craft-behavior",
"craft-host",
@@ -2269,7 +2269,7 @@ dependencies = [
[[package]]
name = "craft-ui-shell"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
dependencies = [
"craft-behavior",
"craft-host",
@@ -2290,7 +2290,7 @@ dependencies = [
[[package]]
name = "craft-ui-widgets"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
dependencies = [
"craft-behavior",
"craft-host",
@@ -2309,7 +2309,7 @@ dependencies = [
[[package]]
name = "craft-update"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
dependencies = [
"base64 0.22.1",
"chrono",
@@ -2341,7 +2341,7 @@ dependencies = [
[[package]]
name = "craft-vectorcraft-format"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
dependencies = [
"flate2",
"serde",
@@ -2352,7 +2352,7 @@ dependencies = [
[[package]]
name = "craft-wayland"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
dependencies = [
"raw-window-handle",
"wayland-backend",
@@ -2362,7 +2362,7 @@ dependencies = [
[[package]]
name = "craft-web-api"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
dependencies = [
"js-sys",
"serde_json",
@@ -2373,7 +2373,7 @@ dependencies = [
[[package]]
name = "craft-win32"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
dependencies = [
"winsafe",
]
@@ -2381,7 +2381,7 @@ dependencies = [
[[package]]
name = "craft-window"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
dependencies = [
"craft-appkit",
"craft-atomic",
@@ -2413,7 +2413,7 @@ dependencies = [
[[package]]
name = "craft-xml"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
dependencies = [
"quick-xml 0.41.0",
"serde",
@@ -3772,7 +3772,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a"
[[package]]
name = "hayro-cmap"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
dependencies = [
"brotli 8.0.4",
"hayro-postscript",
@@ -3781,7 +3781,7 @@ dependencies = [
[[package]]
name = "hayro-interpret"
version = "0.7.0"
source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
dependencies = [
"bitflags 2.13.2",
"hayro-cmap",
@@ -3799,7 +3799,7 @@ dependencies = [
[[package]]
name = "hayro-jbig2"
version = "0.3.0"
source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
dependencies = [
"fearless_simd",
"hayro-ccitt",
@@ -3817,12 +3817,12 @@ dependencies = [
[[package]]
name = "hayro-postscript"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
[[package]]
name = "hayro-syntax"
version = "0.7.2"
source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
dependencies = [
"flate2",
"hayro-ccitt",
@@ -4805,7 +4805,7 @@ dependencies = [
[[package]]
name = "krilla"
version = "0.8.2"
source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
dependencies = [
"base64 0.22.1",
"bumpalo",
@@ -4962,7 +4962,7 @@ checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4"
[[package]]
name = "linesweeper"
version = "0.5.0"
source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
dependencies = [
"arrayvec",
"kurbo 0.13.1",
@@ -8573,7 +8573,6 @@ version = "0.25.1"
dependencies = [
"craft-affinity",
"craft-image-codecs",
"crc32fast",
"proptest",
"vectorcraft-affinity",
]
+38 -38
View File
@@ -10,51 +10,51 @@ license = "MIT OR Apache-2.0"
rust-version = "1.95"
[workspace.dependencies]
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" }
craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" }
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0", default-features = false, features = ["interpret", "write"] }
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" }
craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" }
# 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" }
craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" }
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" }
# 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 = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" }
craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" }
# `.pcraft` documents: their manifest, full-size composite, preview, layer pixels and ICC profile.
craft-doc = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d", features = ["pcraft-pixels"] }
craft-doc = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0", features = ["pcraft-pixels"] }
# Native Affinity documents (craft-libs#914).
craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" }
# Bounded CDR (v1-v27) and CMX (32-bit) reader (craft-libs#778).
craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" }
# SVG parsing, limits, SVGZ and writer (craft-libs#778).
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d", features = ["tree"] }
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0", features = ["tree"] }
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" }
# EPS container, previews, ASCII85 and DSC comments (craft-libs#778).
craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" }
# DXF tags, reader and writer (craft-libs#778, #926, #927).
craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" }
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" }
# WMF, EMF and EMF+ reader (craft-libs#778).
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" }
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" }
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" }
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" }
craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" }
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" }
craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0", default-features = false, features = ["read", "write"] }
craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" }
craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" }
craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" }
craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" }
# 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 = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
craft = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" }
# 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 = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
craft-color-ui = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" }
craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" }
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" }
# Nightly profile isolation, launch protocol, and security fence.
craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" }
craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" }
# internal
vectorcraft-geom = { path = "crates/geom" }
vectorcraft-color = { path = "crates/color" }
@@ -194,13 +194,13 @@ lto = "thin"
codegen-units = 1
[patch.crates-io]
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" }
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" }
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" }
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" }
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" }
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" }
krilla = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" }
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" }
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" }
+2 -2
View File
@@ -233,8 +233,8 @@ VectorCraft is under active development. [**ROADMAP.md**](ROADMAP.md) has the st
and what's next; [`docs/target-app-parity.md`](docs/target-app-parity.md) the full parity assessment and
[`docs/gaps.md`](docs/gaps.md) the ranked list of what's missing.
**Where we are (2026-10-10): alpha.** About 88% of core menu items, tools, effects and formats exist
(92.5% of menu items do something), feature depth is ~75%, and we estimate ~65% ready for real work for a mainstream illustrator (~62% across all tracked features): everyday
**Where we are (2026-11-30): alpha.** About 96% of core menu items, tools, effects and formats exist
(99.9% of menu items do something), feature depth is ~79%, and we estimate ~65% ready for real work for a mainstream illustrator (~67% across all tracked features): everyday
vector illustration is close to usable: drawing and path tools,
Pathfinder and Shape Builder, paint, gradients, appearance and transparency, type with styles, threading and Hebrew/Arabic bidirectional layout, and
files (SVG, PDF and PDF-compatible `.ai` with PDF/X, legacy version 7 `.ai` keeping layers, groups and type, EPS, DXF, EMF/WMF, raster formats, PSD out, PSD/PSB opened with their layers and placed as their merged image, JPEG XL in, Print, Package).
+32 -29
View File
@@ -10,7 +10,7 @@ control channel. This page is the summary; the evidence is in [`docs/target-app-
and the work list in [`docs/gaps.md`](docs/gaps.md).
**Why alpha:** the core workflows exist end to end (drawing and path editing, Pathfinder, paint and appearance,
type, SVG/PDF/EPS, print, export) and feature depth is ~75%, but a professional can't yet switch: Illustrator's
type, SVG/PDF/EPS, print, export) and feature depth is ~79%, but a professional can't yet switch: Illustrator's
own `.ai` files open with a wrong layer structure in real cases and are saved back with an editing copy that
keeps live effects only on paths, compound paths and groups that qualify (at most a fill and a stroke, a non-zero fill rule when filled, no large canvas) and whose appearance and effects the art-style writer supports (see [docs/file-format-parity.md](docs/file-format-parity.md)), and writes live objects as their art, the interaction details have never been checked side by side, and some machines fail to start the
app. Beta needs those closed (the beta list in [gaps.md](docs/gaps.md)). It passes the core-workflow
@@ -24,8 +24,8 @@ blocking it ([Alpha gate](docs/roadmap.md#alpha-gate)).
| | Value | Kind |
|---|---|---|
| **Feature breadth** (Illustrator's menu items, tools, effects, formats exist) | **~88%** | measured in part: menu items 717/719 wired (99.7%), tools 89/92, Illustrator effects 46/50, Photoshop effects 57/57, 3D 4/4 (initial types, no materials) |
| **Feature depth** (weighted by use, scored by behaviour) | **~75%** | estimated |
| **Feature breadth** (Illustrator's menu items, tools, effects, formats exist) | **~96%** | measured in part: menu items 815/816 wired (99.9%), tools 91/92, Illustrator effects 50/50, Photoshop effects 57/57, 3D 4/4 plus 3 Classic (initial types, graphics on the Materials page (#6960), no base materials) |
| **Feature depth** (weighted by use, scored by behaviour) | **~79%** | estimated |
| **To beta** | **~170–270 h** one agent · ~50–80 h with 4–6 agents | estimated |
| **To full parity** | **~360–590 h** one agent · ~95–165 h with 4–6 agents | estimated |
@@ -33,9 +33,9 @@ blocking it ([Alpha gate](docs/roadmap.md#alpha-gate)).
| Audience | Ready % | Opus 5.5 agent hours to ~95% (one agent) | With 4–6 agents | Work that dominates |
|---|---:|---:|---:|---|
| **Full Illustrator** (ready for real work; decides the stage) | **~62%** (57–67%) | **~340–560 h** | ~95–160 h | the mainstream work below, plus 3D (50–85 h), raster effects (23–39 h), advanced type (20–28 h), generative AI (30–60 h), localization (50–85 h) and ecosystem |
| **Full Illustrator** (ready for real work; decides the stage) | **~67%** (62–72%) | **~340–560 h** | ~95–160 h | the mainstream work below, plus 3D (50–85 h), raster effects (23–39 h), advanced type (20–28 h), generative AI (30–60 h), localization (50–85 h) and ecosystem |
| **Mainstream illustrator** | **~65%** (60–70%) | **~230–380 h** | ~65–110 h | the interaction-fidelity pass (60–90 h), hardening and QA (30–50 h), stability (20–35 h), performance budgets (15–25 h), `.ai` exchange (10–20 h), the remaining depth of the everyday areas |
| **Essentials user** | **~75%** (70–80%) | **~60–105 h** | ~25–45 h | launch and stability on Windows (20–35 h), in-app help and onboarding (8–15 h), basic QA (10–15 h), Shape Builder depth (4–8 h; #937's reproduced case is fixed, unconfirmed on the reporter's file), UI polish |
| **Essentials user** | **~77%** (72–82%) | **~60–105 h** | ~25–45 h | launch and stability on Windows (20–35 h), the Windows print crashes (#8021, #9261), help articles and onboarding (8–15 h), basic QA (10–15 h), Shape Builder depth (4–8 h; #937's reproduced case is fixed, unconfirmed on the reporter's file), UI polish |
Hours are Opus 5.5 agent wall-clock hours, calibrated from this repo's merged-PR timestamps (e.g. 0.7–1.2 h per
Photoshop-style filter, ~0.8 h per medium feature); see [calibration](docs/target-app-parity.md#calibration).
@@ -46,15 +46,15 @@ everything is measured from our code against Illustrator's public documentation.
| Dimension | % | One agent (h) | Doc |
|---|---:|---:|---|
| Features (depth) | 75% | 220–360 | [target-app-parity.md](docs/target-app-parity.md) |
| UI/UX fidelity | 55% | 70–110 | [ui-parity.md](docs/ui-parity.md) |
| Features (depth) | 79% | 220–360 | [target-app-parity.md](docs/target-app-parity.md) |
| UI/UX fidelity | 60% | 70–110 | [ui-parity.md](docs/ui-parity.md) |
| File formats | 75% | 15–30 | [file-format-parity.md](docs/file-format-parity.md) |
| Hardware (GPU, pen, touch, displays) | 35% | 25–45 | [hardware-parity.md](docs/hardware-parity.md) |
| Localization (12 key languages) | 74% (measured) | 50–85 | [localization-parity.md](docs/localization-parity.md) |
| Hardware (GPU, pen, touch, displays) | 45% | 25–45 | [hardware-parity.md](docs/hardware-parity.md) |
| Localization (12 key languages) | 87% (measured) | 50–85 | [localization-parity.md](docs/localization-parity.md) |
| Performance | ~60% | 15–25 | [gaps.md › G15](docs/gaps.md#g15-performance-budgets-and-a-gpu-renderer) |
| Stability | ~60% | 30–50 | [gaps.md › G10](docs/gaps.md#g10-launch-and-stability-on-real-machines) |
| Platforms | 80% | 15–25 | [gaps.md › G8](docs/gaps.md#g8-hardening-at-scale) |
| Ecosystem and plug-ins | 15% | 30–60 | [gaps.md › G17](docs/gaps.md#g17-ecosystem-third-party-plug-ins) |
| Stability | ~55% | 30–50 | [gaps.md › G10](docs/gaps.md#g10-launch-and-stability-on-real-machines) |
| Platforms | 82% | 15–25 | [gaps.md › G8](docs/gaps.md#g8-hardening-at-scale) |
| Ecosystem and plug-ins | 30% | 30–60 | [gaps.md › G17](docs/gaps.md#g17-ecosystem-third-party-plug-ins) |
| AI features (generative) | 0% | 30–60 + owner decision | [gaps.md › G18](docs/gaps.md#g18-generative-ai-features) |
| Agent automation | beyond Illustrator | — | [mcp.md](docs/mcp.md) |
@@ -64,26 +64,26 @@ The dimension hours overlap (feature rows hold some UI, format and AI work), so
| Area | % | One agent (h) |
|---|---:|---:|
| Selection, transform & align | 85% | 4–6 |
| Drawing tools | 85% | 8–13 |
| Path operations, Pathfinder, Shape Builder, Live Paint | 80% | 4–8 |
| Selection, transform & align | 86% | 4–6 |
| Drawing tools | 88% | 8–13 |
| Path operations, Pathfinder, Shape Builder, Live Paint | 85% | 4–8 |
| Colour, swatches, gradients, patterns, mesh, recolor | 92% | 4–7 |
| Strokes, brushes, width profiles | 88% | 8–15 |
| Strokes, brushes, width profiles | 90% | 8–15 |
| Appearance, transparency, graphic styles, masks | 97% | 1–2 |
| Live vector effects | 85% | 4–8 |
| Raster effects (Effect Gallery) — [effects-parity.md](docs/effects-parity.md) | 88% | — |
| 3D and Materials | ~25% | 30–55 |
| Type core — [type-parity.md](docs/type-parity.md) | 80% | 14–19 |
| Type advanced (CJK, spelling, Touch Type) | 50% | 20–28 |
| Symbols, blends, envelopes, Repeat, perspective | 88% | 4–7 |
| Image Trace, graphs, image tools | 75% | 5–8 |
| Layers, artboards, document setup | 78% | 5–8 |
| View & navigation | 70% | 9–14 |
| Live vector effects | 90% | 4–8 |
| Raster effects (Effect Gallery) — [effects-parity.md](docs/effects-parity.md) | 55% | — |
| 3D and Materials | ~35% | 30–55 |
| Type core — [type-parity.md](docs/type-parity.md) | 83% | 14–19 |
| Type advanced (CJK, spelling, Touch Type) | 60% | 20–28 |
| Symbols, blends, envelopes, Repeat, perspective | 90% | 4–7 |
| Image Trace, graphs, image tools | 78% | 5–8 |
| Layers, artboards, document setup | 82% | 5–8 |
| View & navigation | 80% | 9–14 |
| Guides, grids, smart guides, snapping | 80% | 4–7 |
| File formats — [file-format-parity.md](docs/file-format-parity.md) | 75% | 10–20 |
| Export for Screens, Asset Export, slices | 85% | 2–4 |
| Export for Screens, Asset Export, slices | 87% | 2–4 |
| Print, colour management, separations | 80% | 2–4 |
| Automation (Actions, Variables, scripting) | 60% | 8–14 |
| Automation (Actions, Variables, scripting) | 80% | 8–14 |
| UI chrome (panels, Properties, preferences) | 80% | 13–20 |
| Libraries, Links, Package | 82% | 2–3 |
| Generative AI | 0% | 30–60 |
@@ -95,7 +95,7 @@ Weights, evidence and the missing items per area: [target-app-parity.md](docs/ta
| Language | Code | Status | Translated |
|---|---|---|---:|
| English | `en` | full | 100% |
| Simplified Chinese | `zh-hans` | partial (messages in English) | 85% |
| Simplified Chinese | `zh-hans` | partial (messages translated, #2578) | 85% |
| Spanish | `es` | full | 100% |
| Hindi | `hi` | catalog complete; machine-assisted draft, native review pending | complete under the scanner |
| Gujarati | `gu` | 4,673 contributor-reviewed catalog rows; 11 corrections applied to the 387 additions | menus and dialogs; status/error messages partial |
@@ -119,7 +119,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
1. **Interaction-fidelity pass** (G1), tool by tool from [ui-parity.md](docs/ui-parity.md): 60–90 h.
2. **`.ai` files from real users** (G9): layer structure, guides, speed: 10–20 h.
3. **Launch and stability on real machines** (G10): 20–35 h.
4. **Core-tool correctness** (G11: the unit preference reverting to points, #864, SVG export units fixed; a Transform effect in a fill's or stroke's own effects, #885; Shape Builder regions and Asset Export borders are fixed): 6–13 h.
4. **Core-tool correctness** (G11: the unit preference reverting to points, #864, SVG export units fixed; a Transform effect in a fill's or stroke's own effects (#5221, #885), Shape Builder regions and Asset Export borders are fixed): 6–13 h.
5. **Then:** type core and advanced type (G4), the Illustrator 2026 additions (G13), 3D (G3). The Effect Gallery's filter thumbnails and in-dialog preview are in (G2).
## Progress log
@@ -160,11 +160,14 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
- 2026-11-11: Pattern libraries: Patterns › Grit Textures, a second built-in pattern library, holds eight seamless black textures (Fine Grain, Coarse Grit, Sand, Speckle, Stipple, Scratches, Sparse Flecks and Dense Flecks) on tiles of 18 to 36 pt, each drawn the same way every time; marks that reach past a tile edge continue on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged.
- 2026-11-11: Pattern libraries: Patterns › Optical Effects, a third built-in pattern library, of VectorCraft's own designs, holds eight black wave, moiré and op-art tiles (Sine Bands, Ripple Lines, Interference Rings, Offset Rings, Warped Checks, Pinched Stripes, Chevron Pulse and Radiating Lenses) of 32 to 48 pt, each drawn the same way every time; each tile is one period of its design, and art that reaches past a tile edge continues on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged.
- 2026-11-01: Find Nearest Swatch joins the Color Effects add-on (Object › Plug-ins › Color Effects): for each colour of the selection, the closest swatches of the document, a built-in library or a library or colour book the user loaded, with their CIEDE2000 difference; Apply gives each colour its nearest swatch as one undo step, linking global and spot swatches and adding a library's to the document first, so a process colour becomes the closest spot colour (`addon.color.nearestSwatch`, `addon.color.applyNearestSwatch`, #4923).
- 2026-11-29: Randomize Fill Colors joins the Color Effects add-on (Object › Plug-ins › Color Effects): each selected filled path, compound path and live compound shape, inside groups and graph series too, gets a fill color of its own at random: any color, tints of a global or spot swatch, or grays between a minimum and a maximum percent, with a seed that repeats the result and Preview, as one undo step (`addon.color.randomFill`); art on a locked artboard keeps its fill (also when `ids` names it), except new art made there while it is still selected.
- 2026-11-01: Expand Dashes into Paths joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): each selected path's dashed stroke becomes separate open paths, one per dash, laid out exactly as the stroke draws them (pattern, offset, Align Dashes to Corners and Path Ends), each keeping the stroke with the dashes off, so the gaps are real gaps for cutters and plotters, as one undo step (`addon.pathtools.expandDashes`, #4922).
- 2026-11-01: Randomize Opacity joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): each selected object gets its own opacity at random between a minimum and a maximum percent, with a seed that repeats the result, as one undo step (`addon.arrange.randomizeOpacity`, #4925).
- 2026-11-01: Sort Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects are sorted by width, height, area, position, opacity or stacking order (small to large, large to small or at random) and take another of those in that order, trading their values or stepping them evenly, as one undo step (`addon.arrange.sort`, #4917).
- 2026-11-29: Mark Bounds of Each joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): each selected object gets its own inward corner marks, or a rectangle, on its geometric or visual bounds, stroked in the color and weight given, stacked directly above it; clip groups are measured by their clipping path. A dialog with Preview, one undo step (`addon.arrange.markBounds`). A VectorCraft addition: headline numbers unchanged.
- 2026-11-29: Match Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the other selected objects take the width, the height or both, the bounding-box angle and the stacking place of the key object, or of the top or the bottom selected object, about a reference point, with Preview, as one undo step (`addon.arrange.match`). A VectorCraft addition: headline numbers unchanged.
- 2026-11-29: Offset Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects are chained one after another in a row or a column with a set gap (negative to overlap them), in stacking order or by position, either way; the first stays in place and the others move only along the row or column, as one undo step (`addon.arrange.offset`). A VectorCraft addition: headline numbers unchanged.
- 2026-11-29: Group by Row joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects whose visual bounds overlap from top to bottom go into one group for each row (or, by column, from left to right), within their own layer or group and artboard, at the stacking place of their frontmost member; an object alone in its row stays as it is. One undo step, with a previewed dialog (`addon.arrange.groupRows`). A VectorCraft addition: headline numbers unchanged.
- 2026-11-15: Tangent Circle joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the circles that touch two selected paths or compound paths at a set radius, or three of them (up to eight for three circles), touching each outline without crossing it; circles, rotated ellipses and other paths alike. A dialog that previews every circle or one picked by number, the current paint, one undo step (`addon.pathtools.tangentCircle`). A VectorCraft addition: headline numbers unchanged.
- 2026-11-17: Add Bounding Rectangle and Add Bounding Circle join the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): a live rectangle on the selection's geometric bounding box, or the smallest live circle that holds its outlines, around the whole selection or around each object, with the current paint and one undo step; the menu items open a dialog with Offset, One per Object and Preview (`addon.pathtools.boundingRectangle`, `addon.pathtools.boundingCircle`, #6966). A VectorCraft addition: headline numbers unchanged.
- 2026-11-22: Add Inscribed Circle joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the largest live circle inside each selected closed path or compound path, in the area it fills under its fill rule, with the current paint and one undo step (`addon.pathtools.inscribedCircle`, #6966). A VectorCraft addition: headline numbers unchanged.
+1 -1
View File
@@ -28,7 +28,7 @@ egui_extras = { workspace = true }
# `wgpu` pulls egui-wgpu's defaults: WebGPU plus the WebGL2 fallback.
eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit"] }
# The page command API (storytold/craft-libs#413): the request plumbing behind window.vectorcraft.
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d", version = "0.1.0" }
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0", version = "0.1.0" }
wasm-bindgen = "0.2"
serde_json = { workspace = true }
+27 -4
View File
@@ -3,8 +3,8 @@
//! mark for [`STALL`] while inside a stage of its frame, the thread writes what the app knows to the
//! log (`logs/vectorcraft.log`) and to `logs/hang-report-<process id>.txt`: the stage, a clipboard
//! call in progress, the last commands, the last frames' times, the platform, the window system, the
//! graphics processor and the present mode the app asked for, and how long the session has run with
//! how many documents open. The process holds a lock on the file until the interface thread answers
//! graphics processor, its driver when known, and the present mode the app asked for, and how long
//! the session has run with how many documents open. The process holds a lock on the file until the interface thread answers
//! again; then the log says after how long and the file is removed. A file nobody holds at a later
//! launch was left by a session that was closed while it did not answer, and a locked one belongs to
//! another instance that is stalled now and is left alone. That launch writes the report to the log,
@@ -113,6 +113,8 @@ pub struct Facts {
pub flatpak: bool,
/// The graphics processor the window draws with.
pub graphics: Option<String>,
/// The active graphics driver's identity, when the backend reports it.
graphics_driver: Option<String>,
/// The present mode and frame queue the app asked the window surface for.
pub surface: String,
}
@@ -128,14 +130,29 @@ impl Facts {
session_type: value("XDG_SESSION_TYPE"),
flatpak: flatpak_info || env("FLATPAK_ID").is_some_and(|v| !v.is_empty()),
graphics,
graphics_driver: None,
surface,
}
}
#[cfg(any(feature = "wgpu", test))]
pub fn with_graphics_driver(mut self, driver: &str, info: &str) -> Facts {
// D3D12 reports 0.0.0.0 when the driver version could not be read.
let mut fields = [driver, info].map(clean).into_iter().filter(|value| !value.is_empty() && value != "0.0.0.0");
self.graphics_driver = fields.next().map(|mut detail| {
if let Some(info) = fields.next().filter(|info| info != &detail) {
detail.push_str(" / ");
detail.push_str(&info);
}
detail
});
self
}
/// The facts as report lines.
pub fn lines(&self) -> String {
let or_unknown = |v: &Option<String>| v.clone().unwrap_or_else(|| "unknown".to_string());
format!(
let mut lines = format!(
"VectorCraft {} on {} {}\nWindow system: {}; desktop: {}; session type: {}; Flatpak: {}\nGraphics: {}; {}\n",
vectorcraft_ui_egui::os_window::version(),
std::env::consts::OS,
@@ -146,7 +163,13 @@ impl Facts {
if self.flatpak { "yes" } else { "no" },
or_unknown(&self.graphics),
self.surface,
)
);
if let Some(driver) = &self.graphics_driver {
lines.push_str("Graphics driver: ");
lines.push_str(driver);
lines.push('\n');
}
lines
}
}
+19
View File
@@ -279,3 +279,22 @@ fn troubleshooting_info_holds_both_sessions_reports() {
assert!(text.contains("(it was closed while it did not answer):\nVectorCraft hang report, last session\n"));
assert!(text.contains("Recent commands, oldest first: none"));
}
#[test]
fn troubleshooting_info_distinguishes_drivers_on_the_same_adapter() {
let mut shared = shared(None);
let beacon = Beacon::new();
for (driver, info, expected) in [
(" 32.0.16.1088 ", "", Some("32.0.16.1088")),
("32.0.16.2124", "", Some("32.0.16.2124")),
("Mesa\nRADV", "Mesa 25.2", Some("MesaRADV / Mesa 25.2")),
("Mesa", "Mesa", Some("Mesa")),
("0.0.0.0", "", None),
("", "", None),
] {
shared.facts = facts().with_graphics_driver(driver, info);
let text = troubleshooting(&shared, &beacon, UNIX_EPOCH);
assert!(text.contains("Graphics: Test GPU"), "the adapter description is still in the report");
assert_eq!(text.lines().find_map(|line| line.strip_prefix("Graphics driver: ")), expected);
}
}
+23 -9
View File
@@ -432,6 +432,12 @@ fn opens_through_xwayland(pref: Option<&str>) -> bool {
true
}
/// The docking runtime needs the backend the desktop window is opened on.
fn desktop_shell_info(detected: Backend, forced_to_x11: bool) -> ShellInfo {
let backend = if forced_to_x11 { Backend::X11 } else { detected };
ShellInfo::current().backend(backend)
}
/// The nightly channel this build is, as a string for the log.
fn channel_name() -> &'static str {
match build_flavor::COMPILED {
@@ -718,10 +724,10 @@ fn main() -> std::process::ExitCode {
// A window forced onto XWayland runs on X11, whose window manager draws the frame: the
// framework decides the frame for that backend, from the platform, `VECTORCRAFT_TITLEBAR` and
// Preferences › User Interface › System Title Bar.
let shell_info = if forced_to_x11 { ShellInfo::current().backend(Backend::X11) } else { ShellInfo::current() };
let shell_info = desktop_shell_info(Backend::from_env(), forced_to_x11);
// On Wayland with no cursor theme, the system pointer stays and no tool cursor is painted
// beside it (#2450, #5311).
let wayland = !forced_to_x11 && Backend::from_env() == Backend::Wayland;
let wayland = shell_info.backend == Backend::Wayland;
let caps = cursor_theme::shell_caps(shell_info.caps, wayland, cursor_theme::theme_missing);
let shell_info = shell_info.caps(caps);
let titlebar_pref =
@@ -981,14 +987,22 @@ fn main() -> std::process::ExitCode {
.map(|_| (format!("{:?}", requested_surface.present_mode), requested_surface.desired_maximum_frame_latency));
#[cfg(not(feature = "wgpu"))]
let surface = None;
let facts = hang_watch::Facts::new(
|name| std::env::var(name).ok(),
std::path::Path::new("/.flatpak-info").exists(),
hang_watch::window_system(winit_window.as_deref()),
app.graphics_adapter.clone(),
hang_watch::surface(surface),
);
#[cfg(feature = "wgpu")]
let facts = if let Some(rs) = &cc.wgpu_render_state {
let info = rs.adapter.get_info();
facts.with_graphics_driver(&info.driver, &info.driver_info)
} else {
facts
};
let hang = std::sync::Arc::new(hang_watch::Shared {
facts: hang_watch::Facts::new(
|name| std::env::var(name).ok(),
std::path::Path::new("/.flatpak-info").exists(),
hang_watch::window_system(winit_window.as_deref()),
app.graphics_adapter.clone(),
hang_watch::surface(surface),
),
facts,
started: std::time::Instant::now(),
last: std::sync::Mutex::new(None),
previous: previous_hang.clone(),
+13
View File
@@ -1,5 +1,18 @@
use super::*;
#[test]
fn desktop_shell_reports_the_backend_selected_for_docking() {
let wayland = desktop_shell_info(Backend::Wayland, false);
assert_eq!(wayland.backend, Backend::Wayland);
assert!(!wayland.window_positions(), "native Wayland keeps palettes inside the window");
for (detected, force_x11) in [(Backend::Wayland, true), (Backend::X11, false)] {
let x11 = desktop_shell_info(detected, force_x11);
assert_eq!(x11.backend, Backend::X11);
assert!(x11.window_positions(), "X11 and XWayland can place native palettes");
}
}
/// The saved UI state of an old `ui.json`, as the legacy import reads it.
fn legacy_ui(bytes: &[u8]) -> Option<vectorcraft_ui_egui::UiState> {
vectorcraft_ui_egui::parse_legacy(bytes).ok().map(|(settings, _)| settings.ui)
+1 -1
View File
@@ -1,4 +1,4 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
<path d="M2 4.8L18.7 1.4L22.6 21.6L4.8 18.2Z"/>
<rect x="0.8" y="3.6" width="2.4" height="2.4" fill="currentColor"/>
<rect x="17.5" y="0.2" width="2.4" height="2.4" fill="currentColor"/>

Before

Width:  |  Height:  |  Size: 525 B

After

Width:  |  Height:  |  Size: 527 B

-1
View File
@@ -19,7 +19,6 @@ craft-affinity = { workspace = true }
[dev-dependencies]
proptest = { workspace = true }
# The tests build containers and decode previews.
crc32fast = { workspace = true }
craft-image-codecs = { workspace = true }
# tests/it's `import_limits`, `outline_limits` and `text` modules need `synth`, also when this crate
# is tested without vectorcraft-engine (`cargo xtask ci shard`).
+73 -8
View File
@@ -41,6 +41,70 @@ fn source(bytes: &[u8]) -> Vec<u8> {
block.bytes(block.root, b"Data").unwrap().to_vec()
}
/// The fixture's one tiled bitmap read straight from its archive entries, interleaved: RGBA8 for
/// RGBA layers (16-bit samples scaled to 8 bits with rounding) and C, M, Y, K, alpha for CMYK.
/// Each channel is a grid of 256-byte × 256-row tiles in row-major order; state 2 is a tile of
/// 0xFF, state 4 a stored tile (the next `Idx<c>` entry), and any other state a tile of zeros.
fn tiled_pixels(bytes: &[u8]) -> (u32, u32, Vec<u8>) {
const TILE: usize = 256;
let mut archive = Archive::open(bytes, Limits::default()).unwrap();
let doc = stream::parse(&archive.read("doc.dat").unwrap()).unwrap();
// The bitmap the image layer (`ImgN`) holds as `Bitm`; the document's other bitmaps are masks.
let bitmaps: Vec<usize> = (0..doc.objects.len())
.filter(|&o| doc.is(o, b"ImgN"))
.filter_map(|o| doc.obj(o, b"Bitm"))
.filter(|&b| doc.is(b, b"DyBm") && doc.field(b, b"Sta1").is_some())
.collect();
assert_eq!(bitmaps.len(), 1, "one tiled image bitmap");
let bitmap = bitmaps[0];
let width = usize::try_from(doc.int(bitmap, b"BmpW").unwrap()).unwrap();
let height = usize::try_from(doc.int(bitmap, b"BmpH").unwrap()).unwrap();
let (channels, bps) = match doc.enumeration(bitmap, b"Frmt").unwrap().0 {
0 => (4, 1),
1 => (4, 2),
4 => (5, 1),
other => panic!("format {other}"),
};
let row = width * bps;
let across = row.div_ceil(TILE);
let mut planes = Vec::new();
for c in 1..=channels {
let digit = b'0' + c as u8;
let Some(stream::Value::Array(states)) = doc.field(bitmap, &[b'S', b't', b'a', digit]) else { panic!("states of channel {c}") };
let mut stored = doc.objs(bitmap, &[b'I', b'd', b'x', digit]).into_iter();
let mut plane = vec![0u8; row * height];
for (t, state) in states.iter().enumerate().take(across * height.div_ceil(TILE)) {
let tile: Vec<u8> = match state {
stream::Value::UInt(2) => vec![0xFF; TILE * TILE],
stream::Value::UInt(4) => {
let name = doc.entry(stored.next().unwrap(), b"Data").unwrap().to_string();
let data = archive.read(&name).unwrap();
assert_eq!(data.len(), TILE * TILE, "{name}");
data
}
_ => continue,
};
let (ox, oy) = ((t % across) * TILE, (t / across) * TILE);
for y in oy..(oy + TILE).min(height) {
for x in ox..(ox + TILE).min(row) {
plane[y * row + x] = tile[(y - oy) * TILE + x - ox];
}
}
}
planes.push(plane);
}
let sample = |c: usize, i: usize| -> u8 {
if bps == 1 {
planes[c][i]
} else {
let v = u32::from(u16::from_le_bytes([planes[c][2 * i], planes[c][2 * i + 1]]));
u8::try_from((v * 255 + 32767) / 65535).unwrap()
}
};
let pixels = (0..width * height).flat_map(|i| (0..channels).map(move |c| (c, i))).map(|(c, i)| sample(c, i)).collect();
(u32::try_from(width).unwrap(), u32::try_from(height).unwrap(), pixels)
}
#[test]
fn source_backed_tiles_retain_the_embedded_jpeg_pixels() {
let Some((bytes, doc, images)) = read_fixture("patchy-embedded-jpeg.af") else { return };
@@ -68,8 +132,8 @@ fn lazy_placed_images_keep_the_original_encoded_bytes() {
#[test]
fn eight_and_sixteen_bit_channels_retain_the_same_pixel_pattern() {
let Some((_, doc8, images8)) = read_fixture("patchy-rgba8.af") else { return };
let (_, doc16, images16) = read_fixture("patchy-rgba16.af").unwrap();
let Some((bytes8, doc8, images8)) = read_fixture("patchy-rgba8.af") else { return };
let (bytes16, doc16, images16) = read_fixture("patchy-rgba16.af").unwrap();
assert!(doc8.warnings.is_empty());
assert!(doc16.warnings.is_empty());
assert_eq!(images8.len(), 1);
@@ -80,13 +144,13 @@ fn eight_and_sixteen_bit_channels_retain_the_same_pixel_pattern() {
assert_eq!(&pixels[..4], &[0, 0, 0, 128]);
assert!(pixels.as_chunks::<4>().0.iter().any(|p| p[3] < 255));
assert!(pixels.as_chunks::<4>().0.iter().any(|p| p[0] != p[1]));
// Frozen pixel-retention baseline, including every alpha sample. It is not a render oracle.
assert_eq!(crc32fast::hash(pixels), 0xc8ee4dc1);
assert_eq!(tiled_pixels(&bytes8), (64, 48, pixels.clone()));
assert_eq!(tiled_pixels(&bytes16), (64, 48, pixels.clone()), "16-bit samples scaled to 8 bits");
}
#[test]
fn rotated_scaled_pixels_keep_the_full_affine_transform() {
let Some((_, doc, images)) = read_fixture("patchy-transform.af") else { return };
let Some((bytes, doc, images)) = read_fixture("patchy-transform.af") else { return };
assert!(doc.warnings.is_empty());
assert_eq!(images.len(), 1);
assert_eq!((images[0].width, images[0].height), (80, 60));
@@ -97,18 +161,19 @@ fn rotated_scaled_pixels_keep_the_full_affine_transform() {
let Pixels::Rgba8(pixels) = &images[0].pixels else { panic!() };
assert_eq!(pixels.len(), 80 * 60 * 4);
assert!(pixels.as_chunks::<4>().0.iter().all(|p| p[3] == 255));
assert_eq!(crc32fast::hash(pixels), 0x3720a442);
assert_eq!(tiled_pixels(&bytes), (80, 60, pixels.clone()));
}
#[test]
fn cmyk_pixels_stay_cmyk_and_lab_losses_are_reported() {
// CMYK layers keep their inks for the importer to convert through a colour profile.
let Some((_, cmyk, images)) = read_fixture("patchy-cmyk.af") else { return };
let Some((bytes, cmyk, images)) = read_fixture("patchy-cmyk.af") else { return };
assert_eq!(images.len(), 1);
assert_eq!((images[0].width, images[0].height), (64, 48));
let Pixels::Cmyka8(pixels) = &images[0].pixels else { panic!() };
assert_eq!(pixels.len(), 64 * 48 * 5);
assert_eq!(crc32fast::hash(pixels), 0x56b1f659);
assert_eq!(tiled_pixels(&bytes), (64, 48, pixels.clone()));
assert!(pixels.as_chunks::<5>().0.iter().any(|p| p[0] != p[3]), "inks differ between channels");
assert!(cmyk.warnings.is_empty(), "{:?}", cmyk.warnings);
assert_eq!(cmyk.cmyk_profile, None, "this file embeds no profile");
let (_, lab, images) = read_fixture("patchy-lab.af").unwrap();
@@ -1,33 +1,33 @@
affinity3-mexican-guy.af dpi=300;spreads=1;model_crc32=32b7cf3f;counts={"depth": 8, "fills": 169, "gradients": 0, "groups": 23, "nodes": 283, "opacity": 1, "segments": 1491, "shapes": 260, "strokes": 114, "subpaths": 264};boards=[];fonts={};warnings=["blur effects (left out) (156×)"]
affinity3-mexican-man.af dpi=300;spreads=1;model_crc32=c10daaea;counts={"depth": 7, "fills": 277, "gradients": 2, "groups": 29, "nodes": 903, "segments": 3225, "shapes": 874, "strokes": 540, "subpaths": 881};boards=[];fonts={};warnings=["blur effects (left out) (244×)"]
affinity3-mexican-woman.af dpi=300;spreads=1;model_crc32=3bc13374;counts={"depth": 9, "fills": 527, "gradients": 0, "groups": 28, "nodes": 595, "segments": 3562, "shapes": 567, "strokes": 60, "subpaths": 570};boards=[];fonts={};warnings=["blur effects (left out) (278×)"]
affinity3-playing-cards.af dpi=300;spreads=1;model_crc32=bc0c838d;counts={"depth": 5, "fills": 363, "gradients": 0, "groups": 758, "nodes": 1350, "segments": 4864, "shapes": 592, "strokes": 17, "subpaths": 656};boards=[];fonts={};warnings=["blur effects (left out) (309×)", "brush strokes (imported as plain strokes)"]
patchy-adjust-curves.af dpi=72;spreads=1;model_crc32=36ab962f;counts={"depth": 1, "images": 1, "nodes": 2, "unsupported": 1};boards=[];fonts={};warnings=["adjustment layers"]
patchy-adjust-hsl.af dpi=72;spreads=1;model_crc32=e2eac05e;counts={"depth": 1, "images": 1, "nodes": 2, "unsupported": 1};boards=[];fonts={};warnings=["adjustment layers"]
patchy-artboards.af dpi=72;spreads=1;model_crc32=0037a28e;counts={"artboards": 2, "depth": 2, "fills": 2, "gradients": 0, "nodes": 4, "segments": 7, "shapes": 2, "strokes": 0, "subpaths": 2};boards=["board-a:0.0000,0.0000,80.0000,60.0000", "board-b:100.0000,10.0000,160.0000,70.0000"];fonts={};warnings=[]
patchy-blend-affinity.af dpi=72;spreads=1;model_crc32=8497c917;counts={"depth": 2, "fills": 8, "gradients": 0, "images": 1, "layers": 1, "nodes": 10, "segments": 24, "shapes": 8, "strokes": 0, "subpaths": 8};boards=[];fonts={};warnings=["an unknown blend mode (imported as Normal) (2×)"]
patchy-cmyk.af dpi=72;spreads=1;model_crc32=56754ce9;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[]
patchy-dpi300.af dpi=300;spreads=1;model_crc32=2561f9d3;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[]
patchy-embedded-jpeg.af dpi=72;spreads=1;model_crc32=ab4b6fbf;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[]
patchy-fx-blur.af dpi=72;spreads=1;model_crc32=29b5083b;counts={"depth": 1, "images": 2, "nodes": 2};boards=[];fonts={};warnings=["blur effects (left out) (2×)"]
patchy-fx-gradient.af dpi=72;spreads=1;model_crc32=96cd10be;counts={"depth": 1, "images": 3, "nodes": 3};boards=[];fonts={};warnings=[]
patchy-fx.af dpi=72;spreads=1;model_crc32=7c8d4d20;counts={"depth": 1, "images": 5, "nodes": 5};boards=[];fonts={};warnings=[]
patchy-group.af dpi=72;spreads=1;model_crc32=dc37ab6c;counts={"depth": 2, "images": 3, "layers": 1, "nodes": 4};boards=[];fonts={};warnings=[]
patchy-incremental-chain.af dpi=72;spreads=1;model_crc32=38c9c5f4;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[]
patchy-lab.af dpi=72;spreads=1;model_crc32=df3a4e40;counts={"depth": 1, "nodes": 1, "unsupported": 1};boards=[];fonts={};warnings=["pixel layers in grey, Lab or 32-bit formats"]
patchy-lazy-placed.af dpi=72;spreads=1;model_crc32=8776a8a0;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[]
patchy-live-filter.af dpi=72;spreads=1;model_crc32=12235fe9;counts={"depth": 2, "fills": 2, "gradients": 0, "nodes": 4, "segments": 6, "shapes": 2, "strokes": 0, "subpaths": 2, "unsupported": 2};boards=[];fonts={};warnings=["adjustment layers", "unknown layers"]
patchy-rgba16.af dpi=72;spreads=1;model_crc32=688b2475;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[]
patchy-rgba8.af dpi=72;spreads=1;model_crc32=688b2475;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[]
patchy-shapes-2.af dpi=72;spreads=1;model_crc32=6f174318;counts={"depth": 1, "fills": 12, "gradients": 0, "nodes": 12, "segments": 168, "shapes": 12, "strokes": 0, "subpaths": 13};boards=[];fonts={};warnings=[]
patchy-shapes.af dpi=72;spreads=1;model_crc32=c1790e97;counts={"depth": 1, "fills": 4, "gradients": 0, "nodes": 4, "segments": 28, "shapes": 4, "strokes": 0, "subpaths": 4};boards=[];fonts={};warnings=[]
patchy-text-artistic.af dpi=72;spreads=1;model_crc32=1d33192c;counts={"depth": 1, "nodes": 1, "text_chars": 5, "text_runs": 1, "texts": 1};boards=[];fonts={"Arial:ArialMT:400:false"};warnings=[]
patchy-text-caps.af dpi=72;spreads=1;model_crc32=24e52518;counts={"depth": 1, "nodes": 2, "text_chars": 21, "text_runs": 2, "texts": 2};boards=[];fonts={"Arial:ArialNarrow:400:false"};warnings=["font width variants (exact face depends on the installed PostScript font) (2×)"]
patchy-text-frame.af dpi=72;spreads=1;model_crc32=3bff8ef9;counts={"depth": 1, "nodes": 1, "text_chars": 11, "text_runs": 1, "texts": 1};boards=[];fonts={"Arial:ArialMT:400:false"};warnings=[]
patchy-text-indent.af dpi=72;spreads=1;model_crc32=dc36dfc5;counts={"depth": 1, "nodes": 2, "text_chars": 104, "text_runs": 2, "texts": 2};boards=[];fonts={"Arial:ArialNarrow:400:false"};warnings=["font width variants (exact face depends on the installed PostScript font) (2×)"]
patchy-text-para-spacing.af dpi=72;spreads=1;model_crc32=6408f39b;counts={"depth": 1, "nodes": 1, "text_chars": 13, "text_runs": 1, "texts": 1};boards=[];fonts={"Arial:ArialNarrow:400:false"};warnings=["font width variants (exact face depends on the installed PostScript font)"]
patchy-text-rotated.af dpi=72;spreads=1;model_crc32=3d1de559;counts={"depth": 1, "nodes": 1, "text_chars": 7, "text_runs": 1, "texts": 1};boards=[];fonts={"Arial:ArialNarrow:400:false"};warnings=["font width variants (exact face depends on the installed PostScript font)"]
patchy-text-runs.af dpi=72;spreads=1;model_crc32=7820b881;counts={"depth": 1, "nodes": 1, "text_chars": 7, "text_runs": 5, "texts": 1};boards=[];fonts={"Arial:ArialNarrow:400:false", "Courier New:CourierNewPSMT:400:false", "Segoe UI Emoji:SegoeUIEmoji:400:false", "Times New Roman:TimesNewRomanPSMT:400:false"};warnings=["font width variants (exact face depends on the installed PostScript font)", "text uses a stored fallback font (imported with that font)"]
patchy-transform.af dpi=72;spreads=1;model_crc32=8d56df84;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[]
patchy-vector-mask.af dpi=72;spreads=1;model_crc32=80ca946a;counts={"depth": 1, "fills": 2, "gradients": 0, "nodes": 2, "segments": 7, "shapes": 2, "strokes": 0, "subpaths": 2, "vector_masks": 1};boards=[];fonts={};warnings=["unknown layers attached to other layers (imported without them)"]
patchy-vector.af dpi=72;spreads=1;model_crc32=3b16c7ed;counts={"depth": 1, "fills": 3, "gradients": 0, "nodes": 4, "segments": 17, "shapes": 4, "strokes": 2, "subpaths": 5};boards=[];fonts={};warnings=[]
affinity3-mexican-guy.af dpi=300;spreads=1;counts={"depth": 8, "fills": 169, "gradients": 0, "groups": 23, "nodes": 283, "opacity": 1, "segments": 1491, "shapes": 260, "strokes": 114, "subpaths": 264};boards=[];fonts={};warnings=["blur effects (left out) (156×)"]
affinity3-mexican-man.af dpi=300;spreads=1;counts={"depth": 7, "fills": 277, "gradients": 2, "groups": 29, "nodes": 903, "segments": 3225, "shapes": 874, "strokes": 540, "subpaths": 881};boards=[];fonts={};warnings=["blur effects (left out) (244×)"]
affinity3-mexican-woman.af dpi=300;spreads=1;counts={"depth": 9, "fills": 527, "gradients": 0, "groups": 28, "nodes": 595, "segments": 3562, "shapes": 567, "strokes": 60, "subpaths": 570};boards=[];fonts={};warnings=["blur effects (left out) (278×)"]
affinity3-playing-cards.af dpi=300;spreads=1;counts={"depth": 5, "fills": 363, "gradients": 0, "groups": 758, "nodes": 1350, "segments": 4864, "shapes": 592, "strokes": 17, "subpaths": 656};boards=[];fonts={};warnings=["blur effects (left out) (309×)", "brush strokes (imported as plain strokes)"]
patchy-adjust-curves.af dpi=72;spreads=1;counts={"depth": 1, "images": 1, "nodes": 2, "unsupported": 1};boards=[];fonts={};warnings=["adjustment layers"]
patchy-adjust-hsl.af dpi=72;spreads=1;counts={"depth": 1, "images": 1, "nodes": 2, "unsupported": 1};boards=[];fonts={};warnings=["adjustment layers"]
patchy-artboards.af dpi=72;spreads=1;counts={"artboards": 2, "depth": 2, "fills": 2, "gradients": 0, "nodes": 4, "segments": 7, "shapes": 2, "strokes": 0, "subpaths": 2};boards=["board-a:0.0000,0.0000,80.0000,60.0000", "board-b:100.0000,10.0000,160.0000,70.0000"];fonts={};warnings=[]
patchy-blend-affinity.af dpi=72;spreads=1;counts={"depth": 2, "fills": 8, "gradients": 0, "images": 1, "layers": 1, "nodes": 10, "segments": 24, "shapes": 8, "strokes": 0, "subpaths": 8};boards=[];fonts={};warnings=["an unknown blend mode (imported as Normal) (2×)"]
patchy-cmyk.af dpi=72;spreads=1;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[]
patchy-dpi300.af dpi=300;spreads=1;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[]
patchy-embedded-jpeg.af dpi=72;spreads=1;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[]
patchy-fx-blur.af dpi=72;spreads=1;counts={"depth": 1, "images": 2, "nodes": 2};boards=[];fonts={};warnings=["blur effects (left out) (2×)"]
patchy-fx-gradient.af dpi=72;spreads=1;counts={"depth": 1, "images": 3, "nodes": 3};boards=[];fonts={};warnings=[]
patchy-fx.af dpi=72;spreads=1;counts={"depth": 1, "images": 5, "nodes": 5};boards=[];fonts={};warnings=[]
patchy-group.af dpi=72;spreads=1;counts={"depth": 2, "images": 3, "layers": 1, "nodes": 4};boards=[];fonts={};warnings=[]
patchy-incremental-chain.af dpi=72;spreads=1;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[]
patchy-lab.af dpi=72;spreads=1;counts={"depth": 1, "nodes": 1, "unsupported": 1};boards=[];fonts={};warnings=["pixel layers in grey, Lab or 32-bit formats"]
patchy-lazy-placed.af dpi=72;spreads=1;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[]
patchy-live-filter.af dpi=72;spreads=1;counts={"depth": 2, "fills": 2, "gradients": 0, "nodes": 4, "segments": 6, "shapes": 2, "strokes": 0, "subpaths": 2, "unsupported": 2};boards=[];fonts={};warnings=["adjustment layers", "unknown layers"]
patchy-rgba16.af dpi=72;spreads=1;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[]
patchy-rgba8.af dpi=72;spreads=1;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[]
patchy-shapes-2.af dpi=72;spreads=1;counts={"depth": 1, "fills": 12, "gradients": 0, "nodes": 12, "segments": 168, "shapes": 12, "strokes": 0, "subpaths": 13};boards=[];fonts={};warnings=[]
patchy-shapes.af dpi=72;spreads=1;counts={"depth": 1, "fills": 4, "gradients": 0, "nodes": 4, "segments": 28, "shapes": 4, "strokes": 0, "subpaths": 4};boards=[];fonts={};warnings=[]
patchy-text-artistic.af dpi=72;spreads=1;counts={"depth": 1, "nodes": 1, "text_chars": 5, "text_runs": 1, "texts": 1};boards=[];fonts={"Arial:ArialMT:400:false"};warnings=[]
patchy-text-caps.af dpi=72;spreads=1;counts={"depth": 1, "nodes": 2, "text_chars": 21, "text_runs": 2, "texts": 2};boards=[];fonts={"Arial:ArialNarrow:400:false"};warnings=["font width variants (exact face depends on the installed PostScript font) (2×)"]
patchy-text-frame.af dpi=72;spreads=1;counts={"depth": 1, "nodes": 1, "text_chars": 11, "text_runs": 1, "texts": 1};boards=[];fonts={"Arial:ArialMT:400:false"};warnings=[]
patchy-text-indent.af dpi=72;spreads=1;counts={"depth": 1, "nodes": 2, "text_chars": 104, "text_runs": 2, "texts": 2};boards=[];fonts={"Arial:ArialNarrow:400:false"};warnings=["font width variants (exact face depends on the installed PostScript font) (2×)"]
patchy-text-para-spacing.af dpi=72;spreads=1;counts={"depth": 1, "nodes": 1, "text_chars": 13, "text_runs": 1, "texts": 1};boards=[];fonts={"Arial:ArialNarrow:400:false"};warnings=["font width variants (exact face depends on the installed PostScript font)"]
patchy-text-rotated.af dpi=72;spreads=1;counts={"depth": 1, "nodes": 1, "text_chars": 7, "text_runs": 1, "texts": 1};boards=[];fonts={"Arial:ArialNarrow:400:false"};warnings=["font width variants (exact face depends on the installed PostScript font)"]
patchy-text-runs.af dpi=72;spreads=1;counts={"depth": 1, "nodes": 1, "text_chars": 7, "text_runs": 5, "texts": 1};boards=[];fonts={"Arial:ArialNarrow:400:false", "Courier New:CourierNewPSMT:400:false", "Segoe UI Emoji:SegoeUIEmoji:400:false", "Times New Roman:TimesNewRomanPSMT:400:false"};warnings=["font width variants (exact face depends on the installed PostScript font)", "text uses a stored fallback font (imported with that font)"]
patchy-transform.af dpi=72;spreads=1;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[]
patchy-vector-mask.af dpi=72;spreads=1;counts={"depth": 1, "fills": 2, "gradients": 0, "nodes": 2, "segments": 7, "shapes": 2, "strokes": 0, "subpaths": 2, "vector_masks": 1};boards=[];fonts={};warnings=["unknown layers attached to other layers (imported without them)"]
patchy-vector.af dpi=72;spreads=1;counts={"depth": 1, "fills": 3, "gradients": 0, "nodes": 4, "segments": 17, "shapes": 4, "strokes": 2, "subpaths": 5};boards=[];fonts={};warnings=[]
+4 -11
View File
@@ -1,8 +1,7 @@
//! Structural regression signatures, measured from the pinned files through our own reader.
//! These freeze feature retention; they are not independent visual or compatibility oracles.
//! The model CRC covers every decoded field via its Debug representation (including paths,
//! paint, masks, image pixels and text runs). A deliberate reader/Debug change needs review;
//! input authenticity is independently checked with SHA256 by the corpus gate.
//! They count retained features; they are not independent visual or compatibility oracles.
//! Pixels are checked against the stored tiles in `raster.rs`. Input authenticity is checked
//! with SHA256 by the corpus gate.
use std::collections::{BTreeMap, BTreeSet};
use vectorcraft_affinity::model::{Document, Kind, Node};
use vectorcraft_affinity::paint::Paint;
@@ -58,11 +57,5 @@ pub fn signature(doc: &Document) -> String {
for spread in &doc.spreads {
visit(&spread.nodes, &mut counts, &mut fonts, &mut boards, 1);
}
let model_crc32 = crc32fast::hash(format!("{:?}", doc.spreads).as_bytes());
format!(
"dpi={};spreads={};model_crc32={model_crc32:08x};counts={counts:?};boards={boards:?};fonts={fonts:?};warnings={:?}",
doc.dpi,
doc.spreads.len(),
doc.warnings
)
format!("dpi={};spreads={};counts={counts:?};boards={boards:?};fonts={fonts:?};warnings={:?}", doc.dpi, doc.spreads.len(), doc.warnings)
}
+3 -2
View File
@@ -894,7 +894,7 @@ fn trimmed_bristle_strands_read_pressure_where_they_begin() {
}
let (_, neutral_width) = start(neutral);
let expected = 0.5 + x / 80.0;
assert!(width / neutral_width > expected - 0.08, "strand at {x}: {width} vs {neutral_width}, expected ratio {expected}");
assert!((width / neutral_width - expected).abs() < 0.02, "strand at {x}: {width} vs {neutral_width}, expected ratio {expected}");
checked = true;
}
assert!(checked, "at least one strand begins past the pressure ramp's first eighth");
@@ -1967,7 +1967,8 @@ fn pressure_varies_angle_and_roundness() {
let b = Brush { name: "r".into(), kind: BrushKind::Calligraphic(vertical.clone()) };
bounds(&stroke_pieces(&Document::new(1.0, 1.0), &b, &line(0.0, 0.0, 0.0, 100.0), &pressed(vec![(0.0, p), (1.0, p)]))).width()
};
assert!(near(wide(0.0), 0.1, 0.05), "{}", wide(0.0));
// Roundness 1% of the 10 pt size.
assert!(near(wide(0.0), 0.1, 1e-6), "{}", wide(0.0));
assert!(near(wide(1.0), 10.0, 0.05), "{}", wide(1.0));
// The angle turns on past 180°: 170 + 40 is 210°, the nib at 30° (not stopped at 180°).
let turned = Calligraphic { angle: 170.0, roundness: 10.0, variation: [40.0, 0.0, 0.0], ..c([Pressure, Fixed, Fixed]) };
+96 -6
View File
@@ -1543,13 +1543,103 @@ fn export_bytes_match_shared_writer_goldens() {
let out = export(&doc, &DxfOptions { version, ..opts(&doc) }).unwrap();
let got = std::str::from_utf8(&out.bytes).expect("UTF-8 DXF");
let path = dir.join(name);
if std::env::var_os("WRITE_DXF_GOLDENS").is_some() {
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(&path, got).unwrap();
continue;
}
let expected = std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("read {}: {e}", path.display()));
assert_eq!(got, expected, "DXF bytes changed versus {}", path.display());
assert_holds_shapes_doc(&expected, version);
if got != expected {
// Written for review only; a golden file changes by hand after its drawing checks pass.
let actual = std::env::temp_dir().join(format!("{name}.actual"));
let saved = std::fs::write(&actual, got).map_or_else(|e| format!("not saved: {e}"), |()| format!("saved to {}", actual.display()));
panic!("DXF bytes changed versus {} (output {saved})", path.display());
}
}
}
/// Checks that a golden file holds [`shapes_doc`] as the DXF Reference describes it, in a 200 × 100 pt
/// region with y up: the red fill and the black 1 pt stroke of the rectangle (10, 40)–(110, 90), and
/// the blue 2 pt circle of radius 30 around (150, 50). ACI colors 1, 5 and 7 are red, blue and
/// black/white; code 420 holds 0xRRGGBB; code 370 is lineweight in hundredths of a millimeter
/// (1 pt = 0.3528 mm gives 35, 2 pt gives 70); a POLYLINE vertex's bulge is tan(arc angle / 4).
fn assert_holds_shapes_doc(golden: &str, version: DxfVersion) {
let ents = section(&pairs(golden.as_bytes()), "ENTITIES");
let colored = |aci: &str| -> Vec<&Pairs> { ents.iter().filter(|e| get(e, 62) == Some(aci)).collect() };
// Every drawn point of the entities in one color; (0, 0) is the elevation point of POLYLINE
// and HATCH headers, which no shape of the drawing reaches.
let points = |aci: &str| -> Vec<(f64, f64)> {
colored(aci).iter().flat_map(|e| all(e, 10).into_iter().zip(all(e, 20))).filter(|p| *p != (0.0, 0.0)).collect()
};
let bbox = |pts: &[(f64, f64)]| {
pts.iter().fold((f64::MAX, f64::MAX, f64::MIN, f64::MIN), |b, p| (b.0.min(p.0), b.1.min(p.1), b.2.max(p.0), b.3.max(p.1)))
};
for aci in ["1", "7"] {
let pts = points(aci);
assert_eq!(pts.len() % 4, 0, "{version:?} ACI {aci}: rectangle corners {pts:?}");
assert_eq!(bbox(&pts), (10.0, 40.0, 110.0, 90.0), "{version:?} ACI {aci}");
// Each run of four points is one outline of the rectangle: all four corners, each joined to
// the next (and the last to the first) by a horizontal or vertical edge.
let corners = [(10.0, 40.0), (110.0, 40.0), (110.0, 90.0), (10.0, 90.0)];
for quad in pts.chunks(4) {
assert!(corners.iter().all(|c| quad.contains(c)), "{version:?} ACI {aci}: corners {quad:?}");
for (i, a) in quad.iter().enumerate() {
let b = quad[(i + 1) % 4];
assert!((a.0 == b.0) != (a.1 == b.1), "{version:?} ACI {aci}: edge {a:?} to {b:?} in {quad:?}");
}
}
}
let circle = colored("5");
assert!(!circle.is_empty(), "{version:?}: the blue circle");
if let Some(c) = circle.iter().find(|e| kind(e) == "CIRCLE") {
assert_eq!((all(c, 10), all(c, 20), all(c, 40)), (vec![150.0], vec![50.0], vec![30.0]), "{version:?}");
} else {
let pts = points("5");
assert!(pts.len() >= 2, "{version:?}: circle vertices {pts:?}");
for (x, y) in &pts {
assert!(((x - 150.0).hypot(y - 50.0) - 30.0).abs() < 1e-4, "{version:?}: vertex ({x}, {y}) off the circle");
}
let turn: f64 = circle.iter().flat_map(|e| all(e, 42)).map(|b| 4.0 * b.atan()).sum();
assert!((turn.abs() - std::f64::consts::TAU).abs() < 1e-4, "{version:?}: bulges sweep {turn} rad");
// Each segment, the closing one included, is an arc of the circle: the point halfway along it,
// which lies bulge × chord / 2 to the right of the chord's middle, is on the circle too.
let mut verts: Vec<((f64, f64), f64)> = Vec::new();
for e in &circle {
let mut x = None;
for (c, v) in e.iter() {
let n = || v.trim().parse::<f64>().expect("a number");
match c {
10 => x = Some(n()),
20 => {
let p = (x.take().unwrap_or(f64::NAN), n());
if p != (0.0, 0.0) {
verts.push((p, 0.0));
}
}
42 => {
if let Some(last) = verts.last_mut() {
last.1 = n();
}
}
_ => {}
}
}
}
for (i, &((px, py), b)) in verts.iter().enumerate() {
let (qx, qy) = verts[(i + 1) % verts.len()].0;
let (mx, my) = (px + (qx - px) / 2.0 + b * (qy - py) / 2.0, py + (qy - py) / 2.0 - b * (qx - px) / 2.0);
assert!(
((mx - 150.0).hypot(my - 50.0) - 30.0).abs() < 1e-4,
"{version:?}: segment ({px}, {py}) to ({qx}, {qy}) with bulge {b} leaves the circle at ({mx}, {my})"
);
}
}
if version >= DxfVersion::R2000 {
let code = |aci: &str, c: i32| -> Vec<String> { colored(aci).iter().filter_map(|e| get(e, c)).map(str::to_string).collect() };
assert!(code("1", 420).iter().all(|v| v == "16711680") && !code("1", 420).is_empty(), "{version:?}: red true color");
assert_eq!(code("7", 420), ["0"], "{version:?}: black true color");
assert_eq!(code("5", 420), ["255"], "{version:?}: blue true color");
assert_eq!(code("7", 370), ["35"], "{version:?}: 1 pt stroke");
assert_eq!(code("5", 370), ["70"], "{version:?}: 2 pt stroke");
} else {
let stroke = colored("7");
assert_eq!((all(stroke[0], 40), all(stroke[0], 41)), (vec![1.0], vec![1.0]), "{version:?}: 1 pt polyline width");
}
}
+3 -1
View File
@@ -685,7 +685,9 @@ mod tests {
let mid = f.split_line(0, 0, 0.5).unwrap();
assert_eq!((mid, &f.lines[0]), (3, &vec![0, 3, 1, 2]));
let p = f.points[3];
assert!(p.at.y.abs() < 1e-9 && p.at.x > 0.0 && p.at.x < 100.0 && (p.opacity - 0.75).abs() < 1e-6, "on the curve, half way: {p:?}");
// The Catmull-Rom segment from (0, 0) to (100, 0), with (200, 0) after it, is at x = 43.75
// half way, not at the straight line's 50.
assert!(p.at.y.abs() < 1e-9 && (p.at.x - 43.75).abs() < 1e-9 && (p.opacity - 0.75).abs() < 1e-6, "on the curve, half way: {p:?}");
assert!(f.remove_point(1));
assert_eq!(f.lines, vec![vec![0, 2, 1]]);
assert!(f.add_line(vec![0, 9]).is_err() && f.add_line(vec![0]).is_err());
+1 -1
View File
@@ -1379,7 +1379,7 @@ fn diamond_pixels_follow_the_squares() {
g.geom = Some(diamond_at(Point::new(2.5, 2.5), 2.5, 1.0));
let px: Vec<[u8; 4]> = g.pixels(b, b, 5, 5, false, &Color::to_rgb).collect();
// White at the center, black in the corners, and the same on each side of it.
assert!(px[2 * 5 + 2][0] > 200 && px[0][0] < 10 && px[24][0] < 10, "{px:?}");
assert_eq!((px[2 * 5 + 2], px[0], px[24]), ([255, 255, 255, 255], [0, 0, 0, 255], [0, 0, 0, 255]), "{px:?}");
assert_eq!(px[2 * 5 + 1], px[2 * 5 + 3]);
assert_eq!(px[5 + 2], px[3 * 5 + 2]);
assert_eq!(px[2 * 5 + 1], px[5 + 2]);
+1
View File
@@ -108,6 +108,7 @@ impl GraphDesign {
let mut e = n.extras_mut();
e.graph = None;
e.series_index = None;
e.graph_design_art = false;
}
if let Some(ch) = n.children_mut() {
let old = std::mem::take(ch);
+1 -1
View File
@@ -457,7 +457,7 @@ mod tests {
n.transform(Affine::scale_non_uniform(1.0, 0.25), false);
assert!(n.extras().image_quad.is_none());
let b = n.geometric_bounds().unwrap();
assert!(b.height() < 1e-6 && (b.width() - 150.0).abs() < 60.0, "{b:?}");
assert!(b.height() < 1e-6 && (b.x0 + 200.0 / 9.0).abs() < 1e-6 && (b.x1 - 1400.0 / 9.0).abs() < 1e-6, "{b:?}");
}
/// A file's corners that the image cannot take are dropped as it is read, so a later scale
+3
View File
@@ -22,6 +22,8 @@ pub struct NodeExtras {
/// Index of the graph series this generated group belongs to. Axes, the legend and other
/// children leave it unset, so a series named "Legend" or "Axes" is not mistaken for them.
pub series_index: Option<u32>,
/// This object is a generated copy of a graph column or marker design.
pub graph_design_art: bool,
/// The group holds the glyph outlines of type. Geometry effects that reshape it move and scale
/// the placed gradients in it with the outlines.
pub type_outlines: bool,
@@ -108,6 +110,7 @@ pub(super) static NO_EXTRAS: NodeExtras = NodeExtras {
wrap: None,
graph: None,
series_index: None,
graph_design_art: false,
type_outlines: false,
pixelated: false,
shaper: None,
+2
View File
@@ -13,6 +13,7 @@ fn extras_are_written_flat_in_order() {
e.mask = Some(Box::new(OpacityMask::new(Node::group(NodeId(8), vec![]), true)));
e.trace = Some(Box::new(serde_json::json!({"preset": "p"})));
e.series_index = Some(2);
e.graph_design_art = true;
e.type_outlines = true;
e.graphic_style = Some(3);
e.attrs = Some(Box::default());
@@ -59,6 +60,7 @@ fn extras_are_written_flat_in_order() {
"mask",
"trace",
"series_index",
"graph_design_art",
"type_outlines",
"kind",
"graphic_style",
+5
View File
@@ -36,6 +36,7 @@ impl Serialize for Node {
e.wrap.is_none(),
e.graph.is_none(),
e.series_index.is_none(),
is_default(&e.graph_design_art),
is_default(&e.type_outlines),
is_default(&e.pixelated),
e.shaper.is_none(),
@@ -86,6 +87,7 @@ impl Serialize for Node {
field!("wrap", &e.wrap);
field!("graph", &e.graph);
field!("series_index", &e.series_index);
field!("graph_design_art", &e.graph_design_art);
field!("type_outlines", &e.type_outlines);
field!("pixelated", &e.pixelated);
field!("shaper", &e.shaper);
@@ -220,6 +222,8 @@ pub(super) struct NodeWire {
#[serde(default)]
series_index: Option<u32>,
#[serde(default)]
graph_design_art: bool,
#[serde(default)]
type_outlines: bool,
#[serde(default)]
pixelated: bool,
@@ -480,6 +484,7 @@ impl From<NodeWire> for Node {
wrap: w.wrap,
graph: w.graph,
series_index: w.series_index,
graph_design_art: w.graph_design_art,
type_outlines: w.type_outlines,
pixelated: w.pixelated,
shaper: w.shaper,
+6 -2
View File
@@ -122,8 +122,12 @@ mod tests {
// One stop doubles the light: sRGB 0.5 (linear 0.214) becomes linear 0.428, sRGB 0.686.
assert!(close(map(EXPOSURE, json!({"exposure": 1})).apply_rgb(grey), [0.686; 3]));
assert!(close(map(EXPOSURE, json!({"exposure": -20})).apply_rgb([1.0; 3]), [0.0; 3]));
assert!(map(EXPOSURE, json!({"offset": 0.1})).apply_rgb([0.0; 3])[0] > 0.3, "the offset lifts the shadows");
assert!(map(EXPOSURE, json!({"gamma": 2})).apply_rgb(grey)[0] > 0.6);
// The offset adds linear light: linear 0.1 is sRGB 0.349.
let lifted = map(EXPOSURE, json!({"offset": 0.1})).apply_rgb([0.0; 3]);
assert!(lifted.iter().all(|c| (c - 0.349_190_2).abs() < 1e-5), "the offset lifts the shadows: {lifted:?}");
// Gamma 2 takes the square root of linear 0.214 (sRGB 0.5): linear 0.463, sRGB 0.710.
let raised = map(EXPOSURE, json!({"gamma": 2})).apply_rgb(grey);
assert!(raised.iter().all(|c| (c - 0.710_196).abs() < 1e-5), "{raised:?}");
assert!(close(map(EXPOSURE, json!({"exposure": 1e300, "gamma": 0})).apply_rgb(grey), [1.0; 3]), "out of range values are clamped");
}
+295 -2
View File
@@ -19,7 +19,7 @@ use serde_json::{Value, json};
use vectorcraft_doc::color::{BlendMode, Color, Paint};
use vectorcraft_doc::{Appearance, Document, Node, NodeId};
use vectorcraft_geom::hit::fill_contains;
use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, Point, Rect, shapes};
use vectorcraft_geom::{Affine, BezPath, CubicBez, FillRule, PathData, Point, Rect, shapes};
use vectorcraft_pathops::{self as po, BoolOp};
use crate::catalog::{EffectInfo, Lengths};
@@ -43,7 +43,7 @@ pub(crate) fn catalog() -> Vec<EffectInfo> {
id: HALFTONE,
label: "Vector Halftone…",
menu: &["Effect", "Color Effects"],
params: "{shape: \"circle\"|\"ellipse\"|\"square\"|\"diamond\"|\"line\" (circle), frequency: lines per inch 1..300 (20), angle: deg (45; CMYK: the black screen's, cyan −30°, magenta +30°, yellow −45° from it), mode: \"mono\"|\"cmyk\" (mono), color: mono dot colour (\"#000000\"), fromArt: bool (false; mono: each dot takes the art's colour under it), invert: bool (false; dots for light tones), clip: bool (true; the dots clipped to the art's outline)} draws the object as vector halftone dots sized by its tone, as object.vectorHalftone makes them (CMYK screens multiply); the object is sampled as drawn with its other effects; at most 100000 cells per screen, past that the object draws as it is",
params: "{shape: \"circle\"|\"ellipse\"|\"square\"|\"diamond\"|\"line\"|\"euclidean\"|\"elliptical\" (circle; euclidean: round dots that meet corner to corner at 50%, then round holes; elliptical: long dots that join into chains at 40% and on all sides at 60%, then long holes), frequency: lines per inch 1..300 (20), angle: deg (45; CMYK: the black screen's, cyan −30°, magenta +30°, yellow −45° from it), mode: \"mono\"|\"cmyk\" (mono), color: mono dot colour (\"#000000\"), fromArt: bool (false; mono: each dot takes the art's colour under it), invert: bool (false; dots for light tones), clip: bool (true; the dots clipped to the art's outline)} draws the object as vector halftone dots sized by its tone, as object.vectorHalftone makes them (CMYK screens multiply); the object is sampled as drawn with its other effects; at most 100000 cells per screen, past that the object draws as it is",
defaults: json!({"shape": "circle", "frequency": 20.0, "angle": 45.0, "mode": "mono", "color": "#000000", "fromArt": false, "invert": false, "clip": true}),
raster: false,
lengths: Lengths::default(),
@@ -63,6 +63,12 @@ pub enum DotShape {
Square,
Diamond,
Line,
/// Round dots that grow into squares meeting corner to corner at 50% (a checkerboard), then
/// round holes, as the Euclidean spot function draws them.
Euclidean,
/// Elongated dots that join along their long side at 40% into chains, along their short side
/// at 60%, then elongated holes.
Elliptical,
}
impl DotShape {
@@ -73,6 +79,8 @@ impl DotShape {
"square" => DotShape::Square,
"diamond" => DotShape::Diamond,
"line" | "lines" => DotShape::Line,
"euclidean" => DotShape::Euclidean,
"elliptical" => DotShape::Elliptical,
_ => return None,
})
}
@@ -94,10 +102,227 @@ impl DotShape {
DotShape::Diamond => square(s * t.sqrt()).transformed(Affine::rotate(std::f64::consts::FRAC_PI_4)),
// Cells along a row join into a line as thick as the tone.
DotShape::Line => shapes::rectangle(Rect::from_center_size(Point::ZERO, (s * 1.001, s * t))),
DotShape::Euclidean => PathData::from_bezpath(&spot(t, s / 2.0, SpotKind::Euclidean)),
DotShape::Elliptical => PathData::from_bezpath(&spot(t, s / 2.0, SpotKind::Elliptical)),
}
}
}
/// The Elliptical dot's height over its width: a dot as wide as its cell covers 40% of it
/// (π × ratio / 4 = 0.4 of a quadrant).
const ELLIPTICAL_RATIO: f64 = 1.6 / std::f64::consts::PI;
/// The Elliptical dot's middle-tone cut in a quadrant of half side 1, the line
/// `ELLIPTICAL_CUT.0 × x + y = ELLIPTICAL_CUT.1`. It meets the side x = 1 at y = 0.25 and the y
/// axis at 0.75 and runs through the quadrant's center, so the dot it cuts at 50% is its own
/// complement: the dark bridges across the x side from 40%, and the y side stays light until 60%.
const ELLIPTICAL_CUT: (f64, f64) = (0.5, 0.75);
/// Steps of the table of dot sizes per tone ([`dot_sizes`]) over tones 0..0.5.
const SIZE_STEPS: usize = 512;
static EUCLIDEAN: OnceLock<Vec<f64>> = OnceLock::new();
static ELLIPTICAL: OnceLock<Vec<f64>> = OnceLock::new();
/// The two spot-function dots.
#[derive(Clone, Copy)]
enum SpotKind {
Euclidean,
Elliptical,
}
impl SpotKind {
/// The first quadrant of the dot of width `a` in a quadrant of half side 1.
fn quadrant(self, a: f64) -> Vec<CubicBez> {
match self {
SpotKind::Euclidean => quadrant(a, a, 1.0),
SpotKind::Elliptical => elliptical_quadrant(a),
}
}
/// The width at which the dot covers half the cell.
fn max_size(self) -> f64 {
match self {
SpotKind::Euclidean => 1.0,
SpotKind::Elliptical => ELLIPTICAL_CUT.1 / ELLIPTICAL_RATIO,
}
}
fn table(self) -> &'static OnceLock<Vec<f64>> {
match self {
SpotKind::Euclidean => &EUCLIDEAN,
SpotKind::Elliptical => &ELLIPTICAL,
}
}
}
/// For tones `k / SIZE_STEPS × 0.5`, the width `a` of the dot of `kind` that covers that tone of the
/// cell [-1, 1]².
fn dot_sizes(kind: SpotKind) -> Vec<f64> {
(0..=SIZE_STEPS)
.map(|k| {
// A quadrant of the cell has area 1.
let target = k as f64 / SIZE_STEPS as f64 * 0.5;
let (mut lo, mut hi) = (0.0, kind.max_size());
for _ in 0..50 {
let mid = (lo + hi) / 2.0;
if curves_area(&kind.quadrant(mid)) < target { lo = mid } else { hi = mid }
}
(lo + hi) / 2.0
})
.collect()
}
/// The area between the origin and `curves`, which run from the x axis to the y axis.
fn curves_area(curves: &[CubicBez]) -> f64 {
use vectorcraft_geom::kurbo::ParamCurveArea;
curves.iter().map(|c| c.signed_area()).sum()
}
/// Cubic curves along the ellipse with semi-axes `a`, `b` from angle `t0` to `t1`.
fn ellipse_arc(out: &mut Vec<CubicBez>, a: f64, b: f64, t0: f64, t1: f64) {
if t1 <= t0 {
return;
}
let at = |th: f64| Point::new(a * th.cos(), b * th.sin());
let n = ((t1 - t0) / std::f64::consts::FRAC_PI_4).ceil().max(1.0);
let d = (t1 - t0) / n;
let k = 4.0 / 3.0 * (d / 4.0).tan();
for i in 0..n as usize {
let (u0, u1) = (t0 + d * i as f64, t0 + d * (i as f64 + 1.0));
let (p0, p3) = (at(u0), at(u1));
let c1 = p0 + k * vectorcraft_geom::Vec2::new(-a * u0.sin(), b * u0.cos());
let c2 = p3 - k * vectorcraft_geom::Vec2::new(-a * u1.sin(), b * u1.cos());
out.push(CubicBez::new(p0, c1, c2, p3));
}
}
/// The straight segment from `p` to `q` as a cubic curve.
fn segment(p: Point, q: Point) -> CubicBez {
CubicBez::new(p, p.lerp(q, 1.0 / 3.0), p.lerp(q, 2.0 / 3.0), q)
}
/// The first quadrant of the Elliptical dot of width `a` (height `ELLIPTICAL_RATIO × a`) in a
/// quadrant of half side 1, from the x axis to the y axis. Up to width 1 (40%) it is the whole
/// ellipse. Wider, the ellipse is clipped to the side x = 1, which makes a bridge to the next dot
/// along x, and to the cut line [`ELLIPTICAL_CUT`], which keeps it off the y side.
fn elliptical_quadrant(a: f64) -> Vec<CubicBez> {
use std::f64::consts::FRAC_PI_2;
let b = a * ELLIPTICAL_RATIO;
let mut out = vec![];
if a <= 1.0 {
ellipse_arc(&mut out, a, b, 0.0, FRAC_PI_2);
return out;
}
let at = |th: f64| Point::new(a * th.cos(), b * th.sin());
let (m, c) = ELLIPTICAL_CUT;
// The ellipse crosses the side x = 1 at angle t0.
let t0 = (1.0 / a).acos();
// Between angles ts and te the ellipse lies beyond the cut line.
let r = (m * a).hypot(b);
let (ts, te) = if r > c {
let (phi, alpha) = (b.atan2(m * a), (c / r).acos());
(phi - alpha, phi + alpha)
} else {
(FRAC_PI_2, FRAC_PI_2)
};
let end = if te < FRAC_PI_2 { at(te) } else { Point::new(0.0, c) };
out.push(segment(Point::new(1.0, 0.0), if t0 < ts || t0 >= te { at(t0) } else { Point::new(1.0, c - m) }));
if t0 >= te {
ellipse_arc(&mut out, a, b, t0, FRAC_PI_2);
return out;
}
if t0 < ts {
ellipse_arc(&mut out, a, b, t0, ts.min(FRAC_PI_2));
if ts >= FRAC_PI_2 {
return out;
}
}
let from = out.last().map_or(Point::new(1.0, 0.0), |q| q.p3);
out.push(segment(from, end));
ellipse_arc(&mut out, a, b, te, FRAC_PI_2);
out
}
/// The first quadrant of the ellipse with semi-axes `a`, `b` clipped to the diamond side x + y ≤
/// `h`, from its point on the x axis to its point on the y axis, as cubic curves.
fn quadrant(a: f64, b: f64, h: f64) -> Vec<CubicBez> {
use std::f64::consts::FRAC_PI_2;
let at = |th: f64| Point::new(a * th.cos(), b * th.sin());
let mut out = vec![];
let r = a.hypot(b);
if r <= h {
ellipse_arc(&mut out, a, b, 0.0, FRAC_PI_2);
return out;
}
let (phi, alpha) = (b.atan2(a), (h / r).acos());
let (ts, te) = (phi - alpha, phi + alpha);
let start = if ts > 0.0 {
ellipse_arc(&mut out, a, b, 0.0, ts);
at(ts)
} else {
Point::new(h, 0.0)
};
let end = if te < FRAC_PI_2 { at(te) } else { Point::new(0.0, h) };
out.push(segment(start, end));
ellipse_arc(&mut out, a, b, te, FRAC_PI_2);
out
}
/// `curves` reversed, each curve run backwards.
fn reversed(curves: &[CubicBez]) -> Vec<CubicBez> {
curves.iter().rev().map(|c| CubicBez::new(c.p3, c.p2, c.p1, c.p0)).collect()
}
/// `curves` with each point mapped by `f`.
fn mapped(curves: &[CubicBez], f: impl Fn(Point) -> Point) -> Vec<CubicBez> {
curves.iter().map(|c| CubicBez::new(f(c.p0), f(c.p1), f(c.p2), f(c.p3))).collect()
}
/// The quadrant of the `kind` spot for tone `u` (0..0.5) in a cell of half side `h`, its size from
/// the kind's table ([`dot_sizes`]).
fn spot_quadrant(u: f64, h: f64, kind: SpotKind) -> Vec<CubicBez> {
let sizes = kind.table().get_or_init(|| dot_sizes(kind));
let x = (u / 0.5).clamp(0.0, 1.0) * SIZE_STEPS as f64;
let i = (x.floor() as usize).min(SIZE_STEPS - 1);
let (lo, hi) = (sizes.get(i).copied().unwrap_or(0.0), sizes.get(i + 1).copied().unwrap_or(0.0));
let a = lo + (hi - lo) * (x - i as f64);
mapped(&kind.quadrant(a), |p| Point::new(p.x * h, p.y * h))
}
/// A spot-function dot for tone `t` (0..1) in a cell of half side `h` centered on the origin: up to
/// half tone, the `kind` dot with the tone's area (Euclidean: a circle clipped to the cell's
/// diamond; Elliptical: an ellipse clipped to the cell's sides and its middle-tone cut); past half,
/// the cell with the dot of the opposite tone cut out at each corner, so the dark joins up and the
/// light becomes holes.
fn spot(t: f64, h: f64, kind: SpotKind) -> BezPath {
let mut bp = BezPath::new();
let mut add = |curves: Vec<CubicBez>, first: bool| {
for (k, c) in curves.iter().enumerate() {
if k == 0 {
if first { bp.move_to(c.p0) } else { bp.line_to(c.p0) }
}
bp.curve_to(c.p1, c.p2, c.p3);
}
};
if t <= 0.5 {
let q1 = spot_quadrant(t, h, kind);
add(q1.clone(), true);
add(reversed(&mapped(&q1, |p| Point::new(-p.x, p.y))), false);
add(mapped(&q1, |p| Point::new(-p.x, -p.y)), false);
add(reversed(&mapped(&q1, |p| Point::new(p.x, -p.y))), false);
} else {
// Round the corners counterclockwise, each one's hole the dot of the opposite tone.
let q1 = spot_quadrant(1.0 - t.min(1.0), h, kind);
add(reversed(&mapped(&q1, |p| Point::new(h - p.x, h - p.y))), true);
add(mapped(&q1, |p| Point::new(p.x - h, h - p.y)), false);
add(reversed(&mapped(&q1, |p| Point::new(p.x - h, p.y - h))), false);
add(mapped(&q1, |p| Point::new(h - p.x, p.y - h)), false);
}
bp.close_path();
bp
}
/// One screen: its ink and angle, and how to read its tone from a sampled pixel.
struct Screen {
paint: Color,
@@ -399,6 +624,7 @@ pub fn halftone_art(d: &Document, n: &Node) -> Option<Node> {
mod tests {
use super::*;
use vectorcraft_doc::Effect;
use vectorcraft_geom::Shape;
/// A black square's samples: `side` points of black from (10, 10), white around it.
fn black_square(side: f64, h: &Halftone) -> (Samples, Rect) {
@@ -464,6 +690,73 @@ mod tests {
assert_eq!(cmyk.layers(&one, Rect::new(2.0, 2.0, 18.0, 18.0), None).0.len(), 2);
}
/// Is `p` (in cells of side 1) inside the dot `shape` draws for tone `t`?
fn covers(shape: DotShape, t: f64, p: (f64, f64)) -> bool {
fill_contains(&shape.path(t, 1.0).to_bezpath(), FillRule::NonZero, Point::new(p.0, p.1))
}
#[test]
fn spot_dots_cover_the_tone() {
for shape in [DotShape::Euclidean, DotShape::Elliptical] {
for k in 1..100 {
let t = f64::from(k) / 100.0;
let area = shape.path(t, 2.0).to_bezpath().area().abs() / 4.0;
assert!((area - t).abs() < 2e-3, "{shape:?} at {t}: {area}");
let b = shape.path(t, 2.0).control_bounds().unwrap();
assert!(b.x0 >= -1.0 - 1e-9 && b.x1 <= 1.0 + 1e-9 && b.y0 >= -1.0 - 1e-9 && b.y1 <= 1.0 + 1e-9, "{shape:?} at {t}: {b:?}");
}
}
assert_eq!((DotShape::parse("Euclidean"), DotShape::parse("elliptical")), (Some(DotShape::Euclidean), Some(DotShape::Elliptical)));
}
#[test]
fn euclidean_dots_meet_corner_to_corner_at_half() {
let s = DotShape::Euclidean;
// Round dots apart from their neighbors below half.
assert!(!covers(s, 0.45, (0.49, 0.0)) && !covers(s, 0.45, (0.0, 0.49)) && covers(s, 0.45, (0.3, 0.0)));
// At half the dot is the diamond reaching the middle of each side: a checkerboard.
for p in [(0.49, 0.0), (-0.49, 0.0), (0.0, 0.49), (0.0, -0.49)] {
assert!(covers(s, 0.5, p), "{p:?}");
}
assert!(!covers(s, 0.5, (0.26, 0.26)) && covers(s, 0.5, (0.24, 0.24)));
// Past half the light becomes round holes at the corners.
assert!(covers(s, 0.55, (0.0, 0.499)) && covers(s, 0.55, (0.499, 0.0)) && !covers(s, 0.55, (0.49, 0.49)));
assert!(covers(s, 0.99, (0.3, 0.3)));
}
#[test]
fn elliptical_dots_join_along_their_length_then_their_width() {
let s = DotShape::Elliptical;
// Below 40% the dots stand apart.
assert!(!covers(s, 0.38, (0.495, 0.0)) && !covers(s, 0.38, (0.0, 0.45)));
// From 40% they reach their neighbors along x, making chains, but not along y.
assert!(covers(s, 0.42, (0.495, 0.0)) && !covers(s, 0.42, (0.0, 0.45)));
// The chains are bridges as tall as the tone allows across the shared side, not single
// points: off the axis on the side x = 0.5, and on the cell's other side by symmetry.
assert!(covers(s, 0.46, (0.499, 0.03)) && covers(s, 0.46, (-0.499, -0.03)) && !covers(s, 0.46, (0.499, 0.2)));
assert!(covers(s, 0.5, (0.499, 0.12)) && !covers(s, 0.5, (0.499, 0.13)) && !covers(s, 0.5, (0.0, 0.49)));
// Up to 60% the light still runs along the top edge between the corner holes.
assert!(!covers(s, 0.55, (0.02, 0.499)) && covers(s, 0.55, (0.0, 0.3)));
// Past 60% the dark joins across the top edge too, leaving elongated holes.
assert!(covers(s, 0.65, (0.02, 0.499)) && covers(s, 0.65, (0.495, 0.0)) && !covers(s, 0.65, (0.49, 0.49)));
// The holes are longer along x than along y.
assert!(!covers(s, 0.8, (0.3, 0.49)) && covers(s, 0.8, (0.49, 0.3)), "ratio {ELLIPTICAL_RATIO}");
// Today's Ellipse stays as it was: an ellipse 1.69 times as wide as tall.
let b = DotShape::Ellipse.path(0.3, 1.0).control_bounds().unwrap();
assert!((b.width() / b.height() - 1.69).abs() < 1e-6, "{b:?}");
}
#[test]
fn spot_shapes_make_dots_through_the_screen() {
for shape in [DotShape::Euclidean, DotShape::Elliptical] {
let h = Halftone::of(&effect(json!({"frequency": 18, "shape": format!("{shape:?}")}))).unwrap();
assert_eq!(h.shape, shape);
let (s, b) = black_square(60.0, &h);
let (layers, dots) = h.layers(&s, b, None);
assert!(layers.len() == 1 && (150..=320).contains(&dots), "{shape:?}: {dots}");
}
}
#[test]
fn the_caps_refuse_too_many_cells() {
let h = Halftone::of(&effect(json!({"frequency": 300}))).unwrap();
+1 -1
View File
@@ -744,7 +744,7 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
"pixelate.colorHalftone",
"Color Halftone…",
PIXELATE,
"{maxRadius: px 4..127 (8; the radius of a dot at full strength, which fills its square cell, in pixels of the Document Raster Effects resolution), channel1: screen angle deg -360..360 (108), channel2: deg (162), channel3: deg (90), channel4: deg (45)} screens each colour channel (red, green, blue: channels 1 to 3; in CMYK documents cyan, magenta, yellow, black: 1 to 4) at its angle into dots whose area follows the channel's mean over their cell",
"{maxRadius: px 4..127 (8; the radius of a dot at full strength, which fills its square cell, in pixels of the Document Raster Effects resolution), channel1: screen angle deg -360..360 (108), channel2: deg (162), channel3: deg (90), channel4: deg (45)} The effect screens cyan, magenta and yellow ink (channels 1 to 3; CMYK mode adds black as channel 4) at their angles into dots whose area follows the cell's mean ink coverage.",
json!({"maxRadius": 8.0, "channel1": 108.0, "channel2": 162.0, "channel3": 90.0, "channel4": 45.0}),
),
r(
+4 -3
View File
@@ -437,7 +437,7 @@ impl Screen {
/// Color Halftone: each channel screened at its angle in square cells sized so that a dot of
/// `max_radius` (pixels of the document's raster grid, `space.line` each) fills one; each cell's
/// dot covers the share of it that is the channel's mean there (white stays white, black black).
/// dot covers the mean ink coverage of that cell (white stays white, black black).
/// Coverage stays as it is.
pub(super) fn color_halftone(px: &mut [[u8; 4]], w: usize, h: usize, space: &PixelSpace, max_radius: f64, angles: [f64; 4]) {
let Some(place) = Place::new(space, w, h) else { return };
@@ -446,7 +446,8 @@ pub(super) fn color_halftone(px: &mut [[u8; 4]], w: usize, h: usize, space: &Pix
if !(side.is_finite() && side / place.px >= 3.0) {
return;
}
let channels = space.channels;
// Screen RGB as dark ink against white, like the CMY channel previews.
let channels = if space.channels == Channels::Rgb { Channels::CmyPlane } else { space.channels };
let n = split([0; 4], channels).1;
let limit = w.saturating_mul(h).saturating_add(4096);
let mut screens = Vec::with_capacity(n);
@@ -478,7 +479,7 @@ pub(super) fn color_halftone(px: &mut [[u8; 4]], w: usize, h: usize, space: &Pix
let mean = if sum[1] > 1e-6 { f64::from(sum[0] / sum[1]) } else { 0.0 };
// Full strength fills the cell, corners too; none leaves no speck.
let radius = match mean {
m if m >= 254.5 / 255.0 => f64::INFINITY,
m if m >= 254.5 / 255.0 => side / std::f64::consts::SQRT_2 + 0.5 * place.px,
m if m <= 0.5 / 255.0 => 0.0,
m => dot_radius(m) * side,
};
+152 -10
View File
@@ -694,11 +694,6 @@ fn smart_blur_smooths_noise_and_keeps_edges() {
assert_eq!(at(&all, w, 20, 10)[0], 255, "a 155-level step is still past 100");
}
/// FNV-1a of `bytes`.
fn digest(bytes: &[u8]) -> u64 {
bytes.iter().fold(0xcbf2_9ce4_8422_2325, |h, b| (h ^ u64::from(*b)).wrapping_mul(0x0100_0000_01b3))
}
#[test]
fn smart_blur_normal_mode_keeps_its_pixels() {
let (w, h) = (48, 40);
@@ -706,7 +701,6 @@ fn smart_blur_normal_mode_keeps_its_pixels() {
let a = if x > 4 && y < 36 { 255 } else { 128 };
[((x * 5 + y) as u8).min(a), ((y * 6) as u8).min(a), (((x * y) % 97) as u8).min(a), a]
});
let mut sums = Vec::new();
for p in [json!({}), json!({"radius": 2, "threshold": 10, "quality": "high"}), json!({"radius": 12, "threshold": 40, "quality": "low"})] {
let mut d = src.clone();
fx("blur.smart", p.clone()).apply(&mut d, w, h, &space(w, h));
@@ -715,10 +709,127 @@ fn smart_blur_normal_mode_keeps_its_pixels() {
p["blurMode"] = json!("normal");
fx("blur.smart", p).apply(&mut normal, w, h, &space(w, h));
assert_eq!(d, normal);
sums.push(digest(&d));
}
// The pixels Smart Blur gave before it had a mode.
assert_eq!(sums, [11495339692959753241, 14281410954765351056, 5111933201350526354]);
}
/// Smart Blur at radius 1 averages each pixel with the neighbours whose channels, alpha included,
/// all lie within the threshold: grays 100 and 110 average to 105 each, 200 is 90 levels from 110
/// and stays, and the two grays 100 after it have the same color but alpha 255 and 128, so neither
/// takes the other.
#[test]
fn smart_blur_averages_only_the_neighbours_within_the_threshold() {
let (w, h) = (5, 1);
let src = image(w, h, |x, _| match x {
0 => [100, 100, 100, 255],
1 => [110, 110, 110, 255],
2 => [200, 200, 200, 255],
3 => [100, 100, 100, 255],
_ => [100, 100, 100, 128],
});
let mut d = src.clone();
fx("blur.smart", json!({"radius": 1, "threshold": 20})).apply(&mut d, w, h, &space(w, h));
assert_eq!(at(&d, w, 0, 0), [105, 105, 105, 255]);
assert_eq!(at(&d, w, 1, 0), [105, 105, 105, 255]);
assert_eq!(at(&d, w, 2, 0), [200, 200, 200, 255]);
assert_eq!(at(&d, w, 3, 0), at(&src, w, 3, 0));
assert_eq!(at(&d, w, 4, 0), at(&src, w, 4, 0));
}
/// Smart Blur at radius 12 reads its neighbours from a box-blurred copy. Next to a step from gray
/// 100 to gray 200 that copy holds values between them, so at threshold 50 the pixel on the dark
/// side of the step takes in some lighter gray and the pixel on the light side some darker gray,
/// while pixels more than 15 pixels from the step keep their gray. Medium quality takes in less of
/// the other gray than low, and at threshold 30 the pixels next to the step keep their gray.
#[test]
fn smart_blur_at_a_wide_radius_reads_the_blurred_copy_next_to_an_edge() {
let (w, h) = (60, 40);
let src = image(w, h, |x, _| grey(if x < 30 { 100 } else { 200 }));
let mut d = src.clone();
fx("blur.smart", json!({"radius": 12, "threshold": 50, "quality": "low"})).apply(&mut d, w, h, &space(w, h));
let dark = at(&d, w, 29, 20)[0];
let light = at(&d, w, 30, 20)[0];
assert!((101..=150).contains(&dark), "the dark side takes in some lighter gray: {dark}");
assert!((150..=199).contains(&light), "the light side takes in some darker gray: {light}");
assert_eq!(at(&d, w, 10, 20), grey(100));
assert_eq!(at(&d, w, 50, 20), grey(200));
// Medium quality spreads 7 samples instead of 5, read from a copy blurred over 2 pixels instead
// of 3, so less of the other gray reaches the pixels next to the step.
let mut medium = src.clone();
fx("blur.smart", json!({"radius": 12, "threshold": 50, "quality": "medium"})).apply(&mut medium, w, h, &space(w, h));
let (medium_dark, medium_light) = (at(&medium, w, 29, 20)[0], at(&medium, w, 30, 20)[0]);
assert!(100 < medium_dark && medium_dark < dark, "medium {medium_dark}, low {dark}");
assert!(light < medium_light && medium_light < 200, "medium {medium_light}, low {light}");
// At threshold 30 the blurred values next to the step are too far from both grays, and the
// pixels on either side keep their gray.
let mut sharp = src.clone();
fx("blur.smart", json!({"radius": 12, "threshold": 30, "quality": "low"})).apply(&mut sharp, w, h, &space(w, h));
assert_eq!(at(&sharp, w, 29, 20), grey(100));
assert_eq!(at(&sharp, w, 30, 20), grey(200));
}
/// Smart Blur at radius 12 and low quality samples offsets 0, 6 and 12 pixels along each axis,
/// in both directions, within distance 12.5. A one-column gray-200 stripe at x = 30 on gray 100
/// becomes (6 * 100 + 200) / 7, about 114.29, in the copy box-blurred with radius 3. For the
/// gray-100 pixel at (24, 20), only the three samples at x = 30 have blurred values above 100.
/// Their own value 200 is outside threshold 30, so they are excluded and the result stays 100.
/// Including them would average ten samples of 100 with three of about 114.29 and round to 103.
#[test]
fn smart_blur_at_a_wide_radius_rejects_a_stripes_own_value_outside_the_threshold() {
let (w, h) = (60, 40);
let src = image(w, h, |x, _| grey(if x == 30 { 200 } else { 100 }));
let mut d = src.clone();
fx("blur.smart", json!({"radius": 12, "threshold": 30, "quality": "low"})).apply(&mut d, w, h, &space(w, h));
assert_eq!(at(&d, w, 24, 20), grey(100));
}
/// Smart Blur at radius 2 reaches two pixels each way: grays 100, 110 and 120 lie within 20 levels
/// of each other and all average to 110 (at radius 1 the ends would give 105 and 115), 200 and 210
/// average to 205, and 60 is too far from both groups and stays.
#[test]
fn smart_blur_at_radius_two_averages_the_neighbours_two_pixels_away() {
let (w, h) = (6, 1);
let src = image(w, h, |x, _| grey([100, 110, 120, 200, 210, 60][x]));
let mut d = src.clone();
fx("blur.smart", json!({"radius": 2, "threshold": 20, "quality": "high"})).apply(&mut d, w, h, &space(w, h));
let want = image(w, h, |x, _| grey([110, 110, 110, 205, 205, 60][x]));
assert_eq!(d, want);
}
/// Smart Blur at radius 2 and high quality reads the original pixels within distance 2.5.
/// The center at (2, 2) is gray 100, one neighbor is gray 120, and the rest are gray 200,
/// outside threshold 20. A neighbor at (4, 2) is two pixels away, so the center averages
/// (100 + 120) / 2 = 110. A neighbor at (4, 4) is sqrt(8), about 2.83 pixels away, so it is
/// excluded and the center stays 100. Reading the whole square would give 110 in both cases.
#[test]
fn smart_blur_at_radius_two_keeps_the_neighbours_inside_the_disc() {
let (w, h) = (5, 5);
for ((nx, ny), want) in [((4, 2), 110), ((4, 4), 100)] {
let src = image(w, h, |x, y| match (x, y) {
(2, 2) => grey(100),
p if p == (nx, ny) => grey(120),
_ => grey(200),
});
let mut d = src.clone();
fx("blur.smart", json!({"radius": 2, "threshold": 20, "quality": "high"})).apply(&mut d, w, h, &space(w, h));
assert_eq!(at(&d, w, 2, 2), grey(want), "neighbor at ({nx}, {ny})");
}
}
/// Smart Blur's default radius 3 and medium quality (7 samples) read every integer offset
/// in the 7 by 7 square without prefiltering, keeping offsets within distance 3.5.
/// The center at (3, 3) is gray 100, its neighbor at (6, 3) is gray 120, and the rest are
/// gray 200, outside the default threshold 25. The center averages (100 + 120) / 2 = 110.
/// A search limited to two pixels would leave the center at 100.
#[test]
fn smart_blur_default_radius_averages_the_neighbour_three_pixels_away() {
let (w, h) = (7, 7);
let mut d = image(w, h, |x, y| match (x, y) {
(3, 3) => grey(100),
(6, 3) => grey(120),
_ => grey(200),
});
fx("blur.smart", json!({})).apply(&mut d, w, h, &space(w, h));
assert_eq!(at(&d, w, 3, 3), grey(110));
}
/// Smart Blur's test image: grays 56 and 64 in a checkerboard for x < 3 and 66 and 74 for x in 3..6
@@ -1070,13 +1181,44 @@ fn color_halftone_screens_midtones_into_dots_and_keeps_white_and_black() {
let mut half = image(w, h, |x, _| if x < 32 { grey(160) } else { [0; 4] });
halftone.apply(&mut half, w, h, &space(w, h));
assert!((0..h).all(|y| (32..w).all(|x| at(&half, w, x, y) == [0; 4])));
// Dots are bigger where the image is brighter.
// Brighter areas have fewer dark pixels.
let mut ramp = image(w, h, |x, _| grey((x * 4) as u8));
halftone.apply(&mut ramp, w, h, &space(w, h));
let lit = |x0: usize| (0..h).flat_map(|y| (x0..x0 + 16).map(move |x| (x, y))).filter(|(x, y)| at(&ramp, w, *x, *y)[0] > 127).count();
assert!(lit(8) < lit(40), "{} < {}", lit(8), lit(40));
}
#[test]
fn color_halftone_draws_dark_dots_on_light_rgb() {
let (w, h) = (64, 64);
let halftone = fx("pixelate.colorHalftone", json!({"maxRadius": 8, "channel1": 0, "channel2": 0, "channel3": 0}));
let mut d = image(w, h, |_, _| grey(192));
halftone.apply(&mut d, w, h, &space(w, h));
assert_eq!(at(&d, w, 37, 37), grey(0));
assert_eq!(at(&d, w, 32, 32), grey(255));
}
#[test]
fn color_halftone_full_coverage_only_overlaps_the_edge_of_an_empty_neighbor() {
let (w, h) = (96, 64);
let source = image(w, h, |x, _| grey(if x < w / 2 { 0 } else { 255 }));
let mut screened = source.clone();
fx("pixelate.colorHalftone", json!({"maxRadius": 8, "channel1": 0, "channel2": 0, "channel3": 0})).apply(&mut screened, w, h, &space(w, h));
let half_cell = (8.0 * std::f64::consts::SQRT_2 / 2.0) as usize;
let (edge, y) = (w / 2, h / 2 + half_cell);
assert_eq!(at(&screened, w, edge - half_cell, y), grey(0), "the full cell keeps its center");
assert_eq!(at(&screened, w, edge, y), grey(0), "the round dot crosses the straight cell edge");
let fringe = at(&screened, w, edge + 2, y)[0];
assert!(fringe > 0 && fringe < 255, "the last overlapping column is antialiased: {fringe}");
// With an 8 px radius and the grid aligned to this edge, the circle and its antialiasing
// can reach only the first three columns of white. Check every row, including cell corners.
for y in 0..h {
for x in edge + 3..w {
assert_eq!(at(&screened, w, x, y), grey(255), "unexpected ink at ({x}, {y})");
}
}
}
#[test]
fn color_halftone_sizes_its_dots_in_pixels_of_the_raster_effects_resolution() {
// Max Radius counts the document's raster grid pixels (#3260): 16 px at 144 ppi (lines half a
+3 -2
View File
@@ -1343,10 +1343,11 @@ fn transform_copies_of_images_stop_at_the_reach_limit() {
fn pucker_bloat_moves_anchors_in_opposite_directions() {
let bloat = run("distort.puckerBloat", json!({"amount": 50}), &square());
let a = bloat.subpaths[0].anchors[0].p;
assert!(a.x > 0.0 && a.y > 0.0, "bloat pulls corners in: {a:?}");
// Half the amount of the way to the centre (50, 50): 25% of 50 pt.
assert!((a.x - 12.5).abs() < 1e-9 && (a.y - 12.5).abs() < 1e-9, "bloat pulls corners in: {a:?}");
let pucker = run("distort.puckerBloat", json!({"amount": -50}), &square());
let a = pucker.subpaths[0].anchors[0].p;
assert!(a.x < 0.0 && a.y < 0.0, "pucker pushes corners out: {a:?}");
assert!((a.x + 12.5).abs() < 1e-9 && (a.y + 12.5).abs() < 1e-9, "pucker pushes corners out: {a:?}");
assert_eq!(run("distort.puckerBloat", json!({"amount": 0}), &square()), square());
}
+119 -5
View File
@@ -5,11 +5,14 @@
//! others; and Set Size of Each gives every selected object an exact width and height. Places and
//! sizes are measured and set as `object.setBounds` does. Match Objects gives the other selected
//! objects the size, bounding-box angle and stacking place of one of them. Group Overlapping Objects groups the
//! objects whose visual bounds overlap, Randomize Opacity gives each selected object a random
//! objects whose visual bounds overlap, Group by Row groups them by the rows (or columns) their
//! visual bounds share, Randomize Opacity gives each selected object a random
//! opacity, and Sort Objects sorts the selected objects by one attribute and gives them another in
//! that order. Its submenu (Object › Plug-ins › Arrange Tools), its dialogs and Zoom to Selection
//! (a view command) are the UI's.
//! that order. Mark Bounds of Each ([`marks`]) draws marks on the bounds of each selected object.
//! Its submenu (Object › Plug-ins › Arrange Tools), its dialogs and Zoom to Selection (a view
//! command) are the UI's.
pub mod marks;
#[cfg(test)]
mod tests;
@@ -18,7 +21,7 @@ use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_color::recolor::Rng;
use vectorcraft_doc::{Node, NodeId, OrientedBox};
use vectorcraft_doc::{Node, NodeId, NodeKind, OrientedBox};
use vectorcraft_geom::{Affine, Point, Rect, Vec2};
use vectorcraft_render::effects;
@@ -108,6 +111,15 @@ pub fn specs() -> Vec<CommandSpec> {
has_multi,
group_overlapping
),
cmd!(
"addon.arrange.groupRows",
"Group by Row",
["Object", "Plug-ins", "Arrange Tools"],
None,
"{direction?: \"row\" (objects whose vertical extents overlap) | \"column\" (objects whose horizontal extents overlap) (\"row\" when omitted; null is invalid)} group the selected objects (the top-level ones, at most 20000) into one group for each row (column), as one undo step. Parameters must be an object. An object joins a row when its visual bounds overlap the row's extent across it. Measurement includes strokes and vector effects, measures a clipping group by its mask, and excludes raster effects such as shadows, glows, and blurs. Extents that only touch stay apart, and an object that overlaps two rows joins them into one. Only objects in the same layer or group and on the same artboard (the one holding the object's center, else the one it overlaps most) share a row. Objects outside all artboards, locked or hidden objects, clipping masks, layers, and sublayers stay in place. Every grouping candidate must have a parent that is a layer or group. The command rejects selections containing editable live blend keys, direct children of Shaper groups, live compound shapes, Objects on Path groups, or Live Paint groups, and any descendants of live graphs. Complete live groups and graphs can be grouped with other artwork. An object alone in its row stays as it is, and each new group goes where its frontmost member was in the stacking order; the new groups (top to bottom, or left to right) and the objects left alone stay selected. A run with no row of two or more objects makes no step → {groups: [id…], grouped (how many objects went into groups)}",
has_multi,
group_rows
),
cmd!(
"addon.arrange.randomizeOpacity",
"Randomize Opacity",
@@ -127,6 +139,9 @@ pub fn specs() -> Vec<CommandSpec> {
sort
),
]
.into_iter()
.chain(marks::specs())
.collect()
}
/// Exactly two objects are selected (Swap Objects).
@@ -577,11 +592,110 @@ fn group_overlapping(s: &mut Session, _: &Value) -> Result<Value> {
roots.iter().filter_map(|id| Some((*id, (d.parent_of(*id), effects::preview::bounds_of(d, &[*id], true)?)))).collect();
let keyed: Vec<(Option<NodeId>, Rect)> = items.iter().map(|(_, k)| *k).collect();
let sets: Vec<Vec<NodeId>> = overlapping(&keyed).into_iter().map(|set| set.iter().filter_map(|i| Some(items.get(*i)?.0)).collect()).collect();
group_each(s, "Group Overlapping Objects", &roots, sets)
}
/// The rows of `items` (each a key and an extent `(start, end)` along the axis across the rows): the sets of
/// two or more (each in the order given) among items of the same key whose extents overlap, chains included.
/// Extents that only touch stay apart. Sorted by start, then by end, each item joins its key's open row when it
/// starts before that row ends, so the rows come out in order along the axis, and an extent with no length at
/// another's start stays apart from it whatever their order. Adding 0.0 turns -0.0 into 0.0, which
/// `total_cmp` would otherwise order first.
fn rows_of<K: Eq + std::hash::Hash + Copy>(items: &[(K, (f64, f64))]) -> Vec<Vec<usize>> {
let items: Vec<(K, (f64, f64))> = items.iter().map(|(k, (start, end))| (*k, (start + 0.0, end + 0.0))).collect();
let mut order: Vec<usize> = (0..items.len()).collect();
order.sort_by(|a, b| items[*a].1.0.total_cmp(&items[*b].1.0).then(items[*a].1.1.total_cmp(&items[*b].1.1)));
let mut rows: Vec<Vec<usize>> = vec![];
// Each key's open row: its index in `rows` and where it ends.
let mut open: HashMap<K, (usize, f64)> = HashMap::new();
for i in order {
let (key, (start, end)) = items[i];
match open.get_mut(&key) {
Some((row, until)) if start < *until => {
if let Some(r) = rows.get_mut(*row) {
r.push(i);
}
*until = until.max(end);
}
_ => {
open.insert(key, (rows.len(), end));
rows.push(vec![i]);
}
}
}
rows.retain(|r| r.len() > 1);
for r in &mut rows {
r.sort_unstable();
}
rows
}
fn group_rows(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "addon.arrange.groupRows";
if !p.is_object() {
return Err(bad(C, "parameters must be an object"));
}
if p.get("direction").is_some_and(Value::is_null) {
return Err(bad(C, "`direction` must be row or column"));
}
let rows = choice(p, C, "direction", &["row", "column"])?.unwrap_or("row") == "row";
let roots = selected_roots(s)?;
if roots.len() > MAX_OBJECTS {
return Err(bad(C, "too many objects selected (at most 20000)"));
}
let d = &s.doc()?.doc;
let editable_roots: Vec<_> = {
let editable = d.editable();
roots.iter().copied().filter(|id| editable(*id) && d.node(*id).is_some_and(|n| !n.is_layer())).collect()
};
for id in &editable_roots {
let parent = d.parent_of(*id);
let valid_parent = parent.and_then(|parent| d.node(parent)).is_some_and(|n| {
matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. })
&& !n.is_compound_shape()
&& n.extras().shaper.is_none()
&& n.extras().objects_on_path.is_none()
&& !vectorcraft_tools::builder::is_live_paint(n)
});
let in_graph = parent
.and_then(|parent| d.ancestry(parent))
.is_some_and(|ancestors| ancestors.iter().any(|ancestor| d.node(*ancestor).is_some_and(|n| n.extras().graph.is_some())));
if !valid_parent || in_graph {
return Err(bad(C, "selected objects must be in a layer or group without live structural roles"));
}
}
// Each object's row key (its parent and its artboard) and its extent across the rows.
type Keyed = ((NodeId, usize), (f64, f64));
let symbols = d.symbol_boxes();
let items: Vec<(NodeId, Keyed)> = editable_roots
.iter()
.filter_map(|id| {
let parent = d.parent_of(*id)?;
let container = d.node(parent)?;
if container.clips() && container.children().and_then(|c| c.first()).is_some_and(|c| c.id == *id) {
return None;
}
let b = effects::preview::visual_bounds(&symbols.unmeasured(), d.node(*id)?)?;
let extent = if rows { (b.y0, b.y1) } else { (b.x0, b.x1) };
Some((*id, ((parent, d.artboard_for_bounds(b)?), extent)))
})
.collect();
let keyed: Vec<_> = items.iter().map(|(_, k)| *k).collect();
let sets: Vec<Vec<NodeId>> = rows_of(&keyed).into_iter().map(|set| set.iter().filter_map(|i| Some(items.get(*i)?.0)).collect()).collect();
let mut selection = roots;
selection.extend(s.doc()?.selection.objects.iter().copied().filter(|id| d.node(*id).is_some_and(|n| n.is_layer())));
group_each(s, if rows { "Group by Row" } else { "Group by Column" }, &selection, sets)
}
/// Put each of `sets` (two or more of the selected top-level objects `roots`, each in stacking order) into a
/// new group of its own at its frontmost member's place, as undo step `label`, and select the new groups and
/// the objects of `roots` left alone. No step when `sets` is empty.
fn group_each(s: &mut Session, label: &str, roots: &[NodeId], sets: Vec<Vec<NodeId>>) -> Result<Value> {
if sets.is_empty() {
return Ok(json!({ "groups": [], "grouped": 0 }));
}
let grouped: std::collections::HashSet<NodeId> = sets.iter().flatten().copied().collect();
let groups = s.edit("Group Overlapping Objects", |d, sel| {
let groups = s.edit(label, |d, sel| {
// Every group at once: the members behind each front one go, then each front one is
// replaced by its group (one pass over the tree each, however many groups).
let (mut places, mut behind, mut groups) = (vec![], vec![], vec![]);
@@ -0,0 +1,147 @@
//! Mark Bounds of Each (`addon.arrange.markBounds`; Object › Plug-ins › Arrange Tools › Mark Bounds
//! of Each…): corner marks, or a rectangle, on the bounds of each selected object rather than
//! around the whole selection, stroked in a color of their own and stacked directly above the
//! object, as one undo step.
#[cfg(test)]
mod tests;
use std::collections::HashMap;
use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_color::{Color, Paint};
use vectorcraft_doc::{Appearance, Document, Node, NodeId};
use vectorcraft_geom::{PathData, Point, Rect, SubPath, shapes};
use vectorcraft_render::drawn_bounds_with;
use super::super::super::edit::selected_roots;
use super::super::super::object::choice;
use super::super::super::paint::new_color;
use super::super::super::{CommandSpec, bad, cmd, color_param, has_selection};
use super::{LEAST, LIMIT, MAX_OBJECTS, number_in};
use crate::{Result, Session};
/// The command.
pub const COMMAND: &str = "addon.arrange.markBounds";
/// The heaviest stroke (pt) the marks take, and the lightest.
const MAX_WEIGHT: f64 = 1000.0;
const MIN_WEIGHT: f64 = 0.01;
/// A side shorter than this (pt) is no side: its marks are drawn as lines along the other one.
const FLAT: f64 = 1e-9;
pub fn specs() -> Vec<CommandSpec> {
vec![cmd!(
"addon.arrange.markBounds",
"Mark Bounds of Each",
["Object", "Plug-ins", "Arrange Tools"],
None,
"{style?: \"corners\" (an L-shaped mark on each corner, its two legs running inward along the edges) | \"rectangle\" (a rectangle on the bounds) (\"corners\"), bounds?: \"geometric\" (strokes not counted) | \"visual\" (strokes, brush art and effects as drawn) (\"geometric\"), length?: pt 0.001..1000000 (10; corners: each leg's length, at most half the side it runs along), weight?: pt 0.01..1000 (1), color?: color (\"#ff0000\"; an RGB color takes the document's color mode)} draw marks on the bounds of each selected object (the top-level ones, at most 20000) as new art: a group of four corner marks, or one rectangle, with no fill and the stroke given, stacked directly above its object (above the outermost clip group or clipping sublayer that holds it, so the clip does not hide them). A clip group is measured by its clipping path and other groups by their members together. Guides, and objects without bounds such as empty groups, get no marks. The marks are selected; one undo step, and none when nothing gets marks (an error) → {ids: [the new marks…], count}",
has_selection,
mark_bounds
)]
}
/// The four corners of `r`, each with the directions its legs run in (inward), the corners that
/// fall on an earlier one left out.
fn corners(r: Rect) -> Vec<(Point, f64, f64)> {
let mut out: Vec<(Point, f64, f64)> = vec![];
for (x, y, sx, sy) in [(r.x0, r.y0, 1.0, 1.0), (r.x1, r.y0, -1.0, 1.0), (r.x1, r.y1, -1.0, -1.0), (r.x0, r.y1, 1.0, -1.0)] {
let at = Point::new(x, y);
if out.iter().all(|(p, _, _)| (p.x - at.x).abs() > FLAT || (p.y - at.y).abs() > FLAT) {
out.push((at, sx, sy));
}
}
out
}
/// The corner marks of `r` with legs `length` long, each at most half its side: one open path per
/// corner, a line where `r` has no width or no height.
fn corner_paths(r: Rect, length: f64) -> Vec<PathData> {
let (lx, ly) = (length.min(r.width() / 2.0), length.min(r.height() / 2.0));
corners(r)
.into_iter()
.filter_map(|(p, sx, sy)| {
let across = Point::new(p.x + sx * lx, p.y);
let down = Point::new(p.x, p.y + sy * ly);
let points = match (lx > FLAT, ly > FLAT) {
(true, true) => vec![across, p, down],
(true, false) => vec![across, p],
(false, true) => vec![p, down],
(false, false) => return None,
};
Some(PathData::single(SubPath::polyline(&points, false)))
})
.collect()
}
/// Where the marks of object `id` go: directly above it, or above the outermost clip group or
/// clipping sublayer that holds it at any depth, which would otherwise clip them. A top-level layer
/// with a clipping mask holds its marks too, since nothing lies outside it.
fn anchor(d: &Document, id: NodeId) -> NodeId {
let (mut at, mut outermost) = (id, id);
while let Some(up) = d.parent_of(at) {
if d.node(up).is_some_and(|n| n.clips()) && d.parent_of(up).is_some() {
outermost = up;
}
at = up;
}
outermost
}
fn mark_bounds(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = COMMAND;
let rectangle = choice(p, C, "style", &["corners", "rectangle"])? == Some("rectangle");
let visual = choice(p, C, "bounds", &["geometric", "visual"])? == Some("visual");
let length = number_in(p, "length", 10.0, (LEAST, LIMIT), C)?;
let weight = number_in(p, "weight", 1.0, (MIN_WEIGHT, MAX_WEIGHT), C)?;
let color = new_color(s, p, color_param(p, "color", C)?.unwrap_or(Color::rgb(1.0, 0.0, 0.0)));
let roots = selected_roots(s)?;
if roots.len() > MAX_OBJECTS {
return Err(bad(C, "too many objects selected (at most 20000)"));
}
let d = &s.doc()?.doc;
let symbols = d.symbol_boxes();
let mut marked: Vec<(NodeId, Rect)> = Vec::with_capacity(roots.len());
for id in roots {
let Some(n) = d.node(id).filter(|n| !n.is_guide()) else { continue };
let bounds = if visual { drawn_bounds_with(&symbols, n) } else { n.geometric_bounds_with(&symbols) };
if let Some(r) = bounds.filter(|r| r.width() > FLAT || r.height() > FLAT) {
marked.push((anchor(d, id), r));
}
}
if marked.is_empty() {
return Err(bad(C, "nothing to mark: the selection has no bounds"));
}
let ap = Appearance::basic(Paint::None, Paint::solid(color), weight);
let ids = s.edit("Mark Bounds of Each", |d, sel| {
// Each anchor once, its objects' marks in stacking order from the back.
let mut lists: Vec<(NodeId, Vec<Node>)> = vec![];
let mut at: HashMap<NodeId, usize> = HashMap::new();
let mut out = Vec::with_capacity(marked.len());
for (anchor, r) in &marked {
let node = if rectangle {
let mut n = Node::path(d.alloc_id(), shapes::rectangle(*r), ap.clone());
n.name = Some("Bounds".into());
n
} else {
let children = corner_paths(*r, length).into_iter().map(|path| Arc::new(Node::path(d.alloc_id(), path, ap.clone()))).collect();
let mut g = Node::group(d.alloc_id(), children);
g.name = Some("Corner Marks".into());
g
};
out.push(node.id);
let k = *at.entry(*anchor).or_insert_with(|| {
lists.push((*anchor, vec![]));
lists.len() - 1
});
if let Some((_, nodes)) = lists.get_mut(k) {
nodes.push(node);
}
}
d.insert_beside(lists, false)?;
sel.set(out.iter().copied());
Ok(out)
})?;
Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "count": ids.len() }))
}
@@ -0,0 +1,353 @@
//! Mark Bounds of Each: the marks each object gets, where they go in the stacking order, how
//! groups, clip groups, strokes and guides are measured, one undo step, and bad params refused.
use serde_json::{Value, json};
use vectorcraft_color::{Color, Paint};
use vectorcraft_doc::{Node, NodeId};
use vectorcraft_geom::Rect;
use super::COMMAND;
use crate::Session;
/// A new document whose new art has no stroke, so visual and geometric bounds agree.
fn session() -> Session {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
s
}
fn rect(s: &mut Session, x: f64, y: f64, w: f64, h: f64) -> NodeId {
NodeId(s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": w, "height": h})).unwrap()["id"].as_u64().unwrap())
}
fn select(s: &mut Session, ids: &[NodeId]) {
s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})).unwrap();
}
fn steps(s: &Session) -> usize {
s.doc().unwrap().history.undo.len()
}
fn node(s: &Session, id: NodeId) -> Node {
s.doc().unwrap().doc.node(id).unwrap().clone()
}
fn ids_of(v: &Value) -> Vec<NodeId> {
v["ids"].as_array().unwrap().iter().map(|i| NodeId(i.as_u64().unwrap())).collect()
}
/// The ids of the children of `parent`, in stacking order from the back.
fn children(s: &Session, parent: NodeId) -> Vec<NodeId> {
node(s, parent).children().unwrap().iter().map(|n| n.id).collect()
}
fn parent(s: &Session, id: NodeId) -> NodeId {
s.doc().unwrap().doc.parent_of(id).unwrap()
}
/// Each path of the mark `id` (a group's members, or the path itself) as its points.
fn lines(s: &Session, id: NodeId) -> Vec<Vec<(f64, f64)>> {
let n = node(s, id);
let paths: Vec<Node> = match n.children() {
Some(c) => c.iter().map(|c| (**c).clone()).collect(),
None => vec![n],
};
paths
.iter()
.map(|p| {
let path = p.path_data().unwrap();
path.subpaths[0].anchors.iter().map(|a| ((a.p.x * 1e6).round() / 1e6, (a.p.y * 1e6).round() / 1e6)).collect()
})
.collect()
}
fn near(a: Rect, b: (f64, f64, f64, f64)) -> bool {
[(a.x0, b.0), (a.y0, b.1), (a.x1, b.2), (a.y1, b.3)].iter().all(|(x, y)| (x - y).abs() < 1e-6)
}
fn marks_bounds(s: &Session, id: NodeId) -> Rect {
node(s, id).geometric_bounds().unwrap()
}
#[test]
fn each_object_gets_inward_corner_marks_above_it_in_one_step() {
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 100.0, 50.0);
let b = rect(&mut s, 200.0, 100.0, 40.0, 40.0);
let layer = parent(&s, a);
select(&mut s, &[a, b]);
let n = steps(&s);
let r = s.execute(COMMAND, &json!({})).unwrap();
assert_eq!(steps(&s), n + 1, "one undo step");
let marks = ids_of(&r);
assert_eq!((marks.len(), r["count"].as_u64()), (2, Some(2)));
// Directly above each object, not around the selection.
assert_eq!(children(&s, layer), vec![a, marks[0], b, marks[1]]);
assert_eq!(s.doc().unwrap().selection.objects.to_vec(), marks, "the marks are selected");
assert_eq!(node(&s, marks[0]).name.as_deref(), Some("Corner Marks"));
assert_eq!(
lines(&s, marks[0]),
vec![
vec![(10.0, 0.0), (0.0, 0.0), (0.0, 10.0)],
vec![(90.0, 0.0), (100.0, 0.0), (100.0, 10.0)],
vec![(90.0, 50.0), (100.0, 50.0), (100.0, 40.0)],
vec![(10.0, 50.0), (0.0, 50.0), (0.0, 40.0)],
]
);
assert!(near(marks_bounds(&s, marks[1]), (200.0, 100.0, 240.0, 140.0)));
// A red 1 pt stroke and no fill.
let group = node(&s, marks[1]);
let ap = &group.children().unwrap()[0].appearance;
assert_eq!((ap.fill_paint(), ap.stroke_paint(), ap.stroke_width()), (Paint::None, Paint::solid(Color::rgb(1.0, 0.0, 0.0)), 1.0));
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(children(&s, layer), vec![a, b]);
}
#[test]
fn length_weight_color_and_the_rectangle_style() {
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 30.0, 100.0);
select(&mut s, &[a]);
let r = s.execute(COMMAND, &json!({"length": 40, "weight": 2.5, "color": "#0000ff"})).unwrap();
let marks = ids_of(&r);
// A leg is never longer than half its side, so opposite marks do not overlap.
assert_eq!(lines(&s, marks[0])[0], vec![(15.0, 0.0), (0.0, 0.0), (0.0, 40.0)]);
let group = node(&s, marks[0]);
let ap = &group.children().unwrap()[0].appearance;
assert_eq!((ap.stroke_paint(), ap.stroke_width()), (Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 2.5));
s.execute("edit.undo", &json!({})).unwrap();
let r = s.execute(COMMAND, &json!({"style": "rectangle"})).unwrap();
let mark = ids_of(&r)[0];
let rect = node(&s, mark);
assert!(rect.children().is_none() && rect.path_data().unwrap().subpaths[0].closed, "one closed path");
assert_eq!(rect.name.as_deref(), Some("Bounds"));
assert!(near(marks_bounds(&s, mark), (0.0, 0.0, 30.0, 100.0)));
}
#[test]
fn a_leg_is_at_most_half_the_side_it_runs_along_vertically() {
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 200.0, 20.0);
select(&mut s, &[a]);
let r = s.execute(COMMAND, &json!({"length": 30})).unwrap();
assert_eq!(
lines(&s, ids_of(&r)[0]),
vec![
vec![(30.0, 0.0), (0.0, 0.0), (0.0, 10.0)],
vec![(170.0, 0.0), (200.0, 0.0), (200.0, 10.0)],
vec![(170.0, 20.0), (200.0, 20.0), (200.0, 10.0)],
vec![(30.0, 20.0), (0.0, 20.0), (0.0, 10.0)],
]
);
}
#[test]
fn geometric_bounds_leave_strokes_out_and_visual_bounds_count_them() {
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0);
select(&mut s, &[a]);
s.execute("paint.setStroke", &json!({"color": "#000000"})).unwrap();
s.execute("stroke.set", &json!({"weight": 4})).unwrap();
let r = s.execute(COMMAND, &json!({"style": "rectangle"})).unwrap();
assert!(near(marks_bounds(&s, ids_of(&r)[0]), (0.0, 0.0, 20.0, 20.0)), "{:?}", marks_bounds(&s, ids_of(&r)[0]));
s.execute("edit.undo", &json!({})).unwrap();
let r = s.execute(COMMAND, &json!({"style": "rectangle", "bounds": "visual"})).unwrap();
assert!(near(marks_bounds(&s, ids_of(&r)[0]), (-2.0, -2.0, 22.0, 22.0)), "{:?}", marks_bounds(&s, ids_of(&r)[0]));
}
#[test]
fn visual_bounds_enclose_a_drop_shadow_and_geometric_bounds_leave_it_out() {
let mut s = session();
let a = rect(&mut s, 50.0, 50.0, 20.0, 20.0);
select(&mut s, &[a]);
let geometry = marks_bounds(&s, a);
let (dx, dy) = (12.0, 8.0);
s.execute("effect.apply", &json!({"effect": "stylize.dropShadow", "item": null, "params": {"x": dx, "y": dy, "blur": 0}})).unwrap();
let shadow = Rect::new(geometry.x0 + dx, geometry.y0 + dy, geometry.x1 + dx, geometry.y1 + dy);
let reach = geometry.union(shadow);
let encloses = |r: Rect| r.x0 <= reach.x0 && r.y0 <= reach.y0 && r.x1 >= reach.x1 && r.y1 >= reach.y1;
let r = s.execute(COMMAND, &json!({"style": "rectangle", "bounds": "geometric"})).unwrap();
let geometric = marks_bounds(&s, ids_of(&r)[0]);
assert!(near(geometric, (geometry.x0, geometry.y0, geometry.x1, geometry.y1)));
assert!(!encloses(geometric), "the geometric mark leaves the shadow outside");
s.execute("edit.undo", &json!({})).unwrap();
let r = s.execute(COMMAND, &json!({"style": "rectangle", "bounds": "visual"})).unwrap();
let visual = marks_bounds(&s, ids_of(&r)[0]);
assert!(encloses(visual), "the visual mark encloses the artwork and its shadow: {visual:?}");
}
#[test]
fn visual_bounds_enclose_brush_art_on_paths_and_in_groups() {
for grouped in [false, true] {
let mut s = session();
let path = NodeId(s.execute("shape.line", &json!({"x1": 50, "y1": 50, "x2": 150, "y2": 50})).unwrap()["id"].as_u64().unwrap());
select(&mut s, &[path]);
s.execute("paint.setStroke", &json!({"color": "#000000"})).unwrap();
s.execute("stroke.set", &json!({"weight": 1})).unwrap();
s.execute("brush.apply", &json!({"name": "Dots"})).unwrap();
let target = if grouped {
s.execute("object.group", &json!({})).unwrap();
parent(&s, path)
} else {
path
};
select(&mut s, &[target]);
let geometry = marks_bounds(&s, path);
let d = &s.doc().unwrap().doc;
let source = d.node(target).unwrap();
let painted = vectorcraft_render::painted_bounds(d, source).unwrap();
let drawn = vectorcraft_render::drawn_bounds(d, source).unwrap();
let base = vectorcraft_render::effect_bounds(&d.symbol_boxes(), source).unwrap();
assert!(drawn.y0 < base.y0 && drawn.y1 > base.y1, "brush art reaches past the base stroke: {drawn:?}, {base:?}");
let encloses = |r: Rect| r.x0 <= drawn.x0 && r.y0 <= drawn.y0 && r.x1 >= drawn.x1 && r.y1 >= drawn.y1;
let r = s.execute(COMMAND, &json!({"style": "rectangle", "bounds": "geometric"})).unwrap();
let geometric = marks_bounds(&s, ids_of(&r)[0]);
assert!(near(geometric, (geometry.x0, geometry.y0, geometry.x1, geometry.y1)));
assert!(!encloses(geometric), "the geometric mark leaves brush art outside");
s.execute("edit.undo", &json!({})).unwrap();
let r = s.execute(COMMAND, &json!({"style": "rectangle", "bounds": "visual"})).unwrap();
let visual = marks_bounds(&s, ids_of(&r)[0]);
assert!(near(visual, (drawn.x0, drawn.y0, drawn.x1, drawn.y1)), "the visual mark follows the drawn bounds: {visual:?}, {drawn:?}");
assert!(encloses(visual), "the visual mark encloses the brush art: {visual:?}, {drawn:?}");
assert!(
visual.x0 > painted.x0 && visual.y0 > painted.y0 && visual.x1 < painted.x1 && visual.y1 < painted.y1,
"the visual mark stays inside the culling margin: {visual:?}, {painted:?}"
);
}
}
#[test]
fn groups_by_their_members_and_clip_groups_by_the_clipping_path() {
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
let b = rect(&mut s, 50.0, 30.0, 10.0, 10.0);
select(&mut s, &[a, b]);
s.execute("object.group", &json!({})).unwrap();
let group = parent(&s, a);
let art = rect(&mut s, 100.0, 100.0, 200.0, 150.0);
let clip = rect(&mut s, 150.0, 120.0, 50.0, 40.0);
select(&mut s, &[art, clip]);
s.execute("object.clippingMask.make", &json!({})).unwrap();
let clip_group = parent(&s, art);
let layer = parent(&s, group);
select(&mut s, &[group, clip_group]);
let r = s.execute(COMMAND, &json!({"style": "rectangle"})).unwrap();
let marks = ids_of(&r);
assert!(near(marks_bounds(&s, marks[0]), (0.0, 0.0, 60.0, 40.0)), "the members together");
assert!(near(marks_bounds(&s, marks[1]), (150.0, 120.0, 200.0, 160.0)), "the clipping path");
assert_eq!(children(&s, layer), vec![group, marks[0], clip_group, marks[1]]);
s.execute("edit.undo", &json!({})).unwrap();
// An object inside the clip group: its marks go above the clip group, where it does not hide them.
select(&mut s, &[art]);
let r = s.execute(COMMAND, &json!({})).unwrap();
let mark = ids_of(&r)[0];
assert_eq!(children(&s, layer), vec![group, clip_group, mark]);
assert!(near(marks_bounds(&s, mark), (100.0, 100.0, 300.0, 250.0)), "the object's own bounds");
s.execute("edit.undo", &json!({})).unwrap();
// And when a plain group lies between the object and the clip group.
select(&mut s, &[art]);
s.execute("object.group", &json!({})).unwrap();
let inner = parent(&s, art);
let clip_group = parent(&s, clip);
assert_eq!(parent(&s, inner), clip_group);
select(&mut s, &[art]);
let r = s.execute(COMMAND, &json!({})).unwrap();
assert_eq!(children(&s, layer), vec![group, clip_group, ids_of(&r)[0]]);
}
#[test]
fn marks_go_outside_a_clipping_sublayer_but_stay_in_a_clipping_top_layer() {
let mut s = session();
let top = s.doc().unwrap().current_layer().unwrap();
let sub = NodeId(s.execute("layer.newSublayer", &json!({"parent": top.0})).unwrap()["id"].as_u64().unwrap());
s.execute("layer.setCurrent", &json!({"id": sub.0})).unwrap();
let art = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
rect(&mut s, 20.0, 20.0, 10.0, 10.0);
s.execute("select.none", &json!({})).unwrap();
assert!(s.execute("layer.clippingMask.toggle", &json!({"id": sub.0})).unwrap()["clip"].as_bool().unwrap());
select(&mut s, &[art]);
let r = s.execute(COMMAND, &json!({})).unwrap();
assert_eq!(children(&s, top), vec![sub, ids_of(&r)[0]], "above the clipping sublayer");
// A clipping top-level layer has nothing outside it to hold them: they go above the object.
let mut s = session();
let top = s.doc().unwrap().current_layer().unwrap();
let art = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
rect(&mut s, 20.0, 20.0, 10.0, 10.0);
s.execute("select.none", &json!({})).unwrap();
assert!(s.execute("layer.clippingMask.toggle", &json!({"id": top.0})).unwrap()["clip"].as_bool().unwrap());
select(&mut s, &[art]);
let r = s.execute(COMMAND, &json!({})).unwrap();
let mark = ids_of(&r)[0];
let stack = children(&s, top);
assert_eq!(stack.iter().position(|id| *id == mark), stack.iter().position(|id| *id == art).map(|i| i + 1), "{stack:?}");
}
#[test]
fn flat_objects_get_lines_and_guides_and_empty_groups_none() {
let mut s = session();
let line = NodeId(s.execute("shape.line", &json!({"x1": 0, "y1": 50, "x2": 100, "y2": 50})).unwrap()["id"].as_u64().unwrap());
select(&mut s, &[line]);
let r = s.execute(COMMAND, &json!({})).unwrap();
// No height: one mark at each end, along the line.
assert_eq!(lines(&s, ids_of(&r)[0]), vec![vec![(10.0, 50.0), (0.0, 50.0)], vec![(90.0, 50.0), (100.0, 50.0)]]);
s.execute("edit.undo", &json!({})).unwrap();
let guide = rect(&mut s, 0.0, 0.0, 20.0, 20.0);
select(&mut s, &[guide]);
s.execute("view.guides.make", &json!({})).unwrap();
select(&mut s, &[guide]);
let layer = s.doc().unwrap().target_parent().unwrap();
let empty = s
.edit("test", |d, _| {
let g = Node::group(d.alloc_id(), vec![]);
let id = g.id;
d.insert(layer, usize::MAX, g)?;
Ok(id)
})
.unwrap();
select(&mut s, &[guide, empty]);
let (before, n) = (s.doc().unwrap().doc.clone(), steps(&s));
let refused = s.execute(COMMAND, &json!({})).unwrap_err().to_string();
assert!(refused.contains("nothing to mark"), "{refused}");
assert_eq!(steps(&s), n, "no undo step");
assert!(*s.doc().unwrap().doc == *before);
// With a real object as well, only it gets marks.
let a = rect(&mut s, 100.0, 100.0, 20.0, 20.0);
select(&mut s, &[guide, empty, a]);
let r = s.execute(COMMAND, &json!({})).unwrap();
assert_eq!(r["count"], 1);
assert!(near(marks_bounds(&s, ids_of(&r)[0]), (100.0, 100.0, 120.0, 120.0)));
}
#[test]
fn bad_params_are_refused_and_it_is_off_without_a_selection() {
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 20.0, 10.0);
select(&mut s, &[a]);
let (before, n) = (s.doc().unwrap().doc.clone(), steps(&s));
for p in [
json!({"style": "cross"}),
json!({"bounds": "preview"}),
json!({"length": 0}),
json!({"length": 1e7}),
json!({"length": "10"}),
json!({"weight": 0}),
json!({"weight": 1001}),
json!({"color": "not a color"}),
json!({"color": "#ff000080"}),
json!({"color": 3}),
] {
assert!(s.execute(COMMAND, &p).is_err(), "{p}");
}
assert_eq!(steps(&s), n);
assert!(*s.doc().unwrap().doc == *before);
s.execute("select.none", &json!({})).unwrap();
assert!(!s.commands().into_iter().find(|c| c.id == COMMAND).unwrap().enabled);
assert!(s.execute(COMMAND, &json!({})).is_err());
}
@@ -779,6 +779,7 @@ fn off_without_a_selection() {
"addon.arrange.size",
"addon.arrange.match",
"addon.arrange.groupOverlapping",
"addon.arrange.groupRows",
"addon.arrange.randomizeOpacity",
"addon.arrange.sort",
] {
@@ -862,6 +863,503 @@ fn group_overlapping_is_off_with_one_object_and_scales_to_many() {
assert!(sets.iter().all(|s| s.len() == 2 && s[1] == s[0] + 1));
}
fn layer_children(s: &Session) -> Vec<NodeId> {
s.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|n| n.id).collect()
}
#[test]
fn group_rows_groups_each_row_and_leaves_loners() {
let mut s = session();
// Row one: a and b (y 0 to 12). c only touches it (from y 12), alone in its row. Row two: d and e.
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
let d = rect(&mut s, 0.0, 40.0, 10.0, 10.0);
let b = rect(&mut s, 20.0, 2.0, 10.0, 10.0);
let c = rect(&mut s, 40.0, 12.0, 10.0, 10.0);
let e = rect(&mut s, 20.0, 45.0, 10.0, 10.0);
select(&mut s, &[a, b, c, d, e]);
let n = steps(&s);
let r = s.execute("addon.arrange.groupRows", &json!({})).unwrap();
assert_eq!(steps(&s), n + 1, "one undo step");
assert_eq!(r["grouped"], json!(4));
let groups = ids_of(&r["groups"]);
assert_eq!(groups.len(), 2);
assert_eq!(children(&s, groups[0]), [a, b], "the top row first, its members in stacking order");
assert_eq!(children(&s, groups[1]), [d, e]);
// Each group where its frontmost member was: a d b c e → group(ab) at b, c, group(de) at e.
assert_eq!(layer_children(&s), [groups[0], c, groups[1]]);
let sel = &s.doc().unwrap().selection.objects;
assert!(sel.contains(&groups[0]) && sel.contains(&groups[1]) && sel.contains(&c) && sel.len() == 3, "{sel:?}");
assert_eq!(s.doc().unwrap().history.undo.last().map(|step| step.label.as_str()), Some("Group by Row"));
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(layer_children(&s), [a, d, b, c, e]);
}
#[test]
fn group_rows_makes_columns_and_joins_rows_an_object_spans() {
let mut s = session();
// Columns: a and b share x 0 to 15, c stands apart.
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
let b = rect(&mut s, 5.0, 50.0, 10.0, 10.0);
let c = rect(&mut s, 30.0, 0.0, 10.0, 10.0);
select(&mut s, &[a, b, c]);
let r = s.execute("addon.arrange.groupRows", &json!({"direction": "column"})).unwrap();
let groups = ids_of(&r["groups"]);
assert_eq!(groups.len(), 1);
assert_eq!(children(&s, groups[0]), [a, b]);
assert_eq!(s.doc().unwrap().history.undo.last().map(|step| step.label.as_str()), Some("Group by Column"));
// By row, p and q lie in two rows until r, reaching from one to the other, joins them.
let mut s = session();
let p = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
let q = rect(&mut s, 50.0, 20.0, 10.0, 10.0);
select(&mut s, &[p, q]);
let n = steps(&s);
let r = s.execute("addon.arrange.groupRows", &json!({"direction": "row"})).unwrap();
assert_eq!((r["grouped"].clone(), steps(&s)), (json!(0), n), "two rows of one: no groups, no step");
let bridge = rect(&mut s, 100.0, 5.0, 10.0, 20.0);
select(&mut s, &[p, q, bridge]);
let r = s.execute("addon.arrange.groupRows", &json!({"direction": "row"})).unwrap();
let groups = ids_of(&r["groups"]);
assert_eq!(groups.len(), 1);
assert_eq!(children(&s, groups[0]), [p, q, bridge]);
}
#[test]
fn group_rows_keeps_layers_and_artboards_apart_and_measures_visual_bounds() {
let mut s = session();
s.execute("artboard.new", &json!({"x": 500, "y": 0, "width": 200, "height": 300})).unwrap();
let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0);
// Touching a's bottom edge: a row of its own until strokes reach over the edge.
let below = rect(&mut s, 50.0, 20.0, 20.0, 20.0);
let far = rect(&mut s, 550.0, 0.0, 20.0, 20.0);
s.execute("layer.new", &json!({})).unwrap();
let other = rect(&mut s, 100.0, 0.0, 20.0, 20.0);
select(&mut s, &[a, below, far, other]);
let n = steps(&s);
let r = s.execute("addon.arrange.groupRows", &json!({})).unwrap();
assert_eq!((r["grouped"].clone(), steps(&s)), (json!(0), n), "another artboard, another layer, a touching edge: no groups");
select(&mut s, &[a, below]);
s.execute("paint.setStroke", &json!({"color": "#000000"})).unwrap();
s.execute("stroke.set", &json!({"weight": 4})).unwrap();
select(&mut s, &[a, below, far, other]);
let r = s.execute("addon.arrange.groupRows", &json!({})).unwrap();
let groups = ids_of(&r["groups"]);
assert_eq!(groups.len(), 1);
assert_eq!(children(&s, groups[0]), [a, below], "the strokes overlap");
let doc = &s.doc().unwrap().doc;
assert_ne!(doc.parent_of(far), Some(groups[0]), "left on its own artboard");
assert_ne!(doc.layer_of(other), doc.layer_of(a), "left in its own layer");
}
#[test]
fn group_rows_measures_clipping_groups_by_their_mask() {
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0);
// A 200 tall object clipped to a 30 tall mask at y 100.
let clipped = rect(&mut s, 50.0, 0.0, 10.0, 200.0);
let mask = rect(&mut s, 40.0, 100.0, 30.0, 30.0);
select(&mut s, &[clipped, mask]);
s.execute("object.clippingMask.make", &json!({})).unwrap();
let group = s.doc().unwrap().selection.objects[0];
let b = rect(&mut s, 100.0, 110.0, 10.0, 10.0);
select(&mut s, &[a, group, b]);
let r = s.execute("addon.arrange.groupRows", &json!({})).unwrap();
let groups = ids_of(&r["groups"]);
assert_eq!(groups.len(), 1);
assert_eq!(children(&s, groups[0]), [group, b], "the mask's row, not the clipped art's");
}
#[test]
fn group_rows_keeps_clipping_masks_first_in_groups_and_layers() {
for clipping_layer in [false, true] {
let mut s = session();
let mask = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
let a = rect(&mut s, 10.0, 10.0, 20.0, 20.0);
let b = rect(&mut s, 40.0, 10.0, 20.0, 20.0);
select(&mut s, &[mask, a, b]);
let parent = if clipping_layer {
s.doc().unwrap().doc.layers[0].id
} else {
s.execute("object.group", &json!({})).unwrap();
s.doc().unwrap().selection.objects[0]
};
s.edit("Set clipping", |d, _| {
d.node_mut(parent).unwrap().set_clips(true);
Ok(())
})
.unwrap();
select(&mut s, &[mask, a]);
let n = steps(&s);
let r = s.execute("addon.arrange.groupRows", &json!({})).unwrap();
assert_eq!((r["grouped"].clone(), steps(&s)), (json!(0), n));
assert_eq!(children(&s, parent), [mask, a, b]);
select(&mut s, &[mask, a, b]);
let before = s.doc().unwrap().doc.clone();
let r = s.execute("addon.arrange.groupRows", &json!({})).unwrap();
let groups = ids_of(&r["groups"]);
assert_eq!(r["grouped"], json!(2));
assert_eq!(children(&s, parent), [mask, groups[0]]);
assert_eq!(children(&s, groups[0]), [a, b]);
assert!(s.doc().unwrap().selection.objects.contains(&mask));
s.execute("edit.undo", &json!({})).unwrap();
assert!(*s.doc().unwrap().doc == *before);
}
}
#[test]
fn group_rows_leaves_selected_layers_and_sublayers_in_place() {
for sublayers in [false, true] {
let mut s = session();
let parent = s.doc().unwrap().doc.layers[0].id;
let mut layers = vec![];
for _ in 0..2 {
let command = if sublayers { "layer.newSublayer" } else { "layer.new" };
let params = if sublayers { json!({"parent": parent.0}) } else { json!({"top": true}) };
let layer = NodeId(s.execute(command, &params).unwrap()["id"].as_u64().unwrap());
rect(&mut s, 10.0, 10.0, 20.0, 20.0);
layers.push(layer);
}
s.execute("layer.setCurrent", &json!({"id": parent.0})).unwrap();
let a = rect(&mut s, 10.0, 10.0, 20.0, 20.0);
let b = rect(&mut s, 15.0, 15.0, 20.0, 20.0);
for direction in ["row", "column"] {
select(&mut s, &layers);
let before = s.doc().unwrap().doc.clone();
let n = steps(&s);
let r = s.execute("addon.arrange.groupRows", &json!({"direction": direction})).unwrap();
assert_eq!(r["grouped"], json!(0), "layers must not become ordinary group members");
assert_eq!(steps(&s), n);
assert!(*s.doc().unwrap().doc == *before);
select(&mut s, &[layers[0], layers[1], a, b]);
let r = s.execute("addon.arrange.groupRows", &json!({"direction": direction})).unwrap();
assert_eq!(r["grouped"], json!(2));
let groups = ids_of(&r["groups"]);
assert_eq!(children(&s, groups[0]), [a, b]);
for layer in &layers {
assert_eq!(s.doc().unwrap().doc.parent_of(*layer), sublayers.then_some(parent));
assert!(s.doc().unwrap().selection.objects.contains(layer));
}
s.execute("edit.undo", &json!({})).unwrap();
assert!(*s.doc().unwrap().doc == *before);
}
}
}
#[test]
fn group_rows_refuses_objects_without_a_parent() {
let mut s = session();
let a = rect(&mut s, 10.0, 10.0, 20.0, 20.0);
let b = rect(&mut s, 15.0, 15.0, 20.0, 20.0);
s.edit("Set root objects", |d, _| {
for id in [a, b] {
let node = d.remove(id)?;
d.layers.push(node);
}
Ok(())
})
.unwrap();
select(&mut s, &[a, b]);
refuses(&mut s, "addon.arrange.groupRows", &[json!({"direction": "row"}), json!({"direction": "column"})]);
}
fn refuse_row_parts_and_group_whole(s: &mut Session, group: NodeId, parts: &[Vec<NodeId>]) {
let center = bounds(s, group).center();
let a = rect(s, center.x - 10.0, center.y - 10.0, 20.0, 20.0);
let b = rect(s, center.x - 5.0, center.y - 5.0, 20.0, 20.0);
let members = children(s, group);
for direction in ["row", "column"] {
for selected in parts {
select(s, selected);
let selection = s.doc().unwrap().selection.clone();
refuses(s, "addon.arrange.groupRows", &[json!({"direction": direction})]);
assert_eq!(s.doc().unwrap().selection, selection);
let mut mixed = selected.clone();
mixed.extend([a, b]);
select(s, &mixed);
refuses(s, "addon.arrange.groupRows", &[json!({"direction": direction})]);
assert_eq!(children(s, group), members);
}
select(s, &[group, a, b]);
let before = s.doc().unwrap().doc.clone();
let n = steps(s);
let r = s.execute("addon.arrange.groupRows", &json!({"direction": direction})).unwrap();
assert_eq!(r["grouped"], json!(3));
let groups = ids_of(&r["groups"]);
assert_eq!(children(s, groups[0]), [group, a, b]);
assert_eq!(children(s, group), members);
assert_eq!(steps(s), n + 1);
s.execute("edit.undo", &json!({})).unwrap();
assert!(*s.doc().unwrap().doc == *before);
}
}
#[test]
fn group_rows_refuses_objects_on_path_children_but_groups_the_whole_group() {
let mut s = session();
let path = rect(&mut s, 20.0, 20.0, 100.0, 100.0);
let member = rect(&mut s, 30.0, 30.0, 20.0, 20.0);
let group = NodeId(s.execute("object.objectsOnPath.attach", &json!({"path": path.0, "ids": [member.0]})).unwrap()["id"].as_u64().unwrap());
refuse_row_parts_and_group_whole(&mut s, group, &[vec![path, member]]);
assert!(s.doc().unwrap().doc.node(group).unwrap().extras().objects_on_path.is_some());
}
#[test]
fn group_rows_refuses_live_paint_faces_and_edges_but_groups_the_whole_group() {
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
let b = rect(&mut s, 50.0, 0.0, 100.0, 100.0);
select(&mut s, &[a, b]);
let group = NodeId(s.execute("livePaint.make", &json!({})).unwrap()["id"].as_u64().unwrap());
let node = s.doc().unwrap().doc.node(group).unwrap();
let faces: Vec<_> = vectorcraft_tools::builder::faces(node).iter().map(|n| n.id).collect();
let edges: Vec<_> = vectorcraft_tools::builder::edges(node).iter().map(|n| n.id).collect();
assert!(faces.len() >= 2);
assert!(edges.len() >= 2);
refuse_row_parts_and_group_whole(&mut s, group, &[faces.clone(), edges.clone()]);
let node = s.doc().unwrap().doc.node(group).unwrap();
assert_eq!(vectorcraft_tools::builder::faces(node).iter().map(|n| n.id).collect::<Vec<_>>(), faces);
assert_eq!(vectorcraft_tools::builder::edges(node).iter().map(|n| n.id).collect::<Vec<_>>(), edges);
}
#[test]
fn group_rows_refuses_live_graph_descendants_but_groups_the_whole_graph() {
let mut s = session();
let params = json!({"type": "column", "x": 20, "y": 20, "width": 200, "height": 200, "csv": ",Series\nA,3\nB,5"});
let graph = NodeId(s.execute("graph.create", &params).unwrap()["id"].as_u64().unwrap());
let node = s.doc().unwrap().doc.node(graph).unwrap();
let series = node.children().unwrap().iter().find(|n| n.extras().series_index == Some(0)).unwrap();
let marks: Vec<_> = series.children().unwrap().iter().take(2).map(|n| n.id).collect();
assert_eq!(marks.len(), 2);
let direct = children(&s, graph);
refuse_row_parts_and_group_whole(&mut s, graph, &[marks, direct]);
assert!(s.doc().unwrap().doc.node(graph).unwrap().extras().graph.is_some());
}
#[test]
fn group_rows_refuses_explicitly_selected_live_blend_keys() {
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0);
let b = rect(&mut s, 30.0, 0.0, 20.0, 20.0);
select(&mut s, &[a, b]);
s.execute("object.blend.make", &json!({})).unwrap();
let blend = s.doc().unwrap().selection.objects[0];
let c = rect(&mut s, 60.0, 0.0, 20.0, 20.0);
let d = rect(&mut s, 90.0, 0.0, 20.0, 20.0);
select(&mut s, &[a, b]);
refuses(&mut s, "addon.arrange.groupRows", &[json!({})]);
select(&mut s, &[a, b, c, d]);
refuses(&mut s, "addon.arrange.groupRows", &[json!({})]);
assert_eq!(children(&s, blend), [a, b]);
}
#[test]
fn group_rows_refuses_explicitly_selected_shaper_children() {
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
let b = rect(&mut s, 50.0, 0.0, 100.0, 100.0);
select(&mut s, &[a, b]);
let shaper = NodeId(s.execute("shaper.scribble", &json!({"points": [[25, 25], [125, 25]]})).unwrap()["id"].as_u64().unwrap());
let members = children(&s, shaper);
assert!(members.len() >= 2);
let sources = members[0];
let face = s
.doc()
.unwrap()
.doc
.node(shaper)
.unwrap()
.children()
.unwrap()
.iter()
.find(|n| n.name.as_deref().is_some_and(|name| name.starts_with(vectorcraft_doc::shaper::FILL_PREFIX)))
.unwrap()
.id;
let c = rect(&mut s, 200.0, 0.0, 20.0, 20.0);
let d = rect(&mut s, 230.0, 0.0, 20.0, 20.0);
for direction in ["row", "column"] {
select(&mut s, &[sources, face]);
refuses(&mut s, "addon.arrange.groupRows", &[json!({"direction": direction})]);
select(&mut s, &[sources, face, c, d]);
refuses(&mut s, "addon.arrange.groupRows", &[json!({"direction": direction})]);
assert_eq!(children(&s, shaper), members);
}
}
#[test]
fn group_rows_refuses_explicitly_selected_live_compound_shape_operands() {
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 30.0, 30.0);
let b = rect(&mut s, 10.0, 0.0, 30.0, 30.0);
select(&mut s, &[a, b]);
s.execute("object.compoundShape.make", &json!({"mode": "subtract"})).unwrap();
let shape = s.doc().unwrap().selection.objects[0];
let c = rect(&mut s, 200.0, 0.0, 20.0, 20.0);
let d = rect(&mut s, 230.0, 0.0, 20.0, 20.0);
for direction in ["row", "column"] {
select(&mut s, &[a, b]);
refuses(&mut s, "addon.arrange.groupRows", &[json!({"direction": direction})]);
select(&mut s, &[a, b, c, d]);
refuses(&mut s, "addon.arrange.groupRows", &[json!({"direction": direction})]);
assert_eq!(children(&s, shape), [a, b]);
}
}
#[test]
fn group_rows_skips_explicitly_selected_locked_and_hidden_objects() {
for command in ["object.lock", "object.hide"] {
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0);
let b = rect(&mut s, 30.0, 0.0, 20.0, 20.0);
let c = rect(&mut s, 60.0, 0.0, 20.0, 20.0);
select(&mut s, &[b]);
s.execute(command, &json!({})).unwrap();
select(&mut s, &[a, b, c]);
assert!(s.doc().unwrap().selection.objects.contains(&b));
let r = s.execute("addon.arrange.groupRows", &json!({})).unwrap();
let groups = ids_of(&r["groups"]);
assert_eq!(r["grouped"], json!(2));
assert_eq!(children(&s, groups[0]), [a, c]);
assert_eq!(s.doc().unwrap().doc.parent_of(b), Some(s.doc().unwrap().doc.layers[0].id));
}
}
#[test]
fn group_rows_leaves_objects_outside_all_artboards_ungrouped() {
for direction in ["row", "column"] {
let mut s = session();
let a = rect(&mut s, 500.0, 500.0, 20.0, 20.0);
let b = rect(&mut s, 505.0, 505.0, 20.0, 20.0);
select(&mut s, &[a, b]);
let (before, n) = (s.doc().unwrap().doc.clone(), steps(&s));
let r = s.execute("addon.arrange.groupRows", &json!({"direction": direction})).unwrap();
assert_eq!((r["grouped"].clone(), steps(&s)), (json!(0), n));
assert!(*s.doc().unwrap().doc == *before);
let c = rect(&mut s, 0.0, 0.0, 20.0, 20.0);
let d = rect(&mut s, 5.0, 5.0, 20.0, 20.0);
select(&mut s, &[a, b, c, d]);
let r = s.execute("addon.arrange.groupRows", &json!({"direction": direction})).unwrap();
let groups = ids_of(&r["groups"]);
assert_eq!(r["grouped"], json!(2));
assert_eq!(children(&s, groups[0]), [c, d]);
assert_eq!(layer_children(&s), [a, b, groups[0]]);
let sel = &s.doc().unwrap().selection.objects;
assert!(sel.contains(&a) && sel.contains(&b));
}
}
#[test]
fn group_rows_documents_and_excludes_raster_effects_from_bounds() {
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0);
select(&mut s, &[a]);
s.execute("effect.apply", &json!({"effect": "stylize.dropShadow", "params": {"x": 0, "y": 5, "blur": 0}})).unwrap();
let b = rect(&mut s, 0.0, 21.0, 20.0, 20.0);
select(&mut s, &[a, b]);
let n = steps(&s);
let r = s.execute("addon.arrange.groupRows", &json!({})).unwrap();
assert_eq!((r["grouped"].clone(), steps(&s)), (json!(0), n));
assert_eq!(layer_children(&s), [a, b]);
let spec = super::specs().into_iter().find(|c| c.id == "addon.arrange.groupRows").unwrap();
assert!(spec.params.contains("excludes raster effects"));
}
#[test]
fn group_rows_is_off_with_one_object_skips_locked_ones_and_refuses_bad_params() {
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0);
select(&mut s, &[a]);
assert!(!enabled(&s, "addon.arrange.groupRows"));
let b = rect(&mut s, 30.0, 0.0, 20.0, 20.0);
let c = rect(&mut s, 60.0, 0.0, 20.0, 20.0);
select(&mut s, &[a, b, c]);
assert!(enabled(&s, "addon.arrange.groupRows"));
refuses(
&mut s,
"addon.arrange.groupRows",
&[json!({"direction": "diagonal"}), json!({"direction": 3}), json!({"direction": true}), json!({"direction": null})],
);
select(&mut s, &[b]);
s.execute("object.lock", &json!({})).unwrap();
s.execute("select.all", &json!({})).unwrap();
let r = s.execute("addon.arrange.groupRows", &json!({})).unwrap();
let groups = ids_of(&r["groups"]);
assert_eq!(groups.len(), 1);
assert_eq!(children(&s, groups[0]), [a, c], "the locked object stays out");
assert_eq!(s.doc().unwrap().doc.parent_of(b), Some(s.doc().unwrap().doc.layers[0].id));
}
#[test]
fn group_rows_refuses_non_object_params_without_an_edit() {
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0);
let b = rect(&mut s, 30.0, 0.0, 20.0, 20.0);
select(&mut s, &[a, b]);
let selection = s.doc().unwrap().selection.objects.clone();
refuses(&mut s, "addon.arrange.groupRows", &[json!([]), json!(["row"]), json!("row"), json!(true), json!(3)]);
assert_eq!(s.doc().unwrap().selection.objects, selection);
}
#[test]
fn group_rows_reads_the_symbol_index_once_for_all_members() {
use std::sync::Arc;
use vectorcraft_doc::{Appearance, Document, Node, NodeKind, Symbol};
use vectorcraft_geom::Affine;
let mut d = Document::new(400.0, 300.0);
for i in 0..200 {
let art = Node::path(d.alloc_id(), vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art());
d.symbols.push(Symbol { dynamic: false, name: format!("Mark {i}"), art: Arc::new(art) });
}
let layer = d.layers[0].id;
let ids: Vec<_> = (0..8)
.map(|i| {
let xf = Affine::translate((0.0, f64::from(i) * 20.0));
let n = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: format!("Mark {i}"), xf });
d.insert(Some(layer), usize::MAX, n).unwrap()
})
.collect();
let symbol_count = d.symbols.len();
let mut s = Session::new();
s.add_document(d, None);
select(&mut s, &ids);
let n = steps(&s);
let before = vectorcraft_doc::symbols_read();
let r = s.execute("addon.arrange.groupRows", &json!({})).unwrap();
let read = vectorcraft_doc::symbols_read() - before;
assert!(read <= symbol_count, "{read} symbols read, {symbol_count} in the document");
assert_eq!((r["grouped"].clone(), steps(&s)), (json!(0), n));
assert_eq!(layer_children(&s), ids);
}
#[test]
fn group_rows_sorts_many_objects_into_rows() {
// 20000 objects in pairs up the page, the front one of each pair starting higher: each pair overlaps,
// neighboring pairs only touch.
let items: Vec<(u8, (f64, f64))> = (0..20_000)
.map(|i| {
let top = (10_000 - i / 2) as f64 * 10.0;
(0, (if i % 2 == 0 { top + 1.0 } else { top }, top + 10.0))
})
.collect();
let rows = super::rows_of(&items);
assert_eq!(rows.len(), 10_000);
assert!(rows.iter().all(|r| r.len() == 2 && r[1] == r[0] + 1), "pairs, in the order given");
assert_eq!(rows.first(), Some(&vec![19_998, 19_999]), "the top row first");
}
#[test]
fn group_rows_keeps_a_flat_object_on_a_row_edge_apart_in_either_order() {
// An extent with no height at the top edge of another only touches it, whichever is in front.
let flat_behind: Vec<(u8, (f64, f64))> = vec![(0, (0.0, 0.0)), (0, (0.0, 10.0))];
let flat_in_front: Vec<(u8, (f64, f64))> = vec![(0, (0.0, 10.0)), (0, (0.0, 0.0))];
assert!(super::rows_of(&flat_behind).is_empty());
assert!(super::rows_of(&flat_in_front).is_empty(), "{:?}", super::rows_of(&flat_in_front));
// Inside the row, it joins.
assert_eq!(super::rows_of(&[(0u8, (0.0, 10.0)), (0, (5.0, 5.0))]), vec![vec![0, 1]]);
// A start of -0.0 is the same edge as 0.0, so the flat extent there still only touches.
let negative_zero: Vec<(u8, (f64, f64))> = vec![(0, (0.0, 0.0)), (0, (-0.0, 10.0))];
assert!(super::rows_of(&negative_zero).is_empty(), "{:?}", super::rows_of(&negative_zero));
}
fn opacity(s: &Session, id: NodeId) -> f32 {
s.doc().unwrap().doc.node(id).unwrap().opacity
}
+12 -1
View File
@@ -5,12 +5,14 @@
//! Print Ink Fixes ([`print_fixes`]) prepares a CMYK document's inks for print, Find Nearest
//! Swatch ([`nearest`]) matches colours to a swatch library's, Create Swatch Legend
//! ([`legend`]) draws labelled chips of the document's swatches, and Apply Fill to Stroke and Apply
//! Stroke to Fill ([`copy_paint`]) copy each object's own paint across. Its panel and its submenu,
//! Stroke to Fill ([`copy_paint`]) copy each object's own paint across, and Randomize Fill Colors
//! ([`random_fill`]) gives each filled path its own color at random. Its panel and its submenu,
//! Object › Plug-ins › Color Effects, are the UI's.
pub mod legend;
mod nearest;
mod print_fixes;
mod random_fill;
#[cfg(test)]
mod tests;
@@ -92,6 +94,15 @@ pub fn specs() -> Vec<CommandSpec> {
has_doc,
|s, p| copy_paint(s, p, false)
),
cmd!(
"addon.color.randomFill",
"Randomize Fill Colors",
["Object", "Plug-ins", "Color Effects"],
None,
"{scheme?: \"color\" (any color: red, green and blue each at random, in the document's color mode) | \"tint\" (a tint of `swatch`, linked to it) | \"gray\" (a gray) (\"color\"), swatch?: a global or spot color swatch's name (tint only, and needed there; a tint swatch gives tints of its base, which must still support tints), min?: % 0..100 (0), max?: % 0..100 (100; not less than min) (tint and gray only: the tint, or the gray's black, ranges from min to max), seed?: whole number (0; the same seed, objects and settings give the same colors; colors are drawn in the order of ids, a repeated id counting once and an id inside a listed group taking its color with that group's objects, so another order can give each object a different color), ids?: [id…] (default: the selection)} give each selected filled path, compound path and live compound shape, and each one inside the selected groups, its own top fill color, picked at random and evenly within the scheme, as one undo step (none when no fill changes). Compound paths and live compound shapes take one color and keep their members' fills. An id naming a nested member targets the outermost compound. Paths, compound paths and live compound shapes with no fill, clipping paths, hidden and locked objects (and objects in hidden or locked groups and layers, or on a locked artboard, also when given in ids, except new art made there while it is still selected), generated graph design art, paths a user groups inside a graph series, type, images, symbol instances, blends and envelopes keep their fills; a gradient or pattern fill becomes the color. On paths directly in a graph series whose fill changes, the graph stores the fill of the frontmost of them for its next redraw, which gives every mark of the series that one color (docs/mcp.md) → {count: objects whose fill changed}",
has_selection,
random_fill::run
),
]
.into_iter()
.chain(legend::specs())
@@ -0,0 +1,255 @@
//! Randomize Fill Colors (`addon.color.randomFill`, Object › Plug-ins › Color Effects › Randomize
//! Fill Colors…): each selected filled path, compound path and live compound shape, and each one inside the selected
//! groups, gets a fill color of its own, picked at random from a seed: any color, a tint of one
//! global or spot swatch, or a gray, as one undo step.
#[cfg(test)]
mod tests;
use std::collections::HashSet;
use serde_json::{Value, json};
use vectorcraft_color::recolor::Rng;
use vectorcraft_color::{Color, Paint};
use vectorcraft_doc::{Document, Node, NodeId, NodeKind};
use super::super::super::colorcmds::{edit_if_changed, keeping_series_paint};
#[cfg(test)]
use super::super::super::graph::is_design_art;
use super::super::super::graph::{is_series_group, paint_targets};
use super::super::super::menucmds::whole_or;
use super::super::super::paint::swatch_solid;
use super::super::super::{bad, checked_ids_or_selection, number_or, text_param};
use crate::{Result, Session};
const C: &str = "addon.color.randomFill";
/// The schemes the colors are picked from (`scheme`).
pub const SCHEMES: [&str; 3] = ["color", "tint", "gray"];
/// How each color is picked.
enum Scheme {
/// Any color: red, green and blue each at random, in the document's color mode.
Color,
/// A tint of the swatch, from the least to the most (0..1).
Tint(String, f32, f32),
/// A gray, from the least black to the most (0..1).
Gray(f32, f32),
}
/// The percentage `p` gives for `key` (`default` when left out).
fn percent(p: &Value, key: &str, default: f64) -> Result<f64> {
let v = number_or(p, key, default, C)?;
if (0.0..=100.0).contains(&v) { Ok(v) } else { Err(bad(C, format!("`{key}` must be from 0 to 100"))) }
}
/// The scheme `p` asks for, checked against the document's swatches.
fn scheme(s: &Session, p: &Value) -> Result<Scheme> {
let name = text_param(p, "scheme", C)?.unwrap_or("color");
if !SCHEMES.contains(&name) {
return Err(bad(C, "`scheme` must be color, tint or gray"));
}
let given = |key: &str| p.get(key).is_some_and(|v| !v.is_null());
if name == "color" && (given("min") || given("max")) {
return Err(bad(C, "`min` and `max` go with scheme tint or gray"));
}
if name != "tint" && given("swatch") {
return Err(bad(C, "`swatch` goes with scheme tint"));
}
if name == "color" {
return Ok(Scheme::Color);
}
let (min, max) = (percent(p, "min", 0.0)?, percent(p, "max", 100.0)?);
if min > max {
return Err(bad(C, "`min` is greater than `max`"));
}
let (min, max) = ((min / 100.0) as f32, (max / 100.0) as f32);
if name == "gray" {
return Ok(Scheme::Gray(min, max));
}
let swatch = text_param(p, "swatch", C)?.ok_or_else(|| bad(C, "scheme tint needs a `swatch`: a global or spot color swatch"))?;
let d = &s.doc()?.doc;
swatch_solid(d, swatch, Some(1.0)).map_err(|e| bad(C, e))?;
if let Some((base, _)) = d.swatch_link(swatch)
&& d.tint_paint(&base, 1.0).is_none()
{
return Err(bad(C, format!("`{swatch}` needs a global or spot base swatch `{base}`")));
}
Ok(Scheme::Tint(swatch.to_string(), min, max))
}
/// Whether the object `id` is left as it is: it, or a layer or group holding it, is hidden or
/// locked, or it is the clipping path of the group or layer holding it.
fn left_alone(d: &Document, id: NodeId) -> bool {
let Some(line) = d.ancestry(id) else { return true };
let nodes: Vec<&Node> = line.iter().filter_map(|id| d.node(*id)).collect();
if nodes.len() != line.len() || nodes.iter().any(|n| !n.visible || n.locked) {
return true;
}
matches!(nodes.as_slice(), [.., parent, n] if parent.clips() && parent.children().and_then(|c| c.first()).is_some_and(|c| c.id == n.id))
}
/// Add to `out` `n` when it is a filled path, compound path or live compound shape that is shown and unlocked, or the
/// ones inside it when it is a group or a layer. A clipping path (the first object of a clipping
/// group or clipped layer, a compound path included), a guide, type, images, symbol instances,
/// blends and envelopes are left as they are.
fn filled(n: &Node, out: &mut Vec<NodeId>) {
if !n.visible || n.locked {
return;
}
if n.is_compound_shape() {
if !n.appearance.fill_paint().is_none() {
out.push(n.id);
}
return;
}
match &n.kind {
NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => {
for c in children.iter().skip(usize::from(n.clips())) {
filled(c, out);
}
}
NodeKind::Path { clipping: false, guide: false, .. } | NodeKind::Compound { .. } if !n.appearance.fill_paint().is_none() => out.push(n.id),
_ => {}
}
}
/// `ids` with each graph series group replaced by the paths, compound paths and live compound shapes directly inside
/// it. A compound path or live compound shape directly in a series group is kept, and the other ids go through
/// [`paint_targets`], as for `paint.setFill`.
fn series_roots(doc: &Document, ids: &[NodeId]) -> Vec<NodeId> {
let is_series = |id: NodeId| doc.node(id).is_some_and(|n| is_series_group(doc, n));
let compound = |n: &Node| matches!(n.kind, NodeKind::Compound { .. }) || n.is_compound_shape();
let ordinary: std::collections::HashSet<NodeId> = paint_targets(doc, ids).into_iter().collect();
let mut out = vec![];
for id in ids {
let Some(n) = doc.node(*id) else { continue };
if is_series(*id) {
out.extend(n.children().into_iter().flatten().filter(|m| matches!(m.kind, NodeKind::Path { .. }) || compound(m)).map(|m| m.id));
} else if (compound(n) && doc.parent_of(*id).is_some_and(is_series)) || ordinary.contains(id) {
out.push(*id);
}
}
let mut seen = std::collections::HashSet::new();
out.retain(|id| seen.insert(*id));
out
}
/// The graph series groups among the ancestors of `targets`, each checked once.
fn cached_series_groups(doc: &Document, targets: &[NodeId]) -> HashSet<NodeId> {
let mut groups: HashSet<NodeId> = targets.iter().filter_map(|id| doc.ancestry(*id)).flatten().collect();
groups.retain(|id| doc.node(*id).is_some_and(|n| is_series_group(doc, n)));
groups
}
/// [`is_design_art`] with the series groups looked up in `series_groups`.
fn cached_is_design_art(doc: &Document, id: NodeId, series_groups: &HashSet<NodeId>) -> bool {
let Some(chain) = doc.ancestry(id) else { return false };
let Some(at) = chain.iter().position(|a| series_groups.contains(a)) else { return false };
match chain.len() - at {
1 => false,
2 => doc.node(id).is_some_and(|n| !matches!(n.kind, NodeKind::Path { .. })),
_ => true,
}
}
pub(super) fn run(s: &mut Session, p: &Value) -> Result<Value> {
let scheme = scheme(s, p)?;
let mut rng = Rng::new(whole_or(p, "seed", 0, C)?);
let ids = checked_ids_or_selection(s, p, C)?;
if ids.is_empty() {
return Ok(json!({ "count": 0 }));
}
let model = s.doc()?.doc.color_mode.model();
// A run that gives every object the fill it has records no undo step.
let count = edit_if_changed(s, "Randomize Fill Colors", |before, d| {
// Art on a locked artboard is left as it is, as for the other commands that take `ids`.
let locks = before.locked_artboards();
// A nested member stands for the outermost compound path or live compound shape after each ancestor is checked.
let mut resolved = vec![];
for id in &ids {
let Some(chain) = before.ancestry(*id) else { continue };
let mut target = None;
let mut blocked = false;
let mut parent: Option<&Node> = None;
let mut layer_object_checked = false;
for ancestor in &chain {
let Some(n) = before.node(*ancestor) else {
blocked = true;
break;
};
if !n.visible || n.locked || parent.is_some_and(|p| p.clips() && p.children().and_then(|c| c.first()).is_some_and(|c| c.id == n.id)) {
blocked = true;
break;
}
if !layer_object_checked && (n.is_ruler_guide() || !n.is_layer()) {
layer_object_checked = true;
if !n.is_ruler_guide() && locks.holds(n) {
blocked = true;
break;
}
}
if matches!(n.kind, NodeKind::Compound { .. }) || n.is_compound_shape() {
target.get_or_insert(*ancestor);
}
parent = Some(n);
}
if !blocked {
resolved.push(target.unwrap_or(*id));
}
}
// A graph's series group stands for its marks, as for `paint.setFill`.
let roots = series_roots(before, &resolved);
let mut targets = vec![];
for id in &roots {
let id = *id;
if left_alone(before, id) || locks.holds_id(id) {
continue;
}
let Some(n) = before.node(id) else { continue };
filled(n, &mut targets);
}
let series_groups = cached_series_groups(before, &targets);
let mut seen = std::collections::HashSet::new();
// A compound directly in a series group is one of the series' marks unless the graph drew it from a design;
// the rest of the series' art below its top level is design art.
let series_compound = |id: NodeId| {
let Some(n) = before.node(id) else { return false };
if !(matches!(n.kind, NodeKind::Compound { .. }) || n.is_compound_shape()) || n.extras().graph_design_art {
return false;
}
let Some(group) = before.parent_of(id).filter(|p| series_groups.contains(p)).and_then(|p| before.node(p)) else { return false };
let Some(index) = group.extras().series_index.and_then(|i| usize::try_from(i).ok()) else { return false };
let graph = before.parent_of(group.id).and_then(|p| before.node(p)).and_then(|p| p.extras().graph.as_deref());
graph.is_some_and(|spec| {
let column = spec.series_columns.get(index).and_then(Option::as_ref).map(|c| c.design.as_str());
let marker = spec.series_markers.get(index).and_then(Option::as_deref);
![column, marker].into_iter().flatten().any(|name| {
before
.graph_designs
.iter()
.any(|design| design.name == name && (matches!(design.art.kind, NodeKind::Compound { .. }) || design.art.is_compound_shape()))
})
})
};
targets.retain(|id| seen.insert(*id) && !locks.holds_id(*id) && (series_compound(*id) || !cached_is_design_art(before, *id, &series_groups)));
let count = keeping_series_paint(d, &roots, |d| {
let mut count = 0;
for id in &targets {
let paint = match &scheme {
Scheme::Color => Paint::solid(Color::rgb(rng.range(0.0, 1.0), rng.range(0.0, 1.0), rng.range(0.0, 1.0)).in_model(model)),
Scheme::Tint(swatch, lo, hi) => swatch_solid(d, swatch, Some(rng.range(*lo, *hi))).map_err(|e| bad(C, e))?,
Scheme::Gray(lo, hi) => Paint::solid(Color::gray(rng.range(*lo, *hi))),
};
if let Some(n) = d.node_mut(*id)
&& n.appearance.fill_paint() != paint
{
n.appearance.set_fill(paint);
count += 1;
}
}
Ok(count)
})?;
Ok((count, count > 0))
})?;
Ok(json!({ "count": count }))
}
@@ -0,0 +1,705 @@
//! Randomize Fill Colors: the colors each scheme gives, which objects take them, one undo step, and
//! bad params refused without a change.
use serde_json::{Value, json};
use vectorcraft_color::{Color, Paint};
use vectorcraft_doc::{NodeId, NodeKind};
use crate::Session;
const C: &str = "addon.color.randomFill";
fn session() -> Session {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
s
}
fn rect(s: &mut Session, x: f64) -> NodeId {
NodeId(s.execute("shape.rectangle", &json!({"x": x, "y": 0, "width": 5, "height": 5})).unwrap()["id"].as_u64().unwrap())
}
fn rects(s: &mut Session, n: usize) -> Vec<NodeId> {
(0..n).map(|i| rect(s, i as f64 * 10.0)).collect()
}
fn select(s: &mut Session, ids: &[NodeId]) {
s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})).unwrap();
}
fn fill(s: &Session, id: NodeId) -> Paint {
s.doc().unwrap().doc.node(id).unwrap().appearance.fill_paint()
}
fn fills(s: &Session, ids: &[NodeId]) -> Vec<Paint> {
ids.iter().map(|id| fill(s, *id)).collect()
}
fn steps(s: &Session) -> usize {
s.doc().unwrap().history.undo.len()
}
fn enabled(s: &Session, cmd: &str) -> bool {
s.commands().into_iter().find(|c| c.id == cmd).unwrap().enabled
}
#[test]
fn each_object_gets_its_own_color_from_the_seed() {
let mut s = session();
let ids = rects(&mut s, 12);
select(&mut s, &ids);
let before = fills(&s, &ids);
let n = steps(&s);
let r = s.execute(C, &json!({"seed": 7})).unwrap();
assert_eq!(r["count"], json!(12));
assert_eq!(steps(&s), n + 1, "one undo step");
let first = fills(&s, &ids);
assert!(first.iter().all(|p| matches!(p, Paint::Solid { color: Color::Rgb { .. }, swatch: None, .. })), "{first:?}");
assert!(first.windows(2).all(|w| w[0] != w[1]), "each its own: {first:?}");
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(fills(&s, &ids), before, "undone");
// The same seed repeats them; another seed doesn't.
s.execute(C, &json!({"seed": 7})).unwrap();
assert_eq!(fills(&s, &ids), first);
s.execute(C, &json!({"seed": 8})).unwrap();
assert_ne!(fills(&s, &ids), first);
}
#[test]
fn repeated_ids_take_one_color_from_the_seed() {
let mut s = session();
let a = rect(&mut s, 0.0);
assert_eq!(s.execute(C, &json!({"ids": [a.0], "seed": 7})).unwrap()["count"], json!(1));
let once = fill(&s, a);
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(s.execute(C, &json!({"ids": [a.0, a.0], "seed": 7})).unwrap()["count"], json!(1));
assert_eq!(fill(&s, a), once);
}
#[test]
fn a_cmyk_document_gets_cmyk_colors() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300, "colorMode": "cmyk"})).unwrap();
let ids = rects(&mut s, 3);
select(&mut s, &ids);
s.execute(C, &json!({"scheme": "color"})).unwrap();
assert!(fills(&s, &ids).iter().all(|p| matches!(p, Paint::Solid { color: Color::Cmyk { .. }, .. })), "{:?}", fills(&s, &ids));
}
#[test]
fn grays_and_tints_stay_within_the_range() {
let mut s = session();
let ids = rects(&mut s, 20);
select(&mut s, &ids);
s.execute(C, &json!({"scheme": "gray", "min": 20, "max": 40, "seed": 3})).unwrap();
let grays: Vec<f32> = fills(&s, &ids)
.into_iter()
.map(|p| match p {
Paint::Solid { color: Color::Gray { k }, swatch: None, .. } => k,
other => panic!("not a gray: {other:?}"),
})
.collect();
assert!(grays.iter().all(|k| (0.2..=0.4).contains(k)), "{grays:?}");
assert!(grays.windows(2).any(|w| w[0] != w[1]), "{grays:?}");
s.execute("swatch.new", &json!({"name": "Ink", "color": "#e01020", "spot": true})).unwrap();
s.execute(C, &json!({"scheme": "tint", "swatch": "Ink", "min": 10, "max": 50, "seed": 3})).unwrap();
for p in fills(&s, &ids) {
let Paint::Solid { swatch: Some(name), tint, .. } = p else { panic!("not linked: {p:?}") };
assert_eq!(name, "Ink");
assert!((0.1..=0.5).contains(&tint), "{tint}");
}
// min = max gives every object that gray.
s.execute(C, &json!({"scheme": "gray", "min": 45, "max": 45})).unwrap();
assert!(fills(&s, &ids).iter().all(|p| *p == Paint::solid(Color::gray(0.45))));
}
#[test]
fn groups_are_entered_and_unfilled_hidden_and_locked_objects_left_alone() {
let mut s = session();
let [a, b, c, hidden, locked] = [0.0, 10.0, 20.0, 30.0, 40.0].map(|x| rect(&mut s, x));
select(&mut s, &[a, b, c, hidden, locked]);
let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
s.execute("paint.setFill", &json!({"ids": [c.0], "none": true})).unwrap();
s.execute("object.hide", &json!({"ids": [hidden.0]})).unwrap();
s.execute("object.lock", &json!({"ids": [locked.0]})).unwrap();
select(&mut s, &[g]);
let (before_hidden, before_locked) = (fill(&s, hidden), fill(&s, locked));
assert!(!before_hidden.is_none() && !before_locked.is_none());
let r = s.execute(C, &json!({"scheme": "gray", "min": 50, "max": 50})).unwrap();
assert_eq!(r["count"], json!(2));
let gray = Paint::solid(Color::gray(0.5));
assert_eq!((fill(&s, a), fill(&s, b), fill(&s, c)), (gray.clone(), gray.clone(), Paint::None), "the unfilled one keeps None");
assert_eq!(fill(&s, g), Paint::None, "the group gets no fill of its own");
assert_eq!((fill(&s, hidden), fill(&s, locked)), (before_hidden, before_locked));
// `ids` stand in for the selection; with nothing selected the menu item is off.
s.execute("select.none", &json!({})).unwrap();
assert!(!enabled(&s, C));
let d = rect(&mut s, 50.0);
s.execute("paint.setFill", &json!({"ids": [d.0], "color": "#336699"})).unwrap();
s.execute("select.none", &json!({})).unwrap();
s.execute(C, &json!({"ids": [d.0], "scheme": "gray", "min": 10, "max": 10})).unwrap();
assert_eq!(fill(&s, d), Paint::solid(Color::gray(0.1)));
assert_eq!(fill(&s, a), gray, "not among ids");
// An object given by id inside a hidden or locked group keeps its fill.
for hide in [true, false] {
let e = rect(&mut s, 60.0);
s.execute("paint.setFill", &json!({"ids": [e.0], "color": "#336699"})).unwrap();
select(&mut s, &[e]);
let outer = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
s.execute(if hide { "object.hide" } else { "object.lock" }, &json!({"ids": [outer.0]})).unwrap();
let kept = fill(&s, e);
assert_eq!(s.execute(C, &json!({"ids": [e.0], "scheme": "gray"})).unwrap()["count"], json!(0), "hidden group: {hide}");
assert_eq!(fill(&s, e), kept);
}
}
#[test]
fn a_compound_path_takes_one_color_and_a_clipping_path_none() {
let mut s = session();
let [a, b] = [0.0, 2.0].map(|x| rect(&mut s, x));
select(&mut s, &[a, b]);
let compound = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap());
// The topmost becomes the clipping path.
let [art, mask] = [100.0, 102.0].map(|x| rect(&mut s, x));
select(&mut s, &[art, mask]);
let clip = NodeId(s.execute("object.clippingMask.make", &json!({})).unwrap()["id"].as_u64().unwrap());
let is_clipping = |s: &Session, id: NodeId| matches!(s.doc().unwrap().doc.node(id).unwrap().kind, NodeKind::Path { clipping: true, .. });
assert!(is_clipping(&s, mask) && !is_clipping(&s, art));
// A clipping path given a fill still keeps it.
s.execute("paint.setFill", &json!({"ids": [mask.0], "color": "#00ff00"})).unwrap();
let mask_fill = fill(&s, mask);
assert!(!mask_fill.is_none());
select(&mut s, &[compound, clip]);
let r = s.execute(C, &json!({"scheme": "gray", "min": 30, "max": 30})).unwrap();
assert_eq!(r["count"], json!(2), "the compound path and the clipped art");
assert_eq!(fill(&s, compound), Paint::solid(Color::gray(0.3)));
assert_eq!(fill(&s, art), Paint::solid(Color::gray(0.3)));
assert_eq!(fill(&s, mask), mask_fill, "the clipping path keeps its fill");
// Given by id, the clipping path keeps it too.
assert_eq!(s.execute(C, &json!({"ids": [mask.0], "scheme": "gray"})).unwrap()["count"], json!(0));
assert_eq!(fill(&s, mask), mask_fill);
}
#[test]
fn a_compound_member_given_by_id_colors_the_compound() {
let mut s = session();
let [a, b] = [0.0, 2.0].map(|x| rect(&mut s, x));
select(&mut s, &[a, b]);
let compound = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap());
let before = fill(&s, compound);
let members = fills(&s, &[a, b]);
assert_eq!(s.execute(C, &json!({"ids": [a.0], "seed": 7})).unwrap()["count"], json!(1));
assert_ne!(fill(&s, compound), before);
assert_eq!(fills(&s, &[a, b]), members);
}
#[test]
fn a_compound_clipping_path_keeps_its_fill() {
let mut s = session();
let art = rect(&mut s, 0.0);
let [a, b] = [0.0, 2.0].map(|x| rect(&mut s, x));
select(&mut s, &[a, b]);
let compound = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap());
select(&mut s, &[art, compound]);
let clip = NodeId(s.execute("object.clippingMask.make", &json!({})).unwrap()["id"].as_u64().unwrap());
assert_eq!(s.doc().unwrap().doc.node(clip).unwrap().children().unwrap()[0].id, compound, "the compound path clips");
s.execute("paint.setFill", &json!({"ids": [compound.0], "color": "#00ff00"})).unwrap();
let mask_fill = fill(&s, compound);
assert!(!mask_fill.is_none());
select(&mut s, &[clip]);
assert_eq!(s.execute(C, &json!({"scheme": "gray", "min": 30, "max": 30})).unwrap()["count"], json!(1), "the clipped art only");
assert_eq!(fill(&s, art), Paint::solid(Color::gray(0.3)));
assert_eq!(fill(&s, compound), mask_fill);
}
#[test]
fn a_live_compound_shape_takes_one_color_and_keeps_its_members_fills() {
for target in ["shape", "group", "member"] {
let mut s = session();
let [a, b] = [0.0, 2.0].map(|x| rect(&mut s, x));
select(&mut s, &[a, b]);
let shape = NodeId(s.execute("object.compoundShape.make", &json!({})).unwrap()["id"].as_u64().unwrap());
assert!(s.doc().unwrap().doc.node(shape).unwrap().is_compound_shape());
let id = match target {
"group" => NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()),
"member" => a,
_ => shape,
};
let before = fill(&s, shape);
let members = fills(&s, &[a, b]);
let n = steps(&s);
assert_eq!(s.execute(C, &json!({"ids": [id.0], "scheme": "gray", "min": 30, "max": 30})).unwrap()["count"], json!(1), "{target}");
assert_eq!(fill(&s, shape), Paint::solid(Color::gray(0.3)), "{target}");
assert_eq!(fills(&s, &[a, b]), members, "{target}");
assert_eq!(steps(&s), n + 1);
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(fill(&s, shape), before);
assert_eq!(fills(&s, &[a, b]), members);
}
}
#[test]
fn a_selected_graph_keeps_the_fills_of_generated_design_art() {
let mut s = session();
let a = rect(&mut s, 0.0);
s.execute("paint.setFill", &json!({"ids": [a.0], "color": "#336699"})).unwrap();
select(&mut s, &[a]);
s.execute("graph.design", &json!({"new": "Tile"})).unwrap();
let graph = NodeId(
s.execute("graph.create", &json!({"type": "column", "x": 100, "y": 100, "width": 200, "height": 150, "series": ["A"], "rows": [[20], [30]]}))
.unwrap()["id"]
.as_u64()
.unwrap(),
);
s.execute("graph.column", &json!({"id": graph.0, "design": "Tile"})).unwrap();
let mut design_paths = vec![];
let d = &s.doc().unwrap().doc;
d.node(graph).unwrap().walk(&mut |n| {
if matches!(n.kind, NodeKind::Path { .. }) && super::is_design_art(d, n.id) && !n.appearance.fill_paint().is_none() {
design_paths.push(n.id);
}
});
assert!(!design_paths.is_empty());
let before = fills(&s, &design_paths);
select(&mut s, &[graph]);
s.execute(C, &json!({"scheme": "gray", "min": 30, "max": 30})).unwrap();
assert_eq!(fills(&s, &design_paths), before);
}
#[test]
fn a_compound_path_in_a_graph_series_takes_a_color() {
let mut s = session();
let graph = NodeId(
s.execute("graph.create", &json!({"type": "column", "x": 100, "y": 100, "width": 200, "height": 150, "series": ["A"], "rows": [[20], [30]]}))
.unwrap()["id"]
.as_u64()
.unwrap(),
);
let d = &s.doc().unwrap().doc;
let series = d.node(graph).unwrap().children().into_iter().flatten().find(|n| n.extras().series_index.is_some()).unwrap();
let group = series.id;
let marks: Vec<NodeId> = series.children().into_iter().flatten().filter(|m| matches!(m.kind, NodeKind::Path { .. })).map(|m| m.id).collect();
assert!(marks.len() >= 2);
let marks = &marks[..2];
select(&mut s, marks);
let compound = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap());
assert_eq!(s.doc().unwrap().doc.parent_of(compound), Some(group), "the compound path is directly in the series group");
for ids in [vec![compound], vec![marks[0]], vec![group]] {
let before = fill(&s, compound);
let r = s.execute(C, &json!({"scheme": "gray", "min": 40, "max": 40, "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})).unwrap();
assert!(r["count"].as_u64().unwrap() >= 1, "{ids:?}");
assert_ne!(fill(&s, compound), before, "{ids:?}");
s.execute("edit.undo", &json!({})).unwrap();
}
}
#[test]
fn a_compound_in_a_graph_series_takes_a_color_after_its_design_is_deleted() {
for kind in ["column", "line", "scatter"] {
let mut s = session();
let a = rect(&mut s, 0.0);
select(&mut s, &[a]);
s.execute("graph.design", &json!({"new": "Tile"})).unwrap();
let graph = NodeId(
s.execute(
"graph.create",
&json!({"type": kind, "x": 100, "y": 100, "width": 200, "height": 150, "series": ["X", "A"], "rows": [[10, 20], [20, 30]]}),
)
.unwrap()["id"]
.as_u64()
.unwrap(),
);
s.execute(if kind == "column" { "graph.column" } else { "graph.marker" }, &json!({"id": graph.0, "design": "Tile"})).unwrap();
s.execute("graph.design", &json!({"delete": "Tile"})).unwrap();
let d = &s.doc().unwrap().doc;
assert!(d.graph_designs.is_empty());
let series = d.node(graph).unwrap().children().into_iter().flatten().find(|n| n.extras().series_index.is_some()).unwrap();
let group = series.id;
let index = series.extras().series_index.unwrap() as usize;
let spec = d.node(graph).unwrap().extras().graph.as_deref().unwrap();
if kind == "column" {
assert_eq!(spec.series_columns[index].as_ref().unwrap().design, "Tile");
} else {
assert_eq!(spec.series_markers[index].as_deref(), Some("Tile"));
}
let marks: Vec<NodeId> = series
.children()
.into_iter()
.flatten()
.filter(|m| matches!(m.kind, NodeKind::Path { .. }) && !m.appearance.fill_paint().is_none())
.map(|m| m.id)
.collect();
assert!(marks.len() >= 2, "{kind}");
let marks = &marks[..2];
select(&mut s, marks);
let compound = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap());
assert_eq!(s.doc().unwrap().doc.parent_of(compound), Some(group), "{kind}");
let before = fill(&s, compound);
let members = fills(&s, marks);
select(&mut s, &[graph]);
let result = s.execute(C, &json!({"scheme": "gray", "min": 40, "max": 40})).unwrap();
assert!(result["count"].as_u64().unwrap() >= 1, "{kind}");
assert_ne!(fill(&s, compound), before, "{kind}");
assert_eq!(fills(&s, marks), members, "{kind}");
}
}
#[test]
fn a_user_compound_in_a_series_with_a_plain_path_design_takes_a_color() {
for kind in ["column", "line", "scatter"] {
let mut s = session();
let a = rect(&mut s, 0.0);
select(&mut s, &[a]);
s.execute("graph.design", &json!({"new": "Tile"})).unwrap();
assert!(matches!(s.doc().unwrap().doc.graph_designs[0].art.kind, NodeKind::Path { .. }));
let graph = NodeId(
s.execute(
"graph.create",
&json!({"type": kind, "x": 100, "y": 100, "width": 200, "height": 150, "series": ["X", "A"], "rows": [[10, 20], [20, 30]]}),
)
.unwrap()["id"]
.as_u64()
.unwrap(),
);
s.execute(if kind == "column" { "graph.column" } else { "graph.marker" }, &json!({"id": graph.0, "design": "Tile"})).unwrap();
let designed = s.doc().unwrap().doc.node(graph).unwrap().extras().graph.clone();
s.execute("edit.undo", &json!({})).unwrap();
s.edit("Set series design without replacing ordinary marks", |d, _| {
d.node_mut(graph).unwrap().extras_mut().graph = designed;
Ok(())
})
.unwrap();
let d = &s.doc().unwrap().doc;
let series = d.node(graph).unwrap().children().into_iter().flatten().find(|n| n.extras().series_index.is_some()).unwrap();
let group = series.id;
let marks: Vec<NodeId> = series
.children()
.into_iter()
.flatten()
.filter(|m| matches!(m.kind, NodeKind::Path { .. }) && !m.appearance.fill_paint().is_none())
.map(|m| m.id)
.collect();
assert!(marks.len() >= 2, "{kind}");
let marks = &marks[..2];
select(&mut s, marks);
let compound = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap());
assert_eq!(s.doc().unwrap().doc.parent_of(compound), Some(group), "{kind}");
assert!(!s.doc().unwrap().doc.node(compound).unwrap().extras().graph_design_art, "{kind}");
let members = fills(&s, marks);
for ids in [vec![compound], vec![marks[0]], vec![group], vec![graph]] {
let before = fill(&s, compound);
let result = s.execute(C, &json!({"scheme": "gray", "min": 40, "max": 40, "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})).unwrap();
assert!(result["count"].as_u64().unwrap() >= 1, "{kind}: {ids:?}");
assert_eq!(fill(&s, compound), Paint::solid(Color::gray(0.4)), "{kind}: {ids:?}");
assert_ne!(fill(&s, compound), before, "{kind}: {ids:?}");
assert_eq!(fills(&s, marks), members, "{kind}: {ids:?}");
s.execute("edit.undo", &json!({})).unwrap();
}
}
}
#[test]
fn grouped_paths_in_a_graph_series_keep_their_fills_as_for_paint_set_fill() {
for kind in ["column", "line", "scatter"] {
let mut s = session();
let graph = NodeId(
s.execute(
"graph.create",
&json!({"type": kind, "x": 100, "y": 100, "width": 200, "height": 150, "series": ["X", "A"], "rows": [[10, 20], [20, 30]]}),
)
.unwrap()["id"]
.as_u64()
.unwrap(),
);
let d = &s.doc().unwrap().doc;
let series = d.node(graph).unwrap().children().into_iter().flatten().find(|n| n.extras().series_index.is_some()).unwrap();
let group = series.id;
let marks: Vec<NodeId> = series
.children()
.into_iter()
.flatten()
.filter(|m| matches!(m.kind, NodeKind::Path { .. }) && !m.appearance.fill_paint().is_none())
.map(|m| m.id)
.collect();
assert!(marks.len() >= 2, "{kind}");
let marks = &marks[..2];
select(&mut s, marks);
let nested = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
assert_eq!(s.doc().unwrap().doc.parent_of(nested), Some(group), "{kind}");
let before = fills(&s, marks);
select(&mut s, &[graph]);
// `paint.setFill` on the graph leaves a group inside a series alone, as design art; so does this command.
s.execute("paint.setFill", &json!({"color": "#aa0000"})).unwrap();
let after_set_fill = fills(&s, marks);
s.execute("edit.undo", &json!({})).unwrap();
s.execute(C, &json!({"scheme": "gray", "min": 40, "max": 40})).unwrap();
assert_eq!(fills(&s, marks), before, "{kind}");
assert_eq!(after_set_fill, before, "{kind}: paint.setFill keeps grouped marks too");
}
}
#[test]
fn generated_compound_design_copies_in_a_graph_series_keep_their_fills() {
// `legacy` clears the design flags and keeps the series' design reference; `flag_only` keeps the flags and clears the
// reference, so each check keeps the copies' fills on its own.
let modes = [(false, false), (true, false), (false, true)];
for (kind, (legacy, flag_only)) in ["column", "line", "scatter"].into_iter().flat_map(|kind| modes.map(|mode| (kind, mode))) {
let mut s = session();
let marks = rects(&mut s, 2);
select(&mut s, &marks);
let compound = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap());
s.execute("paint.setFill", &json!({"ids": [compound.0], "color": "#336699"})).unwrap();
select(&mut s, &[compound]);
s.execute("graph.design", &json!({"new": "Tile"})).unwrap();
let graph = NodeId(
s.execute(
"graph.create",
&json!({"type": kind, "x": 100, "y": 100, "width": 200, "height": 150, "series": ["X", "A"], "rows": [[10, 20], [20, 30]]}),
)
.unwrap()["id"]
.as_u64()
.unwrap(),
);
s.execute(if kind == "column" { "graph.column" } else { "graph.marker" }, &json!({"id": graph.0, "design": "Tile"})).unwrap();
let d = &s.doc().unwrap().doc;
let series = d.node(graph).unwrap().children().into_iter().flatten().find(|n| n.extras().series_index.is_some()).unwrap();
let group = series.id;
let copies: Vec<NodeId> =
series.children().into_iter().flatten().filter(|m| matches!(m.kind, NodeKind::Compound { .. })).map(|m| m.id).collect();
assert!(!copies.is_empty(), "{kind}: the generated compound is directly in the series group");
for id in &copies {
assert!(d.node(*id).unwrap().extras().graph_design_art, "{kind}");
assert!(super::is_design_art(d, *id), "{kind}");
}
let mut art = vec![];
series.walk(&mut |n| {
if super::is_design_art(d, n.id) {
art.push(n.id);
}
});
if legacy {
s.edit("Clear graph design flags", |d, _| {
for id in &art {
d.node_mut(*id).unwrap().extras_mut().graph_design_art = false;
}
Ok(())
})
.unwrap();
}
if flag_only {
s.edit("Clear series design reference", |d, _| {
let mut extras = d.node_mut(graph).unwrap().extras_mut();
let spec = extras.graph.as_deref_mut().unwrap();
spec.series_columns.iter_mut().for_each(|c| *c = None);
spec.series_markers.iter_mut().for_each(|m| *m = None);
Ok(())
})
.unwrap();
for id in &copies {
assert!(s.doc().unwrap().doc.node(*id).unwrap().extras().graph_design_art, "{kind}");
}
}
let before = fills(&s, &art);
let runs = if flag_only { vec![copies.clone()] } else { vec![vec![graph], vec![group], copies] };
for ids in runs {
s.execute(C, &json!({"scheme": "gray", "min": 40, "max": 40, "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})).unwrap();
assert_eq!(fills(&s, &art), before, "{kind}, legacy: {legacy}, flag only: {flag_only}: {ids:?}");
}
}
}
#[test]
fn hidden_or_locked_compound_members_given_by_id_keep_the_compounds_fill() {
for hide in [true, false] {
let mut s = session();
let [a, b] = [0.0, 2.0].map(|x| rect(&mut s, x));
select(&mut s, &[a, b]);
let compound = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap());
s.execute("object.setProps", &if hide { json!({"id": a.0, "visible": false}) } else { json!({"id": a.0, "locked": true}) }).unwrap();
let member = s.doc().unwrap().doc.node(a).unwrap();
assert!(if hide { !member.visible } else { member.locked });
let parent = s.doc().unwrap().doc.node(compound).unwrap();
assert!(parent.visible && !parent.locked);
let before = s.doc().unwrap().doc.clone();
let n = steps(&s);
assert_eq!(s.execute(C, &json!({"ids": [a.0], "scheme": "gray", "min": 30, "max": 30})).unwrap()["count"], json!(0), "hidden: {hide}");
assert_eq!(fill(&s, compound), before.node(compound).unwrap().appearance.fill_paint());
assert!(*s.doc().unwrap().doc == *before);
assert_eq!(steps(&s), n);
}
}
#[test]
fn seeded_colors_follow_ids_order_without_repeating_objects() {
let mut s = session();
let ids = rects(&mut s, 3);
s.execute(C, &json!({"ids": ids.iter().map(|id| id.0).collect::<Vec<_>>(), "seed": 7})).unwrap();
let first = fills(&s, &ids);
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(s.execute(C, &json!({"ids": [ids[2].0, ids[0].0, ids[2].0, ids[1].0], "seed": 7})).unwrap()["count"], json!(3));
assert_eq!(fills(&s, &[ids[2], ids[0], ids[1]]), first);
}
#[test]
fn nested_members_color_the_outermost_compound_unless_an_ancestor_is_blocked() {
for blocked in ["none", "hidden", "locked", "artboard"] {
let mut s = session();
let [a, b, c] = [0.0, 2.0, 4.0].map(|x| rect(&mut s, x));
select(&mut s, &[a]);
let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
select(&mut s, &[group, b]);
let inner = NodeId(s.execute("object.compoundShape.make", &json!({})).unwrap()["id"].as_u64().unwrap());
select(&mut s, &[inner, c]);
let outer = NodeId(s.execute("object.compoundShape.make", &json!({})).unwrap()["id"].as_u64().unwrap());
match blocked {
"hidden" => {
s.execute("object.setProps", &json!({"id": group.0, "visible": false})).unwrap();
}
"locked" => {
s.execute("object.setProps", &json!({"id": inner.0, "locked": true})).unwrap();
}
"artboard" => {
s.execute("artboard.setProps", &json!({"index": 0, "locked": true})).unwrap();
}
_ => {}
}
let before = s.doc().unwrap().doc.clone();
let members = fills(&s, &[a, b, c, group, inner]);
let n = steps(&s);
let r = s.execute(C, &json!({"ids": [a.0], "scheme": "gray", "min": 30, "max": 30})).unwrap();
assert_eq!(fills(&s, &[a, b, c, group, inner]), members, "{blocked}");
if blocked == "none" {
assert_eq!(r["count"], json!(1));
assert_eq!(fill(&s, outer), Paint::solid(Color::gray(0.3)));
assert_eq!(steps(&s), n + 1);
s.execute("edit.undo", &json!({})).unwrap();
} else {
assert_eq!(r["count"], json!(0), "{blocked}");
assert_eq!(steps(&s), n, "{blocked}");
}
assert!(*s.doc().unwrap().doc == *before, "{blocked}");
}
}
#[test]
fn an_invalid_series_index_keeps_ordinary_subgroups_reachable() {
let mut s = session();
let graph = NodeId(
s.execute("graph.create", &json!({"type": "column", "x": 100, "y": 100, "width": 200, "height": 150, "series": ["A"], "rows": [[20], [30]]}))
.unwrap()["id"]
.as_u64()
.unwrap(),
);
let series = s.doc().unwrap().doc.node(graph).unwrap().children().unwrap().iter().find(|n| n.extras().series_index == Some(0)).unwrap();
let group = series.id;
let marks: Vec<NodeId> = series.children().unwrap().iter().filter(|n| matches!(n.kind, NodeKind::Path { .. })).map(|n| n.id).collect();
assert!(!marks.is_empty());
select(&mut s, &marks);
s.execute("object.group", &json!({})).unwrap();
s.edit("Set series index", |d, _| {
d.node_mut(group).unwrap().extras_mut().series_index = Some(u32::MAX);
Ok(())
})
.unwrap();
let before = fills(&s, &marks);
let r = s.execute(C, &json!({"ids": [group.0], "scheme": "gray", "min": 30, "max": 30})).unwrap();
assert_eq!(r["count"], json!(marks.len()));
assert!(fills(&s, &marks).iter().all(|p| *p == Paint::solid(Color::gray(0.3))));
assert_ne!(fills(&s, &marks), before);
assert!(s.doc().unwrap().doc.node(graph).unwrap().extras().graph.as_ref().unwrap().series_paints.is_empty());
}
#[test]
fn a_tint_swatch_with_a_deleted_base_is_refused_without_a_change() {
let mut s = session();
let ids = rects(&mut s, 2);
select(&mut s, &ids);
s.execute("swatch.new", &json!({"name": "Ink", "color": "#e01020", "spot": true})).unwrap();
let tint = s.execute("swatch.new", &json!({"name": "Pale", "swatch": "Ink", "tint": 40})).unwrap()["name"].as_str().unwrap().to_string();
s.execute("swatch.delete", &json!({"name": "Ink", "unlink": false})).unwrap();
let d = &s.doc().unwrap().doc;
assert!(d.swatch("Ink").is_none());
assert_eq!(d.swatch_link(&tint), Some(("Ink".to_string(), 0.4)));
let before = d.clone();
let n = steps(&s);
let e = s.execute(C, &json!({"scheme": "tint", "swatch": tint, "min": 10, "max": 80})).unwrap_err().to_string();
assert!(e.contains("base swatch `Ink`"), "{e}");
assert!(*s.doc().unwrap().doc == *before);
assert_eq!(steps(&s), n);
}
#[test]
fn an_inverted_range_that_rounds_to_equal_f32_bounds_is_refused() {
let mut s = session();
let a = rect(&mut s, 0.0);
select(&mut s, &[a]);
s.execute("swatch.new", &json!({"name": "Ink", "color": "#e01020", "spot": true})).unwrap();
let before = s.doc().unwrap().doc.clone();
let n = steps(&s);
for p in [json!({"scheme": "gray", "min": 50.0000001, "max": 50}), json!({"scheme": "tint", "swatch": "Ink", "min": 50.0000001, "max": 50})] {
let e = s.execute(C, &p).unwrap_err().to_string();
assert!(e.contains("`min` is greater than `max`"), "{p}: {e}");
assert!(*s.doc().unwrap().doc == *before);
assert_eq!(steps(&s), n);
}
}
#[test]
fn no_undo_step_when_no_fill_changes() {
let mut s = session();
let ids = rects(&mut s, 2);
select(&mut s, &ids);
s.execute(C, &json!({"scheme": "gray", "min": 40, "max": 40})).unwrap();
let n = steps(&s);
let r = s.execute(C, &json!({"scheme": "gray", "min": 40, "max": 40})).unwrap();
assert_eq!((r["count"].clone(), steps(&s)), (json!(0), n), "the same grays again");
// Only unfilled objects: nothing to color.
s.execute("paint.setFill", &json!({"none": true})).unwrap();
let n = steps(&s);
assert_eq!(s.execute(C, &json!({})).unwrap()["count"], json!(0));
assert_eq!(steps(&s), n);
}
#[test]
fn bad_params_are_refused() {
let mut s = session();
let a = rect(&mut s, 0.0);
select(&mut s, &[a]);
s.execute("swatch.new", &json!({"name": "Process", "color": "#336699"})).unwrap();
s.execute("swatch.new", &json!({"name": "Ink", "color": "#e01020", "spot": true})).unwrap();
let (before, n) = (s.doc().unwrap().doc.clone(), steps(&s));
let bad: [(Value, &str); 14] = [
(json!({"scheme": "rainbow"}), "`scheme` must be color, tint or gray"),
(json!({"scheme": 3}), "`scheme` must be a string"),
(json!({"min": 10}), "`min` and `max` go with scheme tint or gray"),
(json!({"scheme": "gray", "swatch": "Ink"}), "`swatch` goes with scheme tint"),
(json!({"scheme": "gray", "min": -1}), "`min` must be from 0 to 100"),
(json!({"scheme": "gray", "max": 101}), "`max` must be from 0 to 100"),
(json!({"scheme": "gray", "min": 80, "max": 20}), "`min` is greater than `max`"),
(json!({"scheme": "gray", "max": "50"}), "`max` must be a number"),
(json!({"scheme": "tint"}), "scheme tint needs a `swatch`"),
(json!({"scheme": "tint", "swatch": "Nope"}), "no swatch `Nope`"),
(json!({"scheme": "tint", "swatch": "Process"}), "is a process colour"),
(json!({"seed": -1}), "`seed` must be a whole number"),
(json!({"seed": 1.5}), "`seed` must be a whole number"),
(json!({"ids": [999_999]}), "no such object id"),
];
for (p, want) in bad {
let e = s.execute(C, &p).unwrap_err().to_string();
assert!(e.contains(want), "{p}: {e}");
}
assert_eq!(steps(&s), n);
assert!(*s.doc().unwrap().doc == *before, "the document is unchanged");
}
#[test]
fn art_on_a_locked_artboard_given_by_id_keeps_its_fill() {
let mut s = session();
let a = rect(&mut s, 0.0);
let before = fill(&s, a);
s.execute("artboard.setProps", &json!({"index": 0, "locked": true})).unwrap();
let n = steps(&s);
assert_eq!(s.execute(C, &json!({"ids": [a.0], "seed": 3})).unwrap()["count"], json!(0));
assert_eq!(fill(&s, a), before);
assert_eq!(steps(&s), n);
}
@@ -3,7 +3,7 @@
//! the bridges connect, replacing the circles or added above them.
use serde_json::{Value, json};
use vectorcraft_doc::{Document, Node, NodeId, NodeKind};
use vectorcraft_doc::{Document, LiveShape, Node, NodeId, NodeKind};
use vectorcraft_geom::PathData;
use vectorcraft_pathops::addons::pathtools as pt;
@@ -34,7 +34,7 @@ pub(super) fn specs() -> Vec<CommandSpec> {
"Smooth Bridge",
["Object", "Plug-ins", "Path Precision Tools"],
None,
"{radius?: % 1..1000 (100; the radius of each bridge's two arcs as a percentage of the smaller circle's radius: larger makes a wider, gentler bridge), gap?: pt 0..1000 (instead of radius: the arcs' radius is the smaller circle's radius plus this gap, so each arc stays this gap away from a circle of the smaller circle's size about the arc's center; for equal circles this gap apart that is where a third circle this gap from both sits, as in a triangular grid, so the channels around an empty place in such a grid are one width; giving both is an error), reach?: pt 0..10000 (10; with three or more circles: how far apart two circles' outlines may be for a bridge between them, overlapping ones included; two circles are bridged at any distance), keepOriginals?: bool (false: each outline replaces its circles, painted as the topmost of them, and a group or compound path the other circles leave empty goes; true: it goes directly above that circle and the circles stay), ids?: [id] (default: the selection; a group, other than a clipping group, gives the objects inside it)} join circles (paths whose outline is a circle, not hidden or locked) into metaball (aka meatball) shapes. Two circles become one closed outline: around each circle on its side away from the other, and along two concave arcs, one on each side, that touch both circles so the outline runs on smoothly into them. With three or more, every two circles within reach are bridged the same way, and the bridges that connect are united into one shape each (holes smaller than 1% of the smallest circle's area are filled); a pair within reach but too far apart for the radius gets no bridge, and so does one whose neck would be thinner than the precision its shape is united at, and a circle bridged to no other is left as it is. Overlapping and touching circles are joined too. One circle inside another (among three or more, any such pair within reach) is an error; so are two circles too far apart for the radius (the arcs would not reach both, or would cross), or three or more with no pair the arcs can join, which suggests a larger radius or gap when the largest one would bridge them; so are no two circles within reach, more than 2000 circles and more than 8000 bridges. One undo step; the outlines (and the circles left as they are) are selected → {ids, alone}, with {id} too for two circles",
"{radius?: % 1..1000 (100; the radius of each bridge's two arcs as a percentage of the smaller circle's radius: larger makes a wider, gentler bridge), gap?: pt 0..1000 (instead of radius: the arcs' radius is the smaller circle's radius plus this gap, so each arc stays this gap away from a circle of the smaller circle's size about the arc's center; for equal circles this gap apart that is where a third circle this gap from both sits, as in a triangular grid, so the channels around an empty place in such a grid are one width; giving both is an error), reach?: pt 0..10000 (10; with three or more circles: how far apart two circles' outlines may be for a bridge between them, overlapping ones included; two circles are bridged at any distance), keepOriginals?: bool (false: each outline replaces its circles, painted as the topmost of them, and a group or compound path the other circles leave empty goes; true: it goes directly above that circle and the circles stay), ids?: [id] (default: the selection; a group, other than a clipping group, gives the objects inside it)} join circles (paths whose outline is a circle, not hidden or locked) into metaball (aka meatball) shapes. Two circles become one closed outline: around each circle on its side away from the other, and along two concave arcs, one on each side, that touch both circles so the outline runs on smoothly into them. With three or more, every two circles within reach are bridged the same way, and the bridges that connect are united into one shape each (holes smaller than 1% of the smallest circle's area are filled); a pair within reach but too far apart for the radius gets no bridge, and so does one whose neck would be thinner than the precision its shape is united at, and a circle bridged to no other is left as it is. Overlapping and touching circles are joined too. An object that is not a circle is an error that says why (an ellipse whose width and height differ, a compound path, a hidden or locked object, or another object). One circle inside another (among three or more, any such pair within reach) is an error; so are two circles too far apart for the radius (the arcs would not reach both, or would cross), or three or more with no pair the arcs can join, which suggests a larger radius or gap when the largest one would bridge them; so are no two circles within reach, more than 2000 circles and more than 8000 bridges. One undo step; the outlines (and the circles left as they are) are selected → {ids, alone}, with {id} too for two circles",
has_selection,
bridge
)]
@@ -61,17 +61,30 @@ fn bridge(s: &mut Session, p: &Value) -> Result<Value> {
if roots.len() > pt::MAX_BRIDGED_CIRCLES {
return Err(bad(C, "select at most 2000 circles to bridge"));
}
let circles: Vec<(NodeId, pt::Circle)> = {
// The circles, and why the first object that is not one is refused.
let (circles, why): (Vec<(NodeId, pt::Circle)>, Option<&str>) = {
let d = &s.doc()?.doc;
let editable = d.editable();
d.paint_order(roots.iter().copied())
let mut why = None;
let circles = d
.paint_order(roots.iter().copied())
.into_iter()
.filter_map(|id| match &d.node(id)?.kind {
NodeKind::Path { path, guide: false, clipping: false, .. } if editable(id) => Some((id, pt::circle_of(path)?)),
_ => None,
.filter_map(|id| {
let found = match &d.node(id)?.kind {
NodeKind::Path { path, guide: false, clipping: false, .. } if editable(id) => pt::circle_of(path).map(|c| (id, c)),
_ => None,
};
if found.is_none() && why.is_none() {
why = Some(not_a_circle(d, id, editable(id)));
}
found
})
.collect()
.collect();
(circles, why)
};
if let Some(why) = why {
return Err(bad(C, format!("select two or more circles to bridge: {why}")));
}
if circles.len() != roots.len() || circles.len() < 2 {
return Err(bad(C, "select two or more circles to bridge"));
}
@@ -159,6 +172,26 @@ fn members(d: &Document, ids: &[NodeId]) -> Vec<NodeId> {
out
}
/// Why object `id`, which is not a circle the command bridges, is refused; `editable` says whether it can be
/// edited (not hidden or locked).
fn not_a_circle(d: &Document, id: NodeId, editable: bool) -> &'static str {
// A pie spanning the whole turn, or none of it, is the whole ellipse.
let whole = |(start, end): (f64, f64)| {
let span = (end - start).rem_euclid(360.0);
span < 1e-9 || 360.0 - span < 1e-9
};
match d.node(id).map(|n| &n.kind) {
_ if !editable => "a selected object is hidden or locked",
// A transform that stretches an ellipse leaves its stored width and height as they were, so one stored with
// equal width and height gets the general message.
Some(NodeKind::Path { live: Some(live), guide: false, clipping: false, .. }) if matches!(**live, LiveShape::Ellipse { w, h, pie, .. } if whole(pie) && w != h) => {
"an ellipse whose width and height differ is not a circle: draw it with Shift held, or give it equal width and height"
}
Some(NodeKind::Compound { .. }) => "a compound path is not a circle: release it first",
_ => "a selected object is not a circle",
}
}
/// Remove each of `parents` that is left with nothing in it, and then each group above it left with
/// nothing in it in turn. Layers stay.
fn remove_emptied(d: &mut Document, parents: Vec<NodeId>) -> Result<()> {
@@ -2,7 +2,7 @@
//! gap, many circles joined to their neighbors within reach, and what it refuses.
use serde_json::{Value, json};
use vectorcraft_doc::{NodeId, NodeKind};
use vectorcraft_doc::{LiveShape, NodeId, NodeKind};
use vectorcraft_geom::kurbo::Shape;
use crate::Session;
@@ -173,6 +173,50 @@ fn far_apart_nested_and_other_objects_are_refused() {
assert_eq!(s.doc().unwrap().history.undo.len(), steps, "nothing changed, no undo step");
}
#[test]
fn a_refusal_says_why_an_object_is_not_a_circle() {
let mut s = session();
let a = circle(&mut s, 100.0, 100.0, 20.0);
let b = circle(&mut s, 160.0, 100.0, 20.0);
// A hand-drawn ellipse 1 pt taller than wide.
let oval = NodeId(s.execute("shape.ellipse", &json!({"x": 200, "y": 80, "width": 40, "height": 41})).unwrap()["id"].as_u64().unwrap());
let square = NodeId(s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap());
let stretched = circle(&mut s, 300.0, 100.0, 20.0);
s.execute("object.transform", &json!({"ids": [stretched.0], "matrix": [2.0, 0.0, 0.0, 1.0, 0.0, 0.0]})).unwrap();
let steps = s.doc().unwrap().history.undo.len();
let e = err(&mut s, json!({"ids": [a.0, oval.0]}));
assert!(
e.ends_with(
"select two or more circles to bridge: an ellipse whose width and height differ is not a circle: draw it with Shift held, or give it equal width and height"
),
"{e}"
);
let e = err(&mut s, json!({"ids": [a.0, square.0]}));
assert!(e.ends_with("select two or more circles to bridge: a selected object is not a circle"), "{e}");
// A circle stretched by a transform keeps its equal stored width and height, so it is not called unequal.
let equal = match s.doc().unwrap().doc.node(stretched).map(|n| &n.kind) {
Some(NodeKind::Path { live: Some(live), .. }) => matches!(**live, LiveShape::Ellipse { w, h, .. } if w == h),
_ => false,
};
assert!(equal, "the stretched circle keeps a live ellipse of equal width and height");
let e = err(&mut s, json!({"ids": [a.0, stretched.0]}));
assert!(e.ends_with("select two or more circles to bridge: a selected object is not a circle"), "{e}");
let e = err(&mut s, json!({"ids": [a.0]}));
assert!(e.ends_with("select two or more circles to bridge"), "one circle: {e}");
select(&mut s, &[b]);
s.execute("object.hide", &json!({})).unwrap();
let e = err(&mut s, json!({"ids": [a.0, b.0]}));
assert!(e.ends_with("select two or more circles to bridge: a selected object is hidden or locked"), "{e}");
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().history.undo.len(), steps, "no undo step for a refusal");
select(&mut s, &[a, b]);
let compound = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap());
let c = circle(&mut s, 300.0, 200.0, 20.0);
let e = err(&mut s, json!({"ids": [compound.0, c.0]}));
assert!(e.ends_with("select two or more circles to bridge: a compound path is not a circle: release it first"), "{e}");
}
/// A 3 × 3 grid of circles of radius 10, 4 apart (centers 24 apart), in rows from (100, 100).
fn grid(s: &mut Session) -> Vec<NodeId> {
(0..9).map(|k| circle(s, 100.0 + 24.0 * (k % 3) as f64, 100.0 + 24.0 * (k / 3) as f64, 10.0)).collect()
+1 -1
View File
@@ -171,7 +171,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Nudge in Perspective",
[],
None,
"{dx, dy: arrow direction (-1, 0 or 1), big?: bool (×10), copy?: bool} move the selection in perspective by the keyboard increment, as the arrow keys do with the Perspective Selection tool → {ids}",
"{dx, dy: arrow direction (-1, 0 or 1), big?: bool (×10), fine?: bool (÷10; with big, one increment), copy?: bool} move the selection in perspective by the keyboard increment (Snap to Grid doesn't apply), as the arrow keys do with the Perspective Selection tool → {ids}",
has_selection,
persp_nudge
),
@@ -563,13 +563,16 @@ pub(super) fn plane_match(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({ "plane": plane.id(), "offset": depth }))
}
/// `perspective.nudge`, the arrow keys with the Perspective Selection tool: the selection moves
/// within its plane by [`nudge_step`](crate::cmd::object::nudge_step), measured on the page at the
/// centre of its perspective box, without Snap to Grid.
pub(super) fn persp_nudge(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "perspective.nudge";
let (dx, dy) = (number_or(p, "dx", 0.0, C)?, number_or(p, "dy", 0.0, C)?);
if !(dx.is_finite() && dy.is_finite()) || (dx == 0.0 && dy == 0.0) {
return Err(bad(C, "dx and dy give the arrow's direction"));
}
let k = s.prefs.keyboard_increment * if switch_or(p, "big", false, C)? { 10.0 } else { 1.0 };
let k = crate::cmd::object::nudge_step(s.prefs.keyboard_increment, switch_or(p, "big", false, C)?, switch_or(p, "fine", false, C)?);
let copy = switch_or(p, "copy", false, C)?;
let ids = selected_roots(s)?;
// The step is measured on the page at the centre of the selection's perspective box.
@@ -578,7 +581,12 @@ pub(super) fn persp_nudge(s: &mut Session, p: &Value) -> Result<Value> {
let (plane, depth, rect) = g.plane_bounds(&st.doc, &ids).ok_or_else(|| EngineError::Other("the selection isn't in perspective".into()))?;
let from = g.homography_at(plane, depth).and_then(|h| h.apply(rect.center())).ok_or_else(beyond_horizon)?;
let to = from + vectorcraft_geom::Vec2::new(dx.clamp(-1.0, 1.0), dy.clamp(-1.0, 1.0)) * k;
persp_move(s, &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "from": [from.x, from.y], "to": [to.x, to.y], "copy": copy}))
// The arrow keys move by the step: Snap to Grid would pull an edge on a gridline back onto it,
// so a nudge smaller than a quarter cell would move nothing.
persp_move(
s,
&json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "from": [from.x, from.y], "to": [to.x, to.y], "copy": copy, "snap": false}),
)
}
pub(super) fn persp_draw(s: &mut Session, p: &Value) -> Result<Value> {
+29
View File
@@ -39,6 +39,15 @@ pub fn specs() -> Vec<CommandSpec> {
has_doc,
doc_move
),
cmd!(
"document.setSaved",
"Set Saved State",
[],
None,
"{index?: the document (default: the current one), saved: true or false} records the document as saved (true: Close asks nothing until the next edit) or as having unsaved changes (false), without saving it or adding an undo step; a document already in that state is left as it is",
has_doc,
doc_set_saved
),
cmd!(query "document.inspect", "Inspect Document", [], None, "{depth?, childLimit?, ids?: [id…] (list just these nodes, of any level, in this order, under `nodes` in place of `layers`; an unknown id is an error; at most 10000), kind?: panel label such as Layer; Group; Path; Type or Image (exact, ignoring case; list every such node under `nodes`, each with `path`, its ancestor ids with the layer first, searching the subtrees of `ids` when given), limit?: at most this many entries of the list, offset?: entries skipped first (default 0; with `ids`, `kind`, `limit` or `offset` the reply adds `total`, the entries before paging)} → path (the document's file; null when automation read roots are in force and the file is outside them), layer tree (each node: id, name, kind, visible, locked, bounds, opacity (0–1) and opacityPct (0–100 %, the scale object.setProps takes) when below 1, blend when not Normal, fill, stroke and strokeWidth of objects and compound paths; a compound path's members have compoundMember: true instead of paint, which is the compound's), artboards, selection, history (a sliced tree reports childCount); without the scope options the reply is the whole layer tree", has_doc, doc_inspect),
cmd!(query "document.node", "Inspect Object", [], None, "{id, summary?: compact summary, depth?: child levels in the summary (default all), childLimit?: children shown per node (default all; a level that shows fewer reports childCount)} → one object", has_doc, doc_node),
cmd!(query "document.find", "Find Objects", [], None, "{name?: substring of the Layers panel name, kind?: panel label such as Group; Path; Type or Image (exact), text?: substring of type content, within?: [x, y, width, height] (an object's geometric bounds inside this rectangle, edges included; document points as document.inspect's bounds; layers never match this or the size filters), intersects?: [x, y, width, height] (bounds touching or overlapping it), minWidth?, maxWidth?, minHeight?, maxHeight?: pt (the bounds' size), minThickness?, maxThickness?: pt (the smaller of the bounds' width and height), minArea?, maxArea?: pt² (the bounds' width × height), minAnchors?, maxAnchors?: anchor points of a path (a compound path's members together; other objects never match), select?: bool (also select the matches, leaving out hidden and locked ones, those inside another match, and a compound path's members unless the compound path is isolated; Select > Reselect repeats it), limit?: max matches listed (default 100, 0 counts only)} → {matches: [{id, name, kind, path}], total, selected (with select: the count selected)}; at least one filter, all of them matching", has_doc, doc_find),
@@ -257,6 +266,26 @@ fn doc_activate(s: &mut Session, p: &Value) -> Result<Value> {
if s.set_active(i) { ok() } else { Err(bad("document.activate", "no such document")) }
}
fn doc_set_saved(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "document.setSaved";
let i = opt_u64(p, C, "index")?.map(index).or(s.active_index()).ok_or(EngineError::NoDocument)?;
let saved = match p.get("saved") {
None | Some(Value::Null) => return Err(bad(C, "missing `saved`: true or false")),
Some(Value::Bool(b)) => *b,
Some(_) => return Err(bad(C, "`saved` must be true or false")),
};
let uid = s.documents().get(i).map(|d| d.uid).ok_or_else(|| bad(C, "no such document"))?;
let st = s.document_mut(uid).ok_or_else(|| bad(C, "no such document"))?;
if st.is_dirty() == saved {
if saved {
st.mark_saved();
} else {
st.mark_unsaved();
}
}
ok()
}
fn doc_move(s: &mut Session, p: &Value) -> Result<Value> {
let n = s.documents().len();
let from = match p.get("from") {
+9
View File
@@ -125,6 +125,13 @@ pub use screens::{
builtin_presets as screen_export_builtin_presets, first_file as screen_first_file, preset_list as screen_export_preset_list,
preset_rows as screen_preset_rows,
};
pub(crate) use svg::{lost_artboards_warning as svg_lost_artboards_warning, preserves_editing as svg_preserves_editing};
/// Does a save in `format` (a format id) with options `p` write a legacy version 7 `.ai` file,
/// which holds the artboards its own options pick? An unknown version counts as one.
pub(crate) fn saves_legacy_ai(format: &str, p: &serde_json::Value) -> bool {
format == "ai" && formats::format(format).is_none_or(|f| legacy_ai::wanted("file.saveAs", f, p).unwrap_or(true))
}
pub use svg::options_map as svg_options;
/// Atomic file writes (a temporary file renamed over the target: a failed write never damages the
/// file it replaces), for the apps' own writers too.
@@ -141,6 +148,8 @@ mod formats;
#[cfg(not(target_arch = "wasm32"))]
pub(crate) use access::list_dir;
#[cfg(all(test, not(target_arch = "wasm32")))]
pub(crate) use access::{SCRIPT_OPEN_MAX_BYTES, SCRIPT_OPEN_TOO_LARGE};
pub(crate) use access::{check_images_in, check_scripts_of, with_readable_settings_folder};
pub use access::{check_linked_images, check_linked_scripts, write_file_with, write_save_file, write_save_file_with};
+30 -1
View File
@@ -267,14 +267,43 @@ pub(crate) fn may_write(path: &str) -> Result<()> {
crate::file_access::check_write(path).map_err(EngineError::Other)
}
/// The most a file read during a script command holds, the limit an importer reads.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) const SCRIPT_OPEN_MAX_BYTES: usize = vectorcraft_plugins::import::MAX_INPUT_BYTES;
/// The error of a file past [`SCRIPT_OPEN_MAX_BYTES`].
#[cfg(not(target_arch = "wasm32"))]
pub(crate) const SCRIPT_OPEN_TOO_LARGE: &str = "file exceeds 128 MiB";
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn read_file(path: &str) -> Result<Vec<u8>> {
use std::io::Read;
may_read(path)?;
// A device or pipe may never end: only a regular file is read to its end.
if !std::fs::metadata(path).map_err(|e| EngineError::Other(format!("{path}: {e}")))?.is_file() {
return Err(EngineError::Other(format!("{path}: not a file")));
}
std::fs::read(path).map_err(|e| EngineError::Other(format!("{path}: {e}")))
if crate::file_access::in_script_command() {
let max = SCRIPT_OPEN_MAX_BYTES;
let read = || -> std::io::Result<Vec<u8>> {
let file = std::fs::File::open(path)?;
let meta = file.metadata()?;
if !meta.is_file() {
return Err(std::io::Error::other("not a file"));
}
if meta.len() > max as u64 {
return Err(std::io::Error::other(SCRIPT_OPEN_TOO_LARGE));
}
let mut bytes = Vec::new();
file.take(max as u64 + 1).read_to_end(&mut bytes)?;
if bytes.len() > max {
return Err(std::io::Error::other(SCRIPT_OPEN_TOO_LARGE));
}
Ok(bytes)
};
read().map_err(|e| EngineError::Other(format!("{path}: {e}")))
} else {
std::fs::read(path).map_err(|e| EngineError::Other(format!("{path}: {e}")))
}
}
/// The first `max` bytes of the file at `path` (all of it when it is shorter). Anything but a
+9 -1
View File
@@ -73,7 +73,9 @@ pub(super) fn distinct_names_by(names: impl IntoIterator<Item = String>, key: im
/// Write an export's files for the destination `path` → `{path, bytes, files?, linked?, …extra}`
/// (`files`: every file when there are several; `linked`: the images it links to); with no path
/// → the same with `dataBase64` and `{name, dataBase64}` rows, named after `name`.
/// → the same with `dataBase64` and `{name, dataBase64}` rows, named after `name`. Every path is
/// checked against the file access in force before the first file is written, so a refused path
/// writes none of them.
pub(super) fn write_encoded(path: Option<&str>, name: &str, doc: &vectorcraft_doc::Document, enc: &Encoded, extra: Value) -> Result<Value> {
let files = enc.named(doc, path.unwrap_or(name));
let (main, linked) = files.split_at(enc.files.len());
@@ -82,6 +84,12 @@ pub(super) fn write_encoded(path: Option<&str>, name: &str, doc: &vectorcraft_do
None => json!({ "name": name, "dataBase64": vectorcraft_format::base64_encode(bytes) }),
};
if path.is_some() {
#[cfg(not(target_arch = "wasm32"))]
if files.len() > 1 {
for (p, _) in &files {
super::may_write(p)?;
}
}
for (p, bytes) in &files {
write_file(p, bytes)?;
}
+16 -1
View File
@@ -818,7 +818,7 @@ pub fn read_for_open_asking(
(linked_pages(name, bytes, path.as_deref(), &opts)?, None)
} else {
match super::importer::pick(name, bytes, p)? {
Some(plugin) => (super::importer::load(name, bytes, &plugin, p)?, None),
Some(plugin) => (super::importer::load(name, bytes, &plugin, p)?, opts.color_mode),
// The color mode `p` asks for converts the colors after the policies did, through the
// profiles the document keeps.
None => (load_with(name, bytes, &LoadOptions { color_mode: None, ..opts.clone() })?, opts.color_mode),
@@ -1096,6 +1096,21 @@ pub(super) fn open(s: &mut Session, p: &Value) -> Result<Value> {
source(p, "document.open")?
}
};
let given = |keys: &[&str]| keys.iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null()));
let (options, aliases) = (given(&["page", "cropTo"]), given(&["pages", "crop"]));
if crate::file_access::in_script_command() && (options || aliases) {
// An importer plug-in receives only the params, so it cannot apply the pages or the crop
// box; `linkPages` reads the file with the built-in reader before any importer.
let link_pages = p.get("linkPages").and_then(Value::as_bool) == Some(true);
let built_in = link_pages || super::importer::pick(src.name, &src.bytes, p)?.is_none();
let pdf = built_in
&& (!options
|| (detect(src.name, &src.bytes).is_some_and(|f| matches!(f.id, "pdf" | "ai" | "ait"))
&& !vectorcraft_pdf::is_postscript(&src.bytes)));
if !pdf {
return Err(bad("document.open", "PDF open options require a PDF file"));
}
}
// A relative path is the file in the working directory: its folder is where relative links
// are found (a bare file name has no folder of its own).
let path = src.path.map(super::absolute_path);
+7 -3
View File
@@ -22,6 +22,8 @@ pub struct LoadOptions {
pub pages: Option<String>,
/// The box each page's artboard (or placed frame) gets.
pub crop: CropTo,
/// Whether the options explicitly request the crop box.
pub explicit_crop_box: bool,
/// The password of an encrypted PDF.
pub password: Option<String>,
/// The colour mode the document opens in, its colours converted as Document Color Mode does
@@ -67,6 +69,7 @@ impl Default for LoadOptions {
Self {
pages: None,
crop: CropTo::default(),
explicit_crop_box: false,
password: None,
color_mode: None,
grays: Grays::default(),
@@ -147,6 +150,7 @@ impl LoadOptions {
Ok(Self {
pages,
crop,
explicit_crop_box: crop == CropTo::Crop && crop_to.or(crop_alias).is_some(),
password,
color_mode,
grays,
@@ -173,14 +177,14 @@ impl LoadOptions {
}
/// The PDF import options: `pages` resolved against the file's page count. A PDF-compatible
/// `.ai`, or a PDF saved with its editing data, asked for its crop box opens on its trim boxes,
/// its editor's artboards, with the bleed round them (its crop box takes the bleed in).
/// `.ai`, or a PDF saved with its editing data, opens on its trim boxes by default,
/// with the bleed around them. An explicit crop-box request uses its crop box.
fn import_options(&self, opened: &vectorcraft_pdf::Opened, editor_document: bool) -> Result<ImportOptions> {
let pages = match &self.pages {
None => None,
Some(range) => Some(parse_range(range, opened.page_count()).map_err(|e| err(format!("pages: {e}")))?),
};
let is_ai = self.crop == CropTo::Crop && opened.has_illustrator_data();
let is_ai = !self.explicit_crop_box && self.crop == CropTo::Crop && opened.has_illustrator_data();
Ok(ImportOptions {
pages,
crop: if is_ai { CropTo::Trim } else { self.crop },
+19 -4
View File
@@ -602,6 +602,7 @@ pub struct SaveJob {
stamped: Option<i64>,
/// The artboards also saved to files of their own (`separateArtboards`).
boards: Vec<usize>,
redact_paths: bool,
}
/// Writes the file at a path with what the filler it is given writes into it
@@ -963,7 +964,7 @@ fn job_for_stamped(s: &Session, st: &DocState, plan: SavePlan, stamped: Option<i
};
super::check_linked_scripts(cmd, plan.format.id, st, &checked)?;
super::access::check_native_images(cmd, plan.format.id, &st.doc, crate::cmd::links::LinkBase::of(st), &checked)?;
Ok(SaveJob { plan, doc, params, snapshot, source: st.doc.clone(), stamped, boards })
Ok(SaveJob { plan, doc, params, snapshot, source: st.doc.clone(), stamped, boards, redact_paths: false })
}
impl SaveJob {
@@ -1044,7 +1045,8 @@ impl SaveJob {
}
/// [`SaveJob::write`], once `stop` has seen the paths of every file it writes to a path, in
/// order: when `stop` returns a value, nothing is written and that value is returned. Work
/// order: when `stop` returns a value, nothing is written and that value is returned. When a
/// save writes several files and the file access in force refuses one, none is written. Work
/// canceled ([`crate::cancel`]) before the first file is written returns
/// [`crate::EngineError::Cancelled`] and writes nothing; once the first file is written, the
/// others are written too.
@@ -1069,6 +1071,18 @@ impl SaveJob {
if let Some(stopped) = stop(&files.iter().map(|(p, _)| p.as_str()).collect::<Vec<_>>()) {
return Ok(stopped);
}
// Every path is checked against the file access in force before the first file is
// written. A refused file is not handed to `write`, so a writer that does not check the
// file access writes none of the files; the error is the file access's own refusal, as
// the writers that check it give.
#[cfg(not(target_arch = "wasm32"))]
if files.len() > 1
&& let Some(refused) = files
.iter()
.find_map(|(p, _)| super::may_write(p).err().map(|e| if self.redact_paths { super::access::naming_in_error(e, p) } else { e }))
{
return Err(refused);
}
for (i, (p, bytes)) in files.iter().enumerate() {
if i == 0 {
write(p, bytes)?;
@@ -1229,9 +1243,10 @@ pub fn save_with(s: &mut Session, plan: SavePlan, write: impl FnMut(&str, &[u8])
/// A save command: plan, then write with the file system (a native file as it is encoded).
pub(crate) fn save(s: &mut Session, mode: SaveMode, p: &Value) -> Result<Value> {
let plan = save_plan(s, mode, p)?;
let job = save_job(s, plan)?;
let mut job = save_job(s, plan)?;
let uid = s.doc()?.uid;
let given = str_param(p, "path").is_some_and(|g| !g.is_empty());
job.redact_paths = !given;
// Without a path, the files written are the document's own file and those beside it.
let mut write = |path: &str, fill: &mut dyn FnMut(&mut dyn std::io::Write) -> std::io::Result<()>| {
super::write_save_file_with(path, fill).map_err(|e| if given { e } else { super::access::naming_in_error(e, path) })
@@ -1373,7 +1388,7 @@ pub(super) fn specs() -> Vec<CommandSpec> {
"Save Document",
[],
None,
"{path?, format?: vectorcraft|template|pdf|svg|svgz|ai|eps (default: the path's extension, else the document's own format), options?: {…the format's options, see file.formatOptions; default: as last saved}, svg?: {…SVG options} (an SVG save keeps hidden layers, display:none, unless hiddenLayers is false), …the SVG and PDF options given flat instead (an option given flat or in svg and in options with different values is an error), compress?: bool (native, also in options: gzip; default: the useCompression preference; warnings name an option given flat or in options that the file doesn't read: a legacy .ai reads only its own options, and other .ai files don't read outlineText, hiddenObjects, transparentImages or preserveEditing), version?: 4 (3, 2 or 1: for older VectorCraft versions; 1 and 2 are never compressed), preview?: false (embed a PNG of the first artboard, at most 256 px), precision?: 0..9 (native: round path anchors and handles to this many decimal places, a smaller file; colors, transforms and type stay exact; default: exact, and a later save without it writes exactly again), separateArtboards?: false (native and .ai: also save each artboard of `range` to <name>-<artboard>.<ext> beside the file, holding that artboard and the art touching it; the result's files lists every file written), range?: \"1-3, 5\"|\"all\" (default; with separateArtboards), includeLinked?: false (keep linked files' own pixels, not just their previews; they stay linked), embedProfiles?: true (carry the ICC profiles loaded from files that the document is tagged with; opening the file installs them where missing), pdfCompatible?: true (native: also carry a PDF of every artboard; false omits it) | true for .ai (false: blank pages, only the native document; a .ai file's compress, default true, is its compression.compressText), modified?: Unix seconds|null (the File Info modified date, and created date when there is none, a save to a file stamps; default now, recorded in the journal so a replay matches; null: leave the dates)} → {path, format, bytes, warnings, files?: [path…] (the file and its artboards' files), linked?: [path…] (images an SVG links to)}. Save writes one artboard, except a .ai file and EPS (below): a .ai file is a PDF-compatible file of every artboard carrying the native document (preserveEditing always on; PDF options flat or in options), which document.open restores exactly, on the active artboard (the app's, else the one the document opened on; with editingData: false, the first); separateArtboards writes more files, one per artboard. EPS takes the options of document.exportEps: by default one file whose bounding box fits the visible art (the first artboard when no art shows), carrying the whole editable document; useArtboards: true (also when artboard, artboards or range names artboards; file.formatOptions then reports it true) makes the chosen artboard the page, drawn with its background color (without Use Artboards, only the first artboard's page when no art shows has its color), and with two or more chosen the file at the path is the central file of the visible art (again the first artboard when none shows) and each artboard is also written to <name>_<artboard>.eps beside it, holding that artboard; selectedOnly is refused; its PostScript appearance flattens transparency, as EPS requires. Without a path it writes the document's own file in its own format: a document opened from or saved as SVG/PDF/EPS saves as that again (warnings name what the format loses). No path known (never saved, converted from an older version, restored by Data Recovery, or another format) → {dataBase64, format, name, folder?, warnings} and the document stays modified. Under automation read roots, a reply leaves out the document's own file outside them when no path is given (files and linked then name the files by their file names), and a suggested folder outside them; an svg or svgz save (a document whose own format is SVG or SVGZ included), and a save whose file carries the native document (vectorcraft, template, eps, ai but a version 7 file, pdf of every artboard with preserveEditing on and useArtboards not false), is refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while the file would name a linked image's file outside them (images: link, preserveEditing, or an image whose pixels the document doesn't hold; a URL is not checked), also by file.saveAs and file.saveCopy. A key that no save format takes, beside the path or in options, and an unknown key inside a PDF option's object or svg, are refused. A terminal filesystem permission/read-only refusal returns READ_ONLY_LOCATION: followed by the reason; recovery-copy failures keep their original error. Non-UI callers never open a save panel",
"{path?, format?: vectorcraft|template|pdf|svg|svgz|ai|eps (default: the path's extension, else the document's own format), options?: {…the format's options, see file.formatOptions; default: as last saved}, svg?: {…SVG options} (an SVG save keeps hidden layers, display:none, unless hiddenLayers is false), …the SVG and PDF options given flat instead (an option given flat or in svg and in options with different values is an error), compress?: bool (native, also in options: gzip; default: the useCompression preference; warnings name an option given flat or in options that the file doesn't read: a legacy .ai reads only its own options, and other .ai files don't read outlineText, hiddenObjects, transparentImages or preserveEditing), version?: 4 (3, 2 or 1: for older VectorCraft versions; 1 and 2 are never compressed), preview?: false (embed a PNG of the first artboard, at most 256 px), precision?: 0..9 (native: round path anchors and handles to this many decimal places, a smaller file; colors, transforms and type stay exact; default: exact, and a later save without it writes exactly again), separateArtboards?: false (native and .ai: also save each artboard of `range` to <name>-<artboard>.<ext> beside the file, holding that artboard and the art touching it; the result's files lists every file written), range?: \"1-3, 5\"|\"all\" (default; with separateArtboards), includeLinked?: false (keep linked files' own pixels, not just their previews; they stay linked), embedProfiles?: true (carry the ICC profiles loaded from files that the document is tagged with; opening the file installs them where missing), pdfCompatible?: true (native: also carry a PDF of every artboard; false omits it) | true for .ai (false: blank pages, only the native document; a .ai file's compress, default true, is its compression.compressText), modified?: Unix seconds|null (the File Info modified date, and created date when there is none, a save to a file stamps; default now, recorded in the journal so a replay matches; null: leave the dates)} → {path, format, bytes, warnings, files?: [path…] (the file and its artboards' files), linked?: [path…] (images an SVG links to)}. Save writes one artboard, except a .ai file and EPS (below): a .ai file is a PDF-compatible file of every artboard carrying the native document (preserveEditing always on; PDF options flat or in options), which document.open restores exactly, on the active artboard (the app's, else the one the document opened on; with editingData: false, the first); separateArtboards writes more files, one per artboard; when one of a save's files may not be written, none is written. EPS takes the options of document.exportEps: by default one file whose bounding box fits the visible art (the first artboard when no art shows), carrying the whole editable document; useArtboards: true (also when artboard, artboards or range names artboards; file.formatOptions then reports it true) makes the chosen artboard the page, drawn with its background color (without Use Artboards, only the first artboard's page when no art shows has its color), and with two or more chosen the file at the path is the central file of the visible art (again the first artboard when none shows) and each artboard is also written to <name>_<artboard>.eps beside it, holding that artboard; selectedOnly is refused; its PostScript appearance flattens transparency, as EPS requires. Without a path it writes the document's own file in its own format: a document opened from or saved as SVG/PDF/EPS saves as that again (warnings name what the format loses). No path known (never saved, converted from an older version, restored by Data Recovery, or another format) → {dataBase64, format, name, folder?, warnings} and the document stays modified. Under automation read roots, a reply leaves out the document's own file outside them when no path is given (files and linked then name the files by their file names), and a suggested folder outside them; an svg or svgz save (a document whose own format is SVG or SVGZ included), and a save whose file carries the native document (vectorcraft, template, eps, ai but a version 7 file, pdf of every artboard with preserveEditing on and useArtboards not false), is refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while the file would name a linked image's file outside them (images: link, preserveEditing, or an image whose pixels the document doesn't hold; a URL is not checked), also by file.saveAs and file.saveCopy. A key that no save format takes, beside the path or in options, and an unknown key inside a PDF option's object or svg, are refused. A terminal filesystem permission/read-only refusal returns READ_ONLY_LOCATION: followed by the reason; recovery-copy failures keep their original error. Non-UI callers never open a save panel",
has_doc,
|s, p| save(s, SaveMode::Save, p)
),
+8 -3
View File
@@ -172,14 +172,19 @@ pub(super) fn drawn<'a>(doc: &'a Document, p: &Value) -> Option<Vec<Cow<'a, Docu
/// What a save of `doc` as SVG (format `label`) with options `p` loses of several artboards: the
/// file is one artboard and reopens as one, unless it carries the native document (Preserve
/// Editing Capabilities).
pub(super) fn lost_artboards_warning(doc: &Document, p: &Value, label: &str) -> Option<String> {
pub(crate) fn lost_artboards_warning(doc: &Document, p: &Value, label: &str) -> Option<String> {
let n = doc.artboards.len();
let preserved = plan(doc, p).is_ok_and(|(opts, ..)| opts.preserve_editing);
(n > 1 && !preserved).then(|| {
(n > 1 && !preserves_editing(doc, p)).then(|| {
format!("{label} keeps 1 of the document's {n} artboards: the file reopens with one. Turn on Preserve Editing Capabilities to keep them all.")
})
}
/// Whether a save of `doc` as SVG with options `p` (flat or nested in `svg`) embeds the native
/// document (Preserve Editing Capabilities), which keeps every artboard.
pub(crate) fn preserves_editing(doc: &Document, p: &Value) -> bool {
plan(doc, p).is_ok_and(|(opts, ..)| opts.preserve_editing)
}
/// The native document Preserve Editing embeds: `doc`, without an Export for Screens `folder`
/// outside the read roots of the request being served (the open document keeps it).
fn native_attachment(doc: &Document) -> Vec<u8> {
@@ -120,6 +120,10 @@ fn palette_exports_take_the_transparency_dither() {
let dithered = file(json!({"transparencyDither": method}));
let [left, right] = opaque_halves(&dithered);
assert!((left - 0.25).abs() < 0.1 && (right - 0.75).abs() < 0.1, "{format} {method}: {left} {right}");
if method == "pattern" {
// The ordered pattern keeps exactly one pixel of each 2x2 cell at 25% and three at 75%.
assert_eq!([left, right], [0.25, 0.75], "{format}");
}
assert_eq!(file(json!({"transparencyDither": method})), dithered, "{format} {method}: the same art gives the same file");
// Without transparency the dither does nothing.
let opaque = file(json!({"transparencyDither": method, "transparency": false}));
+2 -2
View File
@@ -54,8 +54,8 @@ pub(crate) use series::{
capture_label_paragraphs, capture_label_rows, capture_label_styles, capture_label_styles_given, capture_label_text, capture_line_changes,
capture_line_fill_stroke_rows, capture_line_kind_rows, capture_line_paint_writes, capture_line_row_writes, capture_line_rows,
capture_series_object_opacity, capture_series_opacity, capture_series_top_paints, follow_wedge_shades, graph_part_members, is_design_art,
is_graph_line, label_object_opacity_differs, label_rows, labels_in, paint_targets, plain_labels, series_group_marks, series_group_marks_where,
series_groups_among, series_marks_in, series_object_opacity_differs, shown_paint, wedge_shades,
is_graph_line, is_series_group, label_object_opacity_differs, label_rows, labels_in, paint_targets, plain_labels, series_group_marks,
series_group_marks_where, series_groups_among, series_marks_in, series_object_opacity_differs, shown_paint, wedge_shades,
};
#[cfg(test)]
+3 -1
View File
@@ -328,7 +328,9 @@ pub(super) fn column_art(
}
parts.push(Arc::new(d.reid(&crate::cmd::place::transformed(n, by))));
}
Some(Arc::new(Node::group(d.alloc_id(), parts)))
let mut n = Node::group(d.alloc_id(), parts);
n.extras_mut().graph_design_art = true;
Some(Arc::new(n))
};
let mut parts = vec![];
let (mut label, mut sliding) = (fit_affine(frame, rect), None);
+3 -1
View File
@@ -271,7 +271,9 @@ impl Gen<'_> {
/// A copy of design art drawn in a series: a single path gets a group of its own, as painting a series paints the
/// paths directly inside its group and the design keeps its own paint.
fn design_copy(&mut self, n: Arc<Node>) -> Arc<Node> {
if matches!(n.kind, NodeKind::Path { .. }) { Arc::new(Node::group(self.d.alloc_id(), vec![n])) } else { n }
let mut n = if matches!(n.kind, NodeKind::Path { .. }) { Arc::new(Node::group(self.d.alloc_id(), vec![n])) } else { n };
Arc::make_mut(&mut n).extras_mut().graph_design_art = true;
n
}
/// A series group. Empty series are omitted by the caller; the index is stored on the group
/// so later paint edits find the series without counting siblings.
+1 -1
View File
@@ -204,7 +204,7 @@ pub(crate) fn series_group_marks_where(doc: &Document, ids: &[NodeId], stands: i
/// Whether `n` is a graph series group: a child of a graph with one of the graph's series indexes ([`series_members`]).
/// It is looked up through its parent, with no pass over the document: the panels call this while they draw.
fn is_series_group(doc: &Document, n: &Node) -> bool {
pub(crate) fn is_series_group(doc: &Document, n: &Node) -> bool {
let Some(index) = n.extras().series_index.and_then(|i| usize::try_from(i).ok()) else { return false };
let graph = doc.parent_of(n.id).and_then(|parent| doc.node(parent)).and_then(|parent| parent.extras().graph.as_deref());
graph.is_some_and(|spec| index < series_count(spec))
+4 -2
View File
@@ -19,7 +19,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Vector Halftone…",
["Object"],
None,
"{shape?: \"circle\"|\"ellipse\"|\"square\"|\"diamond\"|\"line\" (circle), frequency?: lines per inch 1–300 (20), angle?: deg clockwise (45; 0: level rows of dots; CMYK: the black screen's, cyan −30°, magenta +30°, yellow −45° from it), mode?: \"mono\"|\"cmyk\" (mono), color?: mono dot colour (\"#000000\"; #rrggbbaa and #rgba are refused), invert?: bool (dots for light tones), clip?: true (clip the dots to the art's outline), keepOriginal?: false} the selection as vector halftone dots sized by its tone, a group of one path per screen (CMYK screens multiply), as one undo step → {id, dots, warning? (an image in the art couldn't be decoded, as object.rasterize says)}",
"{shape?: \"circle\"|\"ellipse\"|\"square\"|\"diamond\"|\"line\"|\"euclidean\"|\"elliptical\" (circle; euclidean: round dots that meet corner to corner at 50%, then round holes; elliptical: long dots that join into chains at 40% and on all sides at 60%, then long holes), frequency?: lines per inch 1–300 (20), angle?: deg clockwise (45; 0: level rows of dots; CMYK: the black screen's, cyan −30°, magenta +30°, yellow −45° from it), mode?: \"mono\"|\"cmyk\" (mono), color?: mono dot colour (\"#000000\"; #rrggbbaa and #rgba are refused), invert?: bool (dots for light tones), clip?: true (clip the dots to the art's outline), keepOriginal?: false} the selection as vector halftone dots sized by its tone, a group of one path per screen (CMYK screens multiply), as one undo step → {id, dots, warning? (an image in the art couldn't be decoded, as object.rasterize says)}",
has_selection,
halftone
)]
@@ -28,7 +28,9 @@ pub fn specs() -> Vec<CommandSpec> {
fn halftone(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "object.vectorHalftone";
let shape = match text_param(p, "shape", C)? {
Some(v) => DotShape::parse(v).ok_or_else(|| bad(C, format!("unknown shape `{v}` (circle|ellipse|square|diamond|line)")))?,
Some(v) => {
DotShape::parse(v).ok_or_else(|| bad(C, format!("unknown shape `{v}` (circle|ellipse|square|diamond|line|euclidean|elliptical)")))?
}
None => DotShape::Circle,
};
let frequency = number_or(p, "frequency", 20.0, C)?;
+68 -14
View File
@@ -54,7 +54,7 @@ pub fn specs() -> Vec<CommandSpec> {
"New Document Profiles",
[],
None,
"{} the New Document profiles, one per built-in category of file.newPresets: native documents in the New Document Profiles folder next to the preferences, whose swatches, swatch groups, graphic styles, brushes, symbols, patterns, character and paragraph styles, composite fonts, SVG filters, graph designs, ruler origin and mode, transparency grid, document setup (other than bleed, background and Align New Objects to Pixel Grid), assigned color profiles, Document Raster Effects Settings (other than the resolution) and print settings a new document of that category starts with → {profiles: [{name, customized?: a profile file exists (else the shipped profile, today's defaults, applies), path?; both left out for a request that may not read the folder}], folder?: the folder (none in runs without preferences and on the web)}",
"{} the New Document profiles, one per built-in category of file.newPresets: native documents in the New Document Profiles folder next to the preferences, whose swatches, swatch groups, graphic styles, brushes, symbols, patterns, character and paragraph styles, composite fonts, SVG filters, graph designs, ruler origin and mode, transparency grid, document setup (other than bleed, background and Align New Objects to Pixel Grid), assigned color profiles, Document Raster Effects Settings (other than the resolution) and print settings a new document of that category starts with → {profiles: [{name, customized?: a profile file exists (else the shipped profile, today's defaults, applies), unusable?: why file.new does not read it (a link or a folder: new documents get the defaults, and file.newProfiles.edit refuses it), path?; customized, unusable and path left out for a request that may not read the folder}], folder?: the folder (none in runs without preferences and on the web)}",
always,
list_profiles
),
@@ -63,7 +63,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Edit Profile",
[],
None,
"{name: a built-in category of file.newPresets (not Recent or Saved)} open the category's New Document profile as a document to edit (File › Save keeps the changes for the next file.new); a category without a profile file gets the shipped profile written first; under automation roots it needs write and read access to the file, and an error names the file by its file name outside the read roots → document.open's result",
"{name: a built-in category of file.newPresets (not Recent or Saved)} open the category's New Document profile as a document to edit (File › Save keeps the changes for the next file.new); a category without a profile file gets the shipped profile written first; an error when its file is a link or a folder, which file.new does not read either; under automation roots it needs write and read access to the file, and an error names the file by its file name outside the read roots → document.open's result",
always,
edit_profile
),
@@ -72,7 +72,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Reset Profile",
[],
None,
"{name: a built-in category of file.newPresets (not Recent or Saved)} delete the category's profile file, so the shipped profile (today's defaults) applies again; an open copy of it stays open; under automation roots it needs write access to the file, and an error names the file by its file name outside the read roots → {name, reset: whether a file was deleted}",
"{name: a built-in category of file.newPresets (not Recent or Saved)} delete the category's profile file, so the shipped profile (today's defaults) applies again (a link is removed, not the file it leads to; a folder is not deleted, an error); an open copy of it stays open; under automation roots it needs write access to the file, and an error names the file by its file name outside the read roots → {name, reset: whether a file was deleted}",
always,
reset_profile
),
@@ -996,6 +996,44 @@ pub fn profile_names() -> impl Iterator<Item = &'static str> {
CATEGORIES.iter().map(|c| c.0)
}
/// What is at a New Document profile's file.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ProfileFile {
/// Nothing: the shipped profile applies.
None,
/// A plain file, which `file.new` reads.
Plain,
/// A link or another entry that is not a plain file or a folder: `file.new` does not read it (the
/// new document has the defaults), `file.newProfiles.edit` does not open it and
/// `file.newProfiles.reset` removes it (a link, not what it leads to).
NotPlain,
/// A folder, which `file.new` does not read and `file.newProfiles.edit` does not open either.
/// `file.newProfiles.reset` does not delete a folder.
Folder,
}
impl ProfileFile {
/// Whether the category has a file in place of the shipped profile.
pub fn customized(self) -> bool {
self != Self::None
}
/// Whether `file.newProfiles.reset` removes what is there.
pub fn resettable(self) -> bool {
matches!(self, Self::Plain | Self::NotPlain)
}
}
/// What is at `path`, looked at without following a link.
fn profile_file(path: &std::path::Path) -> ProfileFile {
match std::fs::symlink_metadata(path) {
Ok(m) if crate::store::is_plain(&m) => ProfileFile::Plain,
Ok(m) if m.is_dir() && !crate::store::is_link_entry(&m) => ProfileFile::Folder,
Ok(_) => ProfileFile::NotPlain,
Err(_) => ProfileFile::None,
}
}
/// The profile `v` names (a built-in category, any case).
fn profile_name(v: &Value, cmd: &str) -> Result<&'static str> {
let name = v.as_str().map(str::trim).unwrap_or_default();
@@ -1022,9 +1060,9 @@ impl Session {
Some(self.new_doc_profile_dir()?.join(format!("{name}.{}", vectorcraft_format::EXTENSION)))
}
/// Whether profile `name` has a file, which `file.newProfiles.reset` deletes.
pub fn new_doc_profile_customized(&self, name: &str) -> bool {
self.profile_path(name).is_some_and(|p| p.is_file())
/// What is at profile `name`'s file, looked at without following a link.
pub fn new_doc_profile_file(&self, name: &str) -> ProfileFile {
self.profile_path(name).map_or(ProfileFile::None, |p| profile_file(&p))
}
/// Profile `name`'s document, its file's path and a warning for each color profile the file
@@ -1045,7 +1083,7 @@ impl Session {
match std::fs::symlink_metadata(&path) {
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
// A link is refused: the script's gate does not check where it leads.
Ok(m) if !m.file_type().is_file() => return Err(crate::store::NOT_PLAIN.to_string()),
Ok(m) if !crate::store::is_plain(&m) => return Err(crate::store::NOT_PLAIN.to_string()),
_ => {}
}
crate::file_access::check_read(&file).map_err(denied)?;
@@ -1088,7 +1126,11 @@ fn list_profiles(s: &mut Session, _: &Value) -> Result<Value> {
// A request that may not read the folder learns nothing of its files.
Some(path) => {
if let Some(p) = shown(&path) {
v["customized"] = json!(path.is_file());
let file = profile_file(&path);
v["customized"] = json!(file.customized());
if matches!(file, ProfileFile::NotPlain | ProfileFile::Folder) {
v["unusable"] = json!(crate::store::NOT_PLAIN);
}
v["path"] = json!(p);
}
}
@@ -1121,12 +1163,19 @@ fn edit_profile(s: &mut Session, p: &Value) -> Result<Value> {
let path = file.to_string_lossy().to_string();
// document.open reads it next: a profile it can't open is not written either.
crate::file_access::check_read(&path).map_err(|e| profile_error(e, &path))?;
if !file.exists() {
let bytes = vectorcraft_format::save(&shipped_profile(s, name), false);
file.parent()
.map_or(Ok(()), std::fs::create_dir_all)
.and_then(|()| std::fs::write(&file, bytes))
.map_err(|e| profile_error(format!("{path}: {e}"), &path))?;
match profile_file(&file) {
ProfileFile::Plain => {}
// file.new does not read a link or a folder, so it is not opened as the profile either.
ProfileFile::NotPlain | ProfileFile::Folder => return Err(profile_error(format!("{path}: {}", crate::store::NOT_PLAIN), &path)),
// Made new, so a dangling link put there since is not written through.
ProfileFile::None => {
let bytes = vectorcraft_format::save(&shipped_profile(s, name), false);
file.parent()
.map_or(Ok(()), std::fs::create_dir_all)
.and_then(|()| std::fs::OpenOptions::new().write(true).create_new(true).open(&file))
.and_then(|mut f| std::io::Write::write_all(&mut f, &bytes))
.map_err(|e| profile_error(format!("{path}: {e}"), &path))?;
}
}
s.execute("document.open", &json!({ "path": path }))
}
@@ -1136,9 +1185,14 @@ fn reset_profile(s: &mut Session, p: &Value) -> Result<Value> {
let name = profile_name(p.get("name").unwrap_or(&Value::Null), C)?;
let file = writable_profile(s, name, C)?;
let path = file.to_string_lossy().to_string();
if profile_file(&file) == ProfileFile::Folder {
return Err(profile_error(format!("{path}: a folder, which Reset does not delete"), &path));
}
let reset = match std::fs::remove_file(&file) {
Ok(()) => true,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => false,
// On Windows a link to a folder, or a junction, is removed as a folder; what it leads to stays.
Err(_) if std::fs::symlink_metadata(&file).is_ok_and(|m| crate::store::is_link_entry(&m)) && std::fs::remove_dir(&file).is_ok() => true,
Err(e) => return Err(profile_error(format!("{path}: {e}"), &path)),
};
Ok(json!({ "name": name, "reset": reset }))
+1 -1
View File
@@ -41,5 +41,5 @@ pub(crate) use pixelgrid::{
snap_if_aligned, snap_symbol_art,
};
pub(super) use shape::recut;
pub(crate) use transform::{apply_transform, preview_copies, scaling, transform_node, transform_patterns, transforms_objects};
pub(crate) use transform::{apply_transform, nudge_step, preview_copies, scaling, transform_node, transform_patterns, transforms_objects};
pub use transform::{reflect_axis, scale_factors, shear_tangent};
+1 -1
View File
@@ -79,7 +79,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Nudge",
[],
None,
"{dx: -1|0|1, dy: -1|0|1, big?: bool (×10), copy?: bool, patterns?: bool (Transform Patterns: pattern fills and strokes transform with the objects that move whole; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size), objects?: bool (Transform Objects, as object.move), interpolate?: bool (as path.moveAnchors's; default: prefs interpolateControlPoints)} arrow-key nudge by the keyboard increment (the selected anchors (a selected curved segment bends instead: its anchors stay and its handles keep their directions while its middle moves by the step), else objects, along the x and y axes turned by the constrainAngle preference; else ruler guides, along the page axes)",
"{dx: -1|0|1, dy: -1|0|1, big?: bool (×10), fine?: bool (÷10; with big, one increment), copy?: bool, patterns?: bool (Transform Patterns: pattern fills and strokes transform with the objects that move whole; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size), objects?: bool (Transform Objects, as object.move), interpolate?: bool (as path.moveAnchors's; default: prefs interpolateControlPoints)} arrow-key nudge by the keyboard increment (the selected anchors (a selected curved segment bends instead: its anchors stay and its handles keep their directions while its middle moves by the step), else objects, along the x and y axes turned by the constrainAngle preference; else ruler guides, along the page axes)",
has_selection_or_guides,
nudge
),
+7 -2
View File
@@ -438,11 +438,16 @@ pub(crate) fn along_constrain_angle(dx: f64, dy: f64, deg: f64) -> (f64, f64) {
(v.x, v.y)
}
pub(crate) use vectorcraft_tools::nudge_step;
/// `object.nudge`, the arrow keys: the selected anchors, else the selected objects (and the guides
/// that move with them), else the selected ruler guides move by [`nudge_step`] in the arrow's
/// direction, in one undo step.
pub(super) fn nudge(s: &mut Session, p: &Value) -> Result<Value> {
check_numbers(p, &["dx", "dy"], "object.nudge")?;
check_switches(p, &TRANSFORM_SWITCHES, "object.nudge")?;
check_switches(p, &["big", "interpolate"], "object.nudge")?;
let k = s.prefs.keyboard_increment * if bool_or(p, "big", false) { 10.0 } else { 1.0 };
check_switches(p, &["big", "fine", "interpolate"], "object.nudge")?;
let k = nudge_step(s.prefs.keyboard_increment, bool_or(p, "big", false), bool_or(p, "fine", false));
let (dx, dy) = (f64_or(p, "dx", 0.0) * k, f64_or(p, "dy", 0.0) * k);
// Guides keep to the page's axes; art and anchors move along the constrain angle's.
let (gx, gy) = (dx, dy);
@@ -6,6 +6,8 @@
pub(super) const ALLOWED: &[&str] = &[
"addon.arrange.grid",
"addon.arrange.groupOverlapping",
"addon.arrange.groupRows",
"addon.arrange.markBounds",
"addon.arrange.match",
"addon.arrange.offset",
"addon.arrange.randomizeOpacity",
@@ -30,6 +32,7 @@ pub(super) const ALLOWED: &[&str] = &[
"addon.color.fillToStroke",
"addon.color.filter",
"addon.color.nearestSwatch",
"addon.color.randomFill",
"addon.color.select",
"addon.color.strokeToFill",
"addon.color.swatchLegend",
+17 -4
View File
@@ -149,17 +149,30 @@ pub(crate) fn clip_group(d: &mut Document, path: PathData, rule: FillRule, art:
}
/// Render `nodes` alone over transparency: (premultiplied pixels, width, height).
fn render(doc: &Document, nodes: Vec<Node>, region: Rect, scale: f64, anti_alias: AntiAlias) -> vectorcraft_render::Rendered {
let mut tmp = doc.clone();
fn render(doc: &mut Document, nodes: Vec<Node>, region: Rect, scale: f64, anti_alias: AntiAlias) -> vectorcraft_render::Rendered {
struct RestoreLayers<'a> {
doc: &'a mut Document,
original: Vec<Arc<Node>>,
}
impl Drop for RestoreLayers<'_> {
fn drop(&mut self) {
std::mem::swap(&mut self.doc.layers, &mut self.original);
}
}
let mut layer = Node::layer(NodeId(u64::MAX), "raster", vectorcraft_doc::LayerColor::Preset(0));
if let Some(ch) = layer.children_mut() {
*ch = nodes.into_iter().map(Arc::new).collect();
}
tmp.layers = vec![Arc::new(layer)];
// Keep the same resource tables, including images made by earlier effects, without
// copying them for each render. Restore the original layers even if rendering unwinds.
let original = std::mem::replace(&mut doc.layers, vec![Arc::new(layer)]);
let scoped = RestoreLayers { doc, original };
let mut r = vectorcraft_render::Renderer::new();
r.threads = 0;
// Art Optimized is supersampled, as in exports: shapes meeting edge to edge leave no seam.
r.render_region_with(&tmp, region, scale, &RenderOptions { skip_templates: true, anti_alias, supersample: true, ..Default::default() })
r.render_region_with(scoped.doc, region, scale, &RenderOptions { skip_templates: true, anti_alias, supersample: true, ..Default::default() })
}
/// The note for pixels drawn since [`vectorcraft_render::decode_failures`] stood at `failed`, when
+26 -7
View File
@@ -4,11 +4,11 @@
use serde_json::{Value, json};
use vectorcraft_geom::{Rect, Vec2, rotate_deg};
use super::edit::{copy_above, selected_roots};
use super::edit::selected_roots;
use super::object::group_nodes;
use super::{Affine, CommandSpec, NodeId, Result, Session, bad, check_numbers, check_switches, cmd, has_selection, switch_or};
use crate::EngineError;
use vectorcraft_doc::Scaling;
use vectorcraft_doc::{Node, Scaling};
const CMD: &str = "object.stepAndRepeat";
const MAX_CELLS: usize = 10_000;
@@ -20,7 +20,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Step and Repeat…",
["Object", "Transform"],
None,
"{rows?: n (default 1), columns?: n (default 1), fill?: bool (rows and columns are as many as fit the sheet, ignoring `rows` and `columns`; the first copy goes to the sheet's top-left corner plus `margin`), sheet?: {x, y, width, height} (pt; default the artboard that holds the selection's center, else the first), margin?: pt (fill only, default 0), gap?: pt (between neighbors, both axes), gapX?: pt, gapY?: pt (default `gap`, default 0; measured between the bounds of `cutId`, else of the selection, not between centers), cutId?: id (a selected object whose geometric bounds measure the spacing and the 180° turn; default the selection), rotate?: \"none\"|\"columns\"|\"rows\" (turn every other column or row by 180° about its cell's center, the same clockwise or counter-clockwise; default none), patterns?: bool} copy the selection into a grid of cells, left to right and top to bottom, the first cell being the selection itself (moved to the sheet's corner with fill); copies of pixel-aligned objects stay on the pixel grid, so a fractional gap between them is rounded to it, and gaps of other objects are exact; a selection of several objects is grouped first, so that a cut contour stays with its artwork in every copy; one undo step; the copies are selected → {ids: [id…], rows, columns, count}",
"{rows?: n (default 1), columns?: n (default 1), fill?: bool (rows and columns are as many as fit the sheet, ignoring `rows` and `columns`; the first copy goes to the sheet's top-left corner plus `margin`), sheet?: {x, y, width, height} (pt; default the artboard that holds the selection's center, else the first), margin?: pt (fill only, default 0, not negative), gap?: pt (between neighbors, both axes), gapX?: pt, gapY?: pt (default `gap`, default 0; measured between the bounds of `cutId`, else of the selection, not between centers; a negative gap overlaps neighbors and must be smaller than the width or height it is between), cutId?: id (a selected object whose geometric bounds measure the spacing and the 180° turn; default the selection), rotate?: \"none\"|\"columns\"|\"rows\" (turn every other column or row by 180° about its cell's center, the same clockwise or counter-clockwise; default none), patterns?: bool} copy the selection into a grid of cells, left to right and top to bottom, the first cell being the selection itself (moved to the sheet's corner with fill); copies of pixel-aligned objects stay on the pixel grid, so a fractional gap between them is rounded to it, and gaps of other objects are exact; a selection of several objects is grouped first, so that a cut contour stays with its artwork in every copy; one undo step; the copies are selected → {ids: [id…], rows, columns, count}",
has_selection,
step_and_repeat
)]
@@ -119,6 +119,9 @@ fn step_and_repeat(s: &mut Session, p: &Value) -> Result<Value> {
if !(gx.is_finite() && gy.is_finite() && margin.is_finite()) {
return Err(bad(CMD, "gaps and margin must be finite"));
}
if margin < 0.0 {
return Err(bad(CMD, "`margin` must be 0 or more"));
}
let (rows, cols) = if fill { (1, 1) } else { (count_param(p, "rows")?, count_param(p, "columns")?) };
let sheet = sheet_param(p)?;
let mut roots = selected_roots(s)?;
@@ -148,6 +151,9 @@ fn step_and_repeat(s: &mut Session, p: &Value) -> Result<Value> {
if !(w.is_finite() && h.is_finite()) || w <= 0.0 || h <= 0.0 {
return Err(EngineError::Other("the selection has no area to repeat".into()));
}
if w + gx <= EPS || h + gy <= EPS {
return Err(bad(CMD, "a negative gap must be smaller than the width or height it is between"));
}
let anchor = if fill {
let sheet = sheet.or_else(|| {
let c = d.bounds_of(&roots, false).unwrap_or(b).center();
@@ -180,6 +186,9 @@ fn step_and_repeat(s: &mut Session, p: &Value) -> Result<Value> {
if roots.len() > 1 {
roots = vec![group_nodes(d, &roots)?];
}
// Every copy is made first, and all of them go in with one insertion.
let originals: Vec<(NodeId, Node)> = roots.iter().filter_map(|id| d.node(*id).map(|n| (*id, n.clone()))).collect();
let mut lists: Vec<(NodeId, Vec<Node>)> = originals.iter().map(|(id, _)| (*id, Vec::with_capacity(cells.len()))).collect();
let mut copied: Vec<NodeId> = vec![];
let mut first = Affine::IDENTITY;
for c in &cells {
@@ -188,11 +197,21 @@ fn step_and_repeat(s: &mut Session, p: &Value) -> Result<Value> {
first = m;
continue;
}
let copies = copy_above(d, &roots, |_, _, n| {
for ((_, original), (_, list)) in originals.iter().zip(lists.iter_mut()) {
let mut n = d.reid(original);
n.transform(m, sc);
super::object::keep_pixel_aligned(n, sc);
})?;
copied.extend(copies);
super::object::keep_pixel_aligned(&mut n, sc);
copied.push(n.id);
list.push(n);
}
}
if !copied.is_empty() {
// The copy of the last cell goes directly above its original and the first cell's on top.
for (_, list) in &mut lists {
list.reverse();
}
d.insert_beside(lists, false)?;
super::typecmd::refresh_bounds_of(d, &copied);
}
if first != Affine::IDENTITY {
for id in &roots {
@@ -131,6 +131,46 @@ fn rejects_bad_params_and_a_selection_that_does_not_fit() {
assert!(e.execute(CMD, &json!({})).is_err());
}
#[test]
fn rejects_a_negative_margin_and_gaps_that_fold_the_grid_back() {
let (mut s, _) = setup();
let steps = undo_steps(&s);
assert!(s.execute(CMD, &json!({"fill": true, "margin": -5})).is_err());
assert!(s.execute(CMD, &json!({"rows": 1, "columns": 3, "gapX": -50})).is_err());
assert!(s.execute(CMD, &json!({"rows": 3, "columns": 1, "gapY": -40})).is_err());
assert!(s.execute(CMD, &json!({"fill": true, "gap": -50})).is_err());
assert_eq!(undo_steps(&s), steps, "a refusal records no undo step");
let r = s.execute(CMD, &json!({"rows": 1, "columns": 2, "gapX": -10})).unwrap();
assert_eq!(bounds(&s, r["ids"][1].as_u64().unwrap()), (40.0, 0.0, 90.0, 30.0), "a gap above minus the width overlaps neighbors");
}
#[test]
fn copies_go_in_with_one_walk_of_the_document_whatever_the_count() {
let walks = |columns: u64| {
let (mut s, _) = setup();
for i in 0..50 {
s.execute("shape.rectangle", &json!({"x": 0, "y": 100 + i, "width": 5, "height": 5})).unwrap();
}
let id = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 2, "height": 2})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [id]})).unwrap();
let before = vectorcraft_doc::tree_walks();
let r = s.execute(CMD, &json!({"rows": 1, "columns": columns, "gap": 1})).unwrap();
assert_eq!(r["count"], json!(columns));
vectorcraft_doc::tree_walks() - before
};
assert_eq!(walks(40), walks(2), "the walks of the document do not grow with the number of copies");
}
#[test]
fn the_last_cells_copy_sits_directly_above_the_original() {
let (mut s, id) = setup();
let r = s.execute(CMD, &json!({"rows": 1, "columns": 3, "gap": 1})).unwrap();
let ids: Vec<u64> = r["ids"].as_array().unwrap().iter().map(|i| i.as_u64().unwrap()).collect();
let d = &s.doc().unwrap().doc;
let order: Vec<u64> = d.layers[0].children().unwrap().iter().map(|n| n.id.0).collect();
assert_eq!(order, [id, ids[2], ids[1]]);
}
#[test]
fn fill_ignores_explicit_counts() {
let (mut s, _) = setup();
+12
View File
@@ -589,6 +589,18 @@ fn overflow_note(ids: &[NodeId], left_out: &str) -> Option<String> {
}
}
/// Whether Create Outlines has a text object to convert in the selected roots.
pub fn can_create_outlines(s: &Session) -> bool {
use std::ops::ControlFlow::{Break, Continue};
let Ok(roots) = selected_roots(s) else { return false };
let Some(st) = s.active() else { return false };
roots
.iter()
.filter_map(|id| st.doc.node(*id))
.any(|node| node.try_walk(&mut |child| if matches!(child.kind, NodeKind::Text(_)) { Break(()) } else { Continue(()) }).is_break())
}
/// Text objects among `ids` and their descendants.
fn text_ids(d: &Document, ids: &[NodeId]) -> Vec<NodeId> {
text_ids_where(d, ids, |_| true)
+52 -4
View File
@@ -312,6 +312,9 @@ pub(crate) struct ScriptGate {
/// The paths of the open documents' files, as the documents held them when the person last
/// opened or saved them. A document a script's command opened has none here.
pub(crate) documents: Vec<String>,
/// The real paths of the files the script's `File` objects hold open for writing, which a
/// command does not write: the run's end would write the objects' bytes over them.
pub(crate) held: Vec<PathBuf>,
/// The files the documents link to as the person left them when the run began: readable, not
/// writable.
pub(crate) linked: LinkedFiles,
@@ -373,8 +376,11 @@ impl ScriptGate {
Access::Read => self.read.allows(&real) || self.write.allows(&real),
Access::Write => self.write.allows(&real),
};
// A read-only file is not written over, also where a rename could replace it.
let read_only = matches!(access, Access::Write) && std::fs::metadata(&real).is_ok_and(|m| m.is_file() && m.permissions().readonly());
let held = matches!(access, Access::Write) && self.held.contains(&real);
let linked = matches!(access, Access::Read) && self.linked.has(&real) && !self.read.keeps_out(&real);
scoped || self.documents.iter().any(|d| resolve(d).is_ok_and(|d| d == real)) || linked
!read_only && !held && (scoped || self.documents.iter().any(|d| resolve(d).is_ok_and(|d| d == real)) || linked)
});
if allowed { Ok(()) } else { Err(format!("Script file access denied: {path}")) }
}
@@ -1026,6 +1032,7 @@ mod tests {
read: ScriptScope::of_folder(&base.join(dir)),
write: ScriptScope::default(),
documents: vec![],
held: vec![],
linked: LinkedFiles::default(),
also: None,
};
@@ -1055,6 +1062,7 @@ mod tests {
read: ScriptScope::of_folder(dir),
write: ScriptScope::default(),
documents: vec![],
held: vec![],
linked: LinkedFiles::default(),
also: None,
};
@@ -1083,8 +1091,14 @@ mod tests {
let later = base.join("outside/later.svg");
let linked = ScriptGate::real_files([s(secret.clone()), s(later.clone()), s(base.join("outside"))]);
assert_eq!(linked.files.len(), 1, "a missing file and a folder are left out: {linked:?}");
let gate =
ScriptGate { read: ScriptScope::of_folder(&base.join("in")), write: ScriptScope::default(), documents: vec![], linked, also: None };
let gate = ScriptGate {
read: ScriptScope::of_folder(&base.join("in")),
write: ScriptScope::default(),
documents: vec![],
held: vec![],
linked,
also: None,
};
std::fs::write(&later, "<svg/>").unwrap();
let (read, write) =
(|p: &Path| gate.check(&s(p.to_path_buf()), Access::Read).is_ok(), |p: &Path| gate.check(&s(p.to_path_buf()), Access::Write).is_ok());
@@ -1115,6 +1129,7 @@ mod tests {
read,
write: ScriptScope::default(),
documents: vec![],
held: vec![],
linked: ScriptGate::real_files([s(kept.clone()), s(open.clone())]),
also: None,
};
@@ -1150,6 +1165,7 @@ mod tests {
read: ScriptScope::default(),
write: ScriptScope::default(),
documents: vec![],
held: vec![],
linked: ScriptGate::real_files([doc.clone()]),
also: None,
};
@@ -1171,7 +1187,7 @@ mod tests {
std::fs::write(&other, "<svg/>").unwrap();
std::os::unix::fs::symlink(&secret, &link).unwrap();
let linked = ScriptGate::real_files([s(link.clone())]);
let gate = ScriptGate { read: ScriptScope::default(), write: ScriptScope::default(), documents: vec![], linked, also: None };
let gate = ScriptGate { read: ScriptScope::default(), write: ScriptScope::default(), documents: vec![], held: vec![], linked, also: None };
assert!(gate.check(&s(link.clone()), Access::Read).is_ok() && gate.check(&s(secret.clone()), Access::Read).is_ok());
std::fs::remove_file(&link).unwrap();
std::os::unix::fs::symlink(&other, &link).unwrap();
@@ -1180,6 +1196,38 @@ mod tests {
let _ = std::fs::remove_dir_all(base);
}
#[test]
fn a_script_gate_does_not_write_over_a_read_only_file() {
let (base, _) = folders("gate-read-only");
let out = base.join("out/kept.svg");
std::fs::write(&out, "<svg/>").unwrap();
let gate = ScriptGate {
read: ScriptScope::default(),
write: ScriptScope::of_folder(&base.join("out")),
documents: vec![],
held: vec![],
linked: LinkedFiles::default(),
also: None,
};
let (kept, fresh) = (s(out.clone()), s(base.join("out/new.svg")));
let check = |p: &str| with_script_gate(gate.clone(), || (check_write(p).is_ok(), check_read(p).is_ok()));
// The open document's file is the only grant: no folder scope covers it.
let documents = ScriptGate { write: ScriptScope::default(), documents: vec![kept.clone()], ..gate.clone() };
let document_write = || with_script_gate(documents.clone(), || check_write(&kept).is_ok());
assert_eq!(check(&kept), (true, true));
assert!(document_write(), "an open document's file is written");
let mut perms = std::fs::metadata(&out).unwrap().permissions();
perms.set_readonly(true);
std::fs::set_permissions(&out, perms.clone()).unwrap();
assert_eq!(check(&kept), (false, true), "a read-only file is read but not written");
assert!(check(&fresh).0, "a new file next to it is written");
assert!(!document_write(), "also when it is an open document's file");
#[allow(clippy::permissions_set_readonly_false)]
perms.set_readonly(false);
std::fs::set_permissions(&out, perms).unwrap();
let _ = std::fs::remove_dir_all(base);
}
#[test]
fn network_paths_are_told_by_name() {
for p in [r"\\server\share\x.svg", "//server/share/x.svg", r"\\?\UNC\server\share\x.svg", r"\\?\unc\server\share"] {
+1
View File
@@ -39,6 +39,7 @@ pub use cmd::pathops::{HAIRLINE_SLIVER_WIDTH, HAIRLINE_SLIVER_WIDTH_RANGE, auto_
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;
pub use cmd::typecmd::can_create_outlines;
pub use cmd::{CommandInfo, CommandSpec, command_specs, find_command};
pub use cmd::{EyedropperOptions, PathfinderOptions};
pub use journal::Journal;
+128 -32
View File
@@ -98,6 +98,7 @@ use vectorcraft_js::{
use super::{HISTORY_LOST, Host, Link, Savepoint, command, command_value, current, data_size};
use crate::{DocState, Document, NodeId, NodeKind, Session, WindowView};
mod save_open;
mod tags;
mod text;
mod variables;
@@ -229,6 +230,8 @@ pub(super) struct State {
pub(super) active_artboards: RefCell<Vec<u64>>,
/// Each open document's uid and the index of its active artboard when the run started.
pub(super) boards_at_start: Vec<(u64, usize)>,
/// `app.userInteractionLevel` ([`save_open`]).
save_options: save_open::State,
text: text::TextState,
presets: RefCell<Vec<Vec<(String, Data)>>>,
preset_bytes: Cell<u64>,
@@ -626,10 +629,12 @@ fn item_ref(h: &Host, st: &DocState, id: NodeId) -> Data {
}
/// The ids of a document's page items, topmost first, each group or compound path before the
/// objects in it ([`State`] keeps the lists of the last documents read).
fn page_items(h: &Host, st: &DocState) -> Rc<Vec<NodeId>> {
/// objects in it ([`State`] keeps the lists of the last documents read). Building the list again,
/// after an edit or for another document, counts against the run's host-call allowance as a list
/// of that many objects does ([`list_charge`]).
fn page_items(h: &Host, st: &DocState) -> std::result::Result<Rc<Vec<NodeId>>, HostError> {
if let Some(ids) = kept_items(&h.dom.items.borrow(), st.uid, &st.doc) {
return ids;
return Ok(ids);
}
fn walk(nodes: &[Arc<crate::doc::Node>], out: &mut Vec<NodeId>) {
for n in nodes.iter().rev() {
@@ -647,9 +652,16 @@ fn page_items(h: &Host, st: &DocState) -> Rc<Vec<NodeId>> {
}
let mut ids = Vec::new();
walk(&st.doc.layers, &mut ids);
h.charge_call(list_charge(ids.len()))?;
let ids = Rc::new(ids);
keep_items(&mut h.dom.items.borrow_mut(), (st.uid, st.doc.clone(), ids.clone()));
ids
Ok(ids)
}
/// The bytes a list of `n` objects that a collection builds again counts against the run's
/// host-call allowance, as the selection's list counts them ([`selection_of`]).
pub(super) fn list_charge(n: usize) -> u64 {
16u64.saturating_mul(n as u64)
}
/// The objects directly in the layers and sublayers of a document: what deleting every page item
@@ -979,8 +991,8 @@ fn on_doc_steps<T>(
restored = restore_layer(h, uid, layer.0, &layer.1);
}
}
// The document that was active is active again before any error is given: `f`'s error first,
// then the selection's, then the switch back's.
// The document that was active is active again before any error is given: an error that ends
// the run first, then `f`'s error, then the selection's, then the switch back's.
let back = match active {
Some(a) if switch => command(h, "document.activate", &json!({"index": a})).map(drop),
_ => Ok(()),
@@ -992,12 +1004,35 @@ fn on_doc_steps<T>(
{
st.activated = activated;
}
first_error(r, restored, back)
}
/// [`on_doc`]'s result from `f`'s result `r`, then putting back the selection and the layer
/// (`restored`) and the active document (`back`): an error that ends the run first, since a
/// script could catch `f`'s ordinary error, then the first error in that order.
fn first_error<T>(
r: std::result::Result<T, HostError>,
restored: std::result::Result<(), HostError>,
back: std::result::Result<(), HostError>,
) -> std::result::Result<T, HostError> {
if !r.as_ref().is_err_and(ends_run) {
restored.as_ref().err().into_iter().chain(back.as_ref().err()).find(|e| ends_run(e)).map_or(Ok(()), |e| Err(e.clone()))?;
}
let v = r?;
restored?;
back?;
Ok(v)
}
/// Whether `e` ends the run, so that a script cannot catch it.
fn ends_run(e: &HostError) -> bool {
match e {
HostError::Abort(_) => true,
HostError::Marked { error, .. } => ends_run(error),
_ => false,
}
}
/// 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);
@@ -1091,14 +1126,18 @@ fn app_set_coords(h: &Host, a: &[Data]) -> Answer {
Ok(Data::Undefined)
}
/// A path as `getIsFileOpen` compares it, without a trailing `/`: on Windows, `\` and `/` alike and
/// letters in one case; elsewhere `\` is part of a name and case counts.
/// A path as `getIsFileOpen` compares it. A Windows path (any path on Windows, or one that starts
/// with a drive letter) takes `\` and `/` alike and letters in one case. On other systems `\` is a
/// character of a file name, so `/work/a\b.ai` and `/work/a/b.ai` are different files.
fn path_key(p: &str) -> String {
path_key_on(p, cfg!(windows))
}
/// [`path_key`] for Windows when `windows`, else for macOS and Linux.
/// [`path_key`] treating every path as a Windows path when `windows`, else only one that starts
/// with a drive letter.
pub(crate) fn path_key_on(p: &str, windows: bool) -> String {
let b = p.as_bytes();
let windows = windows || (b.len() >= 2 && b[0].is_ascii_alphabetic() && b[1] == b':');
if windows { p.replace('\\', "/").trim_end_matches('/').to_lowercase() } else { p.trim_end_matches('/').to_string() }
}
@@ -1605,6 +1644,13 @@ fn docs_add_document(h: &Host, a: &[Data]) -> Answer {
})
}
/// `documents.addDocumentNoUI(startupPreset)`: a new document from the New Document profile
/// `startupPreset` names, as `addDocument(startupPreset)` makes it, without the New Document
/// dialog. Arguments after `startupPreset` are ignored.
fn docs_add_document_no_ui(h: &Host, a: &[Data]) -> Answer {
docs_add_document(h, &a[..a.len().min(2)])
}
/// `new DocumentPreset()`: a record of new-document settings with the defaults the help page
/// <https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/> gives; the other settings are
/// left out. The settings stay with the run, which hands the script an object of the
@@ -1683,6 +1729,19 @@ fn preset_of(h: &Host, d: &Data) -> Option<usize> {
(i < h.dom.presets.borrow().len()).then_some(i)
}
/// `DocumentPreset.typename`: a `TypeError` for a preset from an earlier run, as its settings give.
fn preset_typename(h: &Host, a: &[Data]) -> Answer {
preset_of(h, arg(a, 0)).ok_or_else(|| HostError::Type("this is not a DocumentPreset".into()))?;
Ok(text("DocumentPreset"))
}
/// `DocumentPreset.toString()`: `[DocumentPreset]`, or a `TypeError` for a preset from an earlier
/// run.
fn preset_to_string(h: &Host, a: &[Data]) -> Answer {
preset_of(h, arg(a, 0)).ok_or_else(|| HostError::Type("this is not a DocumentPreset".into()))?;
Ok(text("[DocumentPreset]"))
}
/// The enumeration whose values the `DocumentPreset` setting `key` takes, when it takes one.
fn preset_enum(key: &str) -> Option<&'static str> {
Some(match key {
@@ -2166,7 +2225,7 @@ fn items_length(h: &Host, a: &[Data]) -> Answer {
return layers::scoped_length(h, a);
}
let doc = items_doc(h, a)?;
let n = with_doc(h, doc, |_, st| page_items(h, st).len());
let n = with_doc(h, doc, |_, st| page_items(h, st).map(|ids| ids.len()))?;
Ok(num(float(n as u64)))
}
@@ -2222,7 +2281,7 @@ fn items_at(h: &Host, a: &[Data]) -> Answer {
match arg(a, 1) {
Data::String(_) => by_name_or_probe(a, items_by_name(h, a)),
Data::Number(n) => match position(*n) {
Some(i) => Ok(item_at(h, doc, i)),
Some(i) => 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,
@@ -2233,8 +2292,8 @@ fn items_at(h: &Host, a: &[Data]) -> Answer {
}
/// 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 item_at(h: &Host, doc: Doc, i: usize) -> Answer {
with_doc(h, doc, |_, st| Ok(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 {
@@ -2249,7 +2308,7 @@ fn items_by_name(h: &Host, a: &[Data]) -> Answer {
/// 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);
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));
id.map(|id| item_ref(h, st, *id)).ok_or_else(|| HostError::Error(NOT_FOUND.into()))
@@ -2261,7 +2320,7 @@ fn items_index(h: &Host, a: &[Data]) -> Answer {
Data::String(_) => items_by_name(h, a),
Data::Number(n) => {
let doc = items_doc(h, a)?;
match position(*n).map(|i| item_at(h, doc, i)) {
match position(*n).map(|i| item_at(h, doc, i)).transpose()? {
None | Some(Data::Undefined) => Err(HostError::Error(NOT_FOUND.into())),
Some(d) => Ok(d),
}
@@ -2756,8 +2815,9 @@ struct Destination {
/// The object a relative object of `move` or `duplicate` names: a page item or a layer of the
/// same document as `item`. An object may go directly above or below itself: a copy goes there, as
/// `layer.move` puts copies, and a move there leaves the object where it is.
fn destination(h: &Host, item: Item, target: &Data, how: &Data) -> std::result::Result<Destination, HostError> {
/// `layer.move` puts copies, and a move there leaves the object where it is. A copy (`copy`) of a
/// clipping path cannot go below it.
fn destination(h: &Host, item: Item, target: &Data, how: &Data, copy: bool) -> std::result::Result<Destination, HostError> {
let how = placement_of(how)?;
let beside = matches!(how, Placement::Above | Placement::Below);
let handle = handle_of(target, "PageItem").or_else(|| handle_of(target, "Layer"));
@@ -2794,6 +2854,15 @@ fn destination(h: &Host, item: Item, target: &Data, how: &Data) -> std::result::
(parent, Some(target))
}
};
// The clipping path stays at the bottom of its clip group or clipping layer. Moving the
// clipping path below itself leaves it where it is.
if how == Placement::Below
&& (target != item.id || copy)
&& d.node(parent).is_some_and(crate::doc::Node::clips)
&& d.position(target).is_some_and(|(_, i, _)| i == 0)
{
return Err(HostError::Error("an object cannot go below a clipping mask".into()));
}
if !editable(d, parent) {
return Err(HostError::Error("the layer or group is hidden or locked".into()));
}
@@ -2848,7 +2917,7 @@ fn item_move(h: &Host, a: &[Data]) -> Answer {
if matches!(arg(a, 1), Data::Undefined) {
return Err(HostError::Type("move needs a relative object".into()));
}
let to = destination(h, item, arg(a, 1), arg(a, 2))?;
let to = destination(h, item, arg(a, 1), arg(a, 2), false)?;
if to.beside != Some(item.id) {
place(h, item.doc, item.id, &to)?;
}
@@ -2889,7 +2958,7 @@ fn item_duplicate(h: &Host, a: &[Data]) -> Answer {
}
None
}
target => Some(destination(h, item, target, arg(a, 2))?),
target => Some(destination(h, item, target, arg(a, 2), true)?),
};
let id = atomically(h, |h| {
let (_, made) = on_doc(h, item.doc.uid, true, |h| command_value(h, "edit.duplicate", &json!({"ids": [item.id.0]})))?;
@@ -2921,17 +2990,22 @@ fn item_z_order(h: &Host, a: &[Data]) -> Answer {
}
refuse_protected_edit(h, item)?;
selection_ids(h, item.doc, arg(a, 0))?;
let (before, after) = with_doc(h, item.doc, |_, st| {
let at = st.doc.position(item.id);
let count = at.and_then(|(p, ..)| st.doc.children(p).map(Vec::len)).unwrap_or(0);
(at.map(|(_, i, _)| i), count)
// The Arrange commands keep a clipping path at the bottom of its parent and the art below the
// parent's ruler guides, so the item's place is counted among the art above the clipping path.
let (before, floor, art) = with_doc(h, item.doc, |_, st| {
let d = &st.doc;
let at = d.position(item.id);
let parent = at.and_then(|(p, ..)| p);
let floor = usize::from(parent.and_then(|p| d.node(p)).is_some_and(crate::doc::Node::clips));
let art = at.and_then(|(p, ..)| d.children(p)).map_or(0, |c| crate::doc::Node::guide_run_start(c));
(at.map(|(_, i, _)| i), floor, art)
});
let Some(i) = before else { return Err(HostError::Error(STALE_ITEM.into())) };
let top = i + 1 >= after;
let unchanged = match id {
"object.arrange.bringToFront" | "object.arrange.bringForward" => top,
_ => i == 0,
};
let unchanged = i < floor
|| match id {
"object.arrange.bringToFront" | "object.arrange.bringForward" => i + 1 >= art,
_ => i <= floor,
};
if !unchanged {
edit_item(h, item, id, &json!({"ids": [item.id.0]}))?;
}
@@ -3021,7 +3095,7 @@ const ENUMS: &[(&str, &[&str])] = &[
/// holds.
pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), RunError> {
text::install_enums(realm)?;
for (name, members) in ENUMS {
for (name, members) in ENUMS.iter().chain(save_open::ENUMS) {
let items = members.iter().map(|m| (m.to_string(), HostItem::Value(text(format!("{name}.{m}"))))).collect();
realm.define_host_object(name, items)?;
}
@@ -3059,6 +3133,7 @@ fn classes(link: &Link) -> Vec<HostClass> {
]);
application.push(("textFonts".into(), text::app_text_fonts(l), MemberInfo { collection: true, ..typed("TextFonts") }));
application.push(later(l, "Application", "beep"));
application.extend(save_open::application_members(l));
application.extend(super::actions::app_members(l));
let preset = {
let l = link.clone();
@@ -3068,8 +3143,8 @@ fn classes(link: &Link) -> Vec<HostClass> {
new_preset(&h)
});
let mut members = vec![
("typename".to_string(), typename_of("DocumentPreset"), typed("string")),
("toString".to_string(), class_text("DocumentPreset"), returns("string", &[])),
("typename".to_string(), get(link, preset_typename), typed("string")),
("toString".to_string(), method(link, preset_to_string), returns("string", &[])),
];
members.extend(PRESET_FIELDS.iter().map(|k| (k.to_string(), preset_field(link, k), typed(preset_type(k)))));
HostClass { construct: Some(f), ..class("DocumentPreset", None, members, None) }
@@ -3107,6 +3182,7 @@ fn classes(link: &Link) -> Vec<HostClass> {
method(l, docs_add_document),
returns("Document", &[("startupPreset", "string"), ("presetSettings", "DocumentPreset"), ("showOptionsDialog", "boolean")]),
),
("addDocumentNoUI", method(l, docs_add_document_no_ui), returns("Document", &[("startupPreset", "string")])),
("toString", class_text("Documents"), returns("string", &[])),
]),
Some(function(l, docs_at)),
@@ -3136,8 +3212,9 @@ fn classes(link: &Link) -> Vec<HostClass> {
]);
document.extend(defaults::document_members(l));
document.extend(text::styles::doc_members(l));
document.extend(["swatches", "symbols", "saveAs", "close"].into_iter().map(|m| later(l, "Document", m)));
document.extend(["swatches", "symbols"].into_iter().map(|m| later(l, "Document", m)));
document.extend(layers::document_members(l));
document.extend(save_open::document_members(l));
document.extend(variables::document_members(l));
document.push(("tags".into(), get(l, tags::doc_tags), MemberInfo { collection: true, ..typed("Tags") }));
classes.push(class("Document", None, document, None));
@@ -3251,6 +3328,7 @@ fn classes(link: &Link) -> Vec<HostClass> {
classes.extend(colors::classes(l));
classes.extend(text::classes(l));
classes.extend(variables::classes(l));
classes.extend(save_open::classes(l));
classes.extend(tags::classes(l));
classes
}
@@ -3268,6 +3346,24 @@ mod tests {
assert_eq!(done_unless_refused(Err(HostError::Range("too large".into()))), Err(HostError::Range("too large".into())));
}
/// A stop from putting back the selection or the active document is not hidden by the edit's
/// own error, which a script could catch; ordinary errors keep their order.
#[test]
fn an_edit_gives_a_stop_ahead_of_its_own_error() {
let error = |m: &str| HostError::Error(m.into());
let stop = || HostError::Abort("stop".into());
let marked = || HostError::Marked { error: Box::new(stop()), mark: 0 };
assert_eq!(first_error::<()>(Err(error("edit")), Err(stop()), Ok(())), Err(stop()));
assert_eq!(first_error::<()>(Err(error("edit")), Ok(()), Err(stop())), Err(stop()));
assert_eq!(first_error::<()>(Err(error("edit")), Err(error("selection")), Err(marked())), Err(marked()));
assert_eq!(first_error(Ok(1), Ok(()), Err(stop())), Err(stop()));
// The edit's own stop comes first, and with no stop the edit's error does.
assert_eq!(first_error::<()>(Err(HostError::Abort("edit".into())), Err(stop()), Ok(())), Err(HostError::Abort("edit".into())));
assert_eq!(first_error::<()>(Err(error("edit")), Err(error("selection")), Err(error("back"))), Err(error("edit")));
assert_eq!(first_error::<()>(Ok(()), Err(error("selection")), Err(error("back"))), Err(error("selection")));
assert_eq!(first_error(Ok(1), Ok(()), Ok(())), Ok(1));
}
#[test]
fn page_item_lists_are_kept_for_several_documents() {
let docs: Vec<Arc<Document>> = (0..=ITEM_LISTS).map(|_| Arc::new(Document::new(100.0, 100.0))).collect();
+1 -1
View File
@@ -661,7 +661,7 @@ fn art_list(h: &Host, st: &DocState, kind: Kind, container: Option<NodeId>) -> R
}
let ids: Vec<NodeId> = match container {
None => {
let all = page_items(h, st);
let all = page_items(h, st)?;
h.charge_call(all.len() as u64)?;
all.iter().copied().filter(|i| st.doc.node(*i).is_some_and(|n| kind.holds(n))).collect()
}
+25 -16
View File
@@ -17,7 +17,9 @@
//! it, topmost first, and make their paths on top of its contents; a layer or group that is hidden
//! or locked, or that is in a hidden or locked layer or group, throws [`CONTAINER_LOCKED`].
//! - A change to the geometry or paint of a path that is hidden or locked, or that is in a hidden
//! or locked layer or group, throws `Cannot edit` with nothing changed.
//! or locked layer or group, or that is on a locked artboard, throws `Cannot edit` with nothing
//! changed, and `pathItems.removeAll()` deletes nothing when one of the paths is on a locked
//! artboard.
//! - A path in a compound path or compound shape reads that owner's paint, which the paint
//! commands change in its place, and a gradient that `filled = true` gives it is placed on that
//! owner's bounds. A paint or stroke change leaves the paint for new art, the active proxy and
@@ -108,6 +110,18 @@ fn cannot_edit(id: NodeId) -> HostError {
HostError::Error(format!("Cannot edit PathItem {}: it, or a layer or group it is in, is hidden or locked", id.0))
}
/// Refuses a change to the path `id` that is hidden or locked, is in a hidden or locked layer or
/// group ([`cannot_edit`]), or is on a locked artboard, as the PageItem setters refuse one.
fn refuse_path_edit(h: &super::Host, st: &DocState, id: NodeId) -> std::result::Result<(), HostError> {
if !editable(&st.doc, id) {
return Err(cannot_edit(id));
}
if super::on_locked_artboard(h, st, id) {
return Err(HostError::Error(format!("Cannot edit PathItem {}: it is on a locked artboard", id.0)));
}
Ok(())
}
/// The path `d` names, which must still be in its document.
fn path_of(h: &super::Host, d: &Data) -> std::result::Result<Item, HostError> {
let item = item_of(h, d)?;
@@ -252,7 +266,7 @@ fn read_points<T>(h: &super::Host, item: Item, f: impl FnOnce(&[SubPath]) -> T)
/// Changes the subpaths of the path of `item` with `f`. The change waits in [`super::State`] with
/// the path's other point changes until [`flush`] writes them. The first change of a path writes
/// the waiting changes of another path first, and throws `Cannot edit` when the path is hidden or
/// locked, unless it changes nothing. A path that is aligned to the pixel grid, or is in an object
/// locked or is on a locked artboard ([`refuse_path_edit`]), unless it changes nothing. A path that is aligned to the pixel grid, or is in an object
/// that is, is written at once, so that its points read as the grid snaps them.
fn edit_points<T>(h: &super::Host, item: Item, f: impl FnOnce(&mut Vec<SubPath>) -> T) -> std::result::Result<T, HostError> {
edit_points_keeping(h, item, false, f)
@@ -280,15 +294,13 @@ fn edit_points_keeping<T>(
flush(h)?;
let mut subs = read_path(h, item, |_, _, pd| pd.subpaths.clone())?;
let r = f(&mut subs);
let (same, ok, aligned) = read_path(h, item, |st, _, pd| {
let (same, refused, aligned) = read_path(h, item, |st, _, pd| {
let d = &st.doc;
let aligned = d.ancestry(item.id).is_some_and(|a| a.iter().chain([&item.id]).any(|i| d.node(*i).is_some_and(|n| n.extras().pixel_aligned)));
(pd.subpaths == subs, editable(d, item.id), aligned)
(pd.subpaths == subs, refuse_path_edit(h, st, item.id), aligned)
})?;
if !same {
if !ok {
return Err(cannot_edit(item.id));
}
refused?;
*h.dom.pending.borrow_mut() = Some((item, subs));
h.dom.pending_reshaped.set(!counts_kept);
if aligned {
@@ -386,15 +398,12 @@ fn drawing_normally<T>(h: &super::Host, f: impl FnOnce() -> T) -> T {
}
/// Runs `id` with `params` and `ids: [item]` (unless `params` names its `ids`) on the item, which
/// must be one the user could edit.
/// must be one the user could edit ([`refuse_path_edit`]).
/// The paint for new art, the active Fill or Stroke proxy, the last color and gradient and the
/// recent colors, which `paint.setFill`, `paint.setStroke` and `stroke.set` also set, are put
/// back afterwards, so the edit changes only the path.
fn edit_path(h: &super::Host, item: Item, id: &str, mut params: Value) -> std::result::Result<Data, HostError> {
let ok = with_doc(h, item.doc, |_, st| editable(&st.doc, item.id));
if !ok {
return Err(cannot_edit(item.id));
}
with_doc(h, item.doc, |_, st| refuse_path_edit(h, st, item.id))?;
if let Some(o) = params.as_object_mut() {
o.entry("ids").or_insert_with(|| json!([item.id.0]));
}
@@ -445,7 +454,7 @@ fn path_items(h: &super::Host, st: &DocState, container: Option<NodeId>) -> std:
Rc::new(children.iter().rev().filter(|n| is_path(n)).map(|n| n.id).collect())
}
None => {
let all = super::page_items(h, st);
let all = super::page_items(h, st)?;
h.charge_call(all.len() as u64)?;
Rc::new(all.iter().copied().filter(|i| st.doc.node(*i).is_some_and(is_path)).collect())
}
@@ -546,9 +555,9 @@ fn items_index(h: &super::Host, a: &[Data]) -> Answer {
}
/// `pathItems.removeAll()`: deletes every path the collection lists in one command. A hidden or
/// locked path, or one in a hidden or locked layer or group, stops it before anything is deleted.
/// A compound path's `pathItems.removeAll()` leaves the compound path, empty, as `remove()` of its
/// last path does.
/// locked path, one in a hidden or locked layer or group, or one on a locked artboard stops it
/// before anything is deleted, as `PageItems.removeAll()` does. A compound path's
/// `pathItems.removeAll()` leaves the compound path, empty, as `remove()` of its last path does.
fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer {
let (doc, c) = items_scope(h, a)?;
let (ids, refused, on_locked) = with_doc(h, doc, |_, st| {
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -74,7 +74,7 @@ fn each(h: &Host, owner: Owner, mut f: impl FnMut(NodeId, &ObjectTag) -> Control
Ok(())
}),
Owner::Doc(doc) => with_doc(h, doc, |_, st| {
let ids = page_items(h, st);
let ids = page_items(h, st)?;
h.charge_call(ids.len() as u64)?;
for id in ids.iter() {
if let Some(n) = st.doc.node(*id) {
+14 -11
View File
@@ -1233,18 +1233,21 @@ pub(super) fn doc_text_frames(link: &Link) -> HostMember {
}
/// The ids of the document's type objects, topmost first as `pageItems` lists them, kept while the
/// document is unchanged.
fn frame_ids(h: &Host, st: &DocState) -> Rc<Vec<NodeId>> {
/// document is unchanged. Building the list again counts the page items it looks through against
/// the run's host-call allowance.
fn frame_ids(h: &Host, st: &DocState) -> std::result::Result<Rc<Vec<NodeId>>, HostError> {
if let Some((uid, doc, ids)) = &*h.dom.text.list.borrow()
&& *uid == st.uid
&& std::ptr::eq(doc.as_ptr(), Arc::as_ptr(&st.doc))
{
return ids.clone();
return Ok(ids.clone());
}
let ids: Vec<NodeId> = page_items(h, st).iter().copied().filter(|i| text_of(st, *i).is_some()).collect();
let all = page_items(h, st)?;
h.charge_call(all.len() as u64)?;
let ids: Vec<NodeId> = all.iter().copied().filter(|i| text_of(st, *i).is_some()).collect();
let ids = Rc::new(ids);
*h.dom.text.list.borrow_mut() = Some((st.uid, Arc::downgrade(&st.doc), ids.clone()));
ids
Ok(ids)
}
fn frames_doc(h: &Host, a: &[Data]) -> std::result::Result<Doc, HostError> {
@@ -1253,7 +1256,7 @@ fn frames_doc(h: &Host, a: &[Data]) -> std::result::Result<Doc, HostError> {
fn frames_length(h: &Host, a: &[Data]) -> Answer {
let doc = frames_doc(h, a)?;
Ok(num(float(with_doc(h, doc, |_, st| frame_ids(h, st).len()) as u64)))
Ok(num(float(with_doc(h, doc, |_, st| frame_ids(h, st).map(|ids| ids.len()))? as u64)))
}
fn frames_parent(h: &Host, a: &[Data]) -> Answer {
@@ -1265,14 +1268,14 @@ fn frames_at(h: &Host, a: &[Data]) -> Answer {
let doc = frames_doc(h, a)?;
let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) };
let Some(i) = usize_of(*n) else { return Ok(Data::Undefined) };
Ok(with_doc(h, doc, |_, st| frame_ids(h, st).get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id))))
with_doc(h, doc, |_, st| Ok(frame_ids(h, st)?.get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id))))
}
fn frames_by_name(h: &Host, a: &[Data]) -> Answer {
let doc = frames_doc(h, a)?;
let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) };
with_doc(h, doc, |_, st| {
let ids = frame_ids(h, st);
let ids = frame_ids(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()));
id.map(|id| item_ref(h, st, *id)).ok_or_else(|| HostError::Error(NOT_FOUND.into()))
@@ -1364,13 +1367,13 @@ fn frames_path_text(h: &Host, a: &[Data]) -> Answer {
fn frames_remove_all(h: &Host, a: &[Data]) -> Answer {
let doc = frames_doc(h, a)?;
let (ids, refused, on_locked) = with_doc(h, doc, |_, st| {
let ids = frame_ids(h, st);
let ids = frame_ids(h, st)?;
let ok = |id: &NodeId| editable(&st.doc, *id) && st.doc.node(*id).is_some_and(all_editable);
let refused: Vec<u64> = ids.iter().filter(|i| !ok(i)).map(|i| i.0).take(20).collect();
let locks = st.doc.locked_artboards();
let on_locked: Vec<u64> = ids.iter().filter(|i| locks.holds_id(**i)).map(|i| i.0).take(20).collect();
(ids, refused, on_locked)
});
Ok::<_, HostError>((ids, refused, on_locked))
})?;
if !refused.is_empty() {
let list = refused.iter().map(u64::to_string).collect::<Vec<_>>().join(", ");
return Err(HostError::Error(format!("cannot delete hidden or locked type: {list}")));
+1 -1
View File
@@ -633,7 +633,7 @@ fn heads(h: &Host, st: &DocState) -> std::result::Result<Rc<Vec<NodeId>>, HostEr
{
return Ok(ids.clone());
}
let ids = frame_ids(h, st);
let ids = frame_ids(h, st)?;
h.charge_call(ids.len() as u64 + st.doc.text_threads.iter().map(|t| t.len() as u64).sum::<u64>())?;
// A frame listed by an earlier thread belongs to that one, as `story_of` finds it.
let (mut threaded, mut first) = (HashSet::new(), HashSet::new());
+44 -2
View File
@@ -124,6 +124,8 @@ pub(crate) const MASK_TOO_COSTLY: &str = "Script folder mask takes too many step
pub(crate) const NOT_WRITABLE: &str = "Script file is not open for writing";
pub(crate) const UNENCODABLE: &str = "Script file cannot encode the text";
pub(crate) const WRITE_FAILED: &str = "Script file could not be written";
pub(crate) const READ_ONLY: &str = "Script file is read-only";
pub(crate) const OPEN_FOR_WRITING: &str = "Script file is open for writing";
pub(crate) const NOT_EMPTY: &str = "Script folder is not empty";
pub(crate) const NAME_TAKEN: &str = "Script file name is already in use";
pub(crate) const BAD_NAME: &str = "Script file name must be a name without a folder";
@@ -281,6 +283,9 @@ pub(crate) struct Disk {
/// when they were last written to the grants file.
kept: Vec<(std::path::PathBuf, bool, bool)>,
recorded: usize,
/// While set, the gate of a command the script runs leaves out the files of the open documents
/// ([`Disk::gate`]): the command reads and writes only where the script's `File` objects may.
pub(crate) exact: bool,
/// The write bits setting `readonly` cleared from each file in this run, by its device and
/// inode, which a rename keeps, at most [`MAX_ENTRIES`] files: clearing `readonly` gives them back.
#[cfg(unix)]
@@ -334,6 +339,7 @@ impl Disk {
ran_too_much: setup.engine_code.1,
kept: Vec::new(),
recorded: 0,
exact: false,
#[cfg(unix)]
cleared: HashMap::new(),
};
@@ -466,9 +472,12 @@ impl Disk {
/// The gate for a command the script runs: the places it reads and writes now, the files the
/// person gave the open documents, `documents`, and the files it may only read because the documents open when
/// the run began link to them, `linked`.
/// the run began link to them, `linked`, but not the files its `File` objects hold open for writing.
pub(crate) fn gate(&self, documents: Vec<String>, linked: crate::file_access::LinkedFiles) -> crate::file_access::ScriptGate {
crate::file_access::ScriptGate { read: self.scope.clone(), write: self.writes.clone(), documents, linked, also: None }
// A save, export or open of a `File` the script names reads and writes as its `File` would.
let (documents, linked) = if self.exact { (Vec::new(), Default::default()) } else { (documents, linked) };
let held = self.open.values().filter_map(|o| o.target.clone()).collect();
crate::file_access::ScriptGate { read: self.scope.clone(), write: self.writes.clone(), documents, held, linked, also: None }
}
/// The files written since this was last asked, to name in the report.
@@ -687,6 +696,39 @@ impl Disk {
}
}
/// The real path a save or export of the document to `path` writes, as a `File` opened for
/// writing would write it ([`Disk::target`]), or why it may not: a folder is not a file, a
/// read-only file is not written over, and neither is a file a `File` object holds open for
/// writing, whose bytes the run's end would write over the saved file.
pub(crate) fn save_target(&self, path: &str) -> Result<std::path::PathBuf, &'static str> {
let real = self.target(path, true)?;
if self.open.values().any(|o| o.target.as_deref() == Some(real.as_path())) {
return Err(OPEN_FOR_WRITING);
}
match std::fs::metadata(&real) {
Ok(m) if !m.is_file() => Err(NOT_REGULAR),
Ok(m) if m.permissions().readonly() => Err(READ_ONLY),
_ => Ok(real),
}
}
/// The real path of the file `path` that opening it as a document reads, as a `File` reads it
/// ([`ScriptScope::locate`]), or why it may not: it is not there, it is not a regular file, or
/// the script may not read it.
pub(crate) fn open_target(&self, path: &str) -> Result<std::path::PathBuf, &'static str> {
let p = self.checked(path)?;
let real = match self.scope.locate(p) {
Ok(real) => real,
Err(ScriptRead::Missing) => return Err(NOT_FOUND),
Err(ScriptRead::Refused | ScriptRead::TooLarge) => return Err(ACCESS_DENIED),
Err(ScriptRead::Failed(_)) => return Err(READ_FAILED),
};
if !real.is_file() {
return Err(NOT_REGULAR);
}
Ok(real)
}
/// Counts `n` more bytes written in the run, which ends past [`MAX_RUN_BYTES`].
fn charge_write(&mut self, n: usize) -> Result<(), HostError> {
self.written = self.written.saturating_add(n);
+12
View File
@@ -222,6 +222,18 @@ fn read_past_cap(path: &Path, max: u64) -> std::io::Result<Vec<u8>> {
/// What [`read_capped_plain`] tells a path that is not a plain file.
pub(crate) const NOT_PLAIN: &str = "not a plain file";
/// Whether `m`, read without following a link, is a plain file: not a link, a folder or (on Windows)
/// a junction or other reparse point.
pub(crate) fn is_plain(m: &std::fs::Metadata) -> bool {
m.file_type().is_file() && !reparse_point(m)
}
/// Whether `m`, read without following a link, is a link (on Windows also a junction or other
/// reparse point).
pub(crate) fn is_link_entry(m: &std::fs::Metadata) -> bool {
m.file_type().is_symlink() || reparse_point(m)
}
/// The content of `path` when it is a plain file of at most `max` bytes. The file is opened without
/// following a link at `path` (on Windows a junction or other reparse point is opened itself), and
/// its kind and bytes are read from that open file, so a link put at `path` after an earlier check
+2
View File
@@ -191,6 +191,7 @@ mod script_include;
mod script_io;
mod script_modules;
mod script_run;
mod script_save_open;
mod script_scriptui;
mod script_styles;
mod script_tags;
@@ -1516,6 +1517,7 @@ fn a_boolean_given_as_text_for_a_transform_is_an_error() {
("object.move", json!({"dx": 5, "copy": "true"}), "copy"),
("object.move", json!({"dx": 5, "objects": 0}), "objects"),
("object.nudge", json!({"dx": 1, "big": "true"}), "big"),
("object.nudge", json!({"dx": 1, "fine": "true"}), "fine"),
("object.rotate", json!({"angle": 45, "absolute": "true"}), "absolute"),
("object.scale", json!({"sx": 200, "strokes": "false"}), "strokes"),
("object.scale", json!({"sx": 200, "corners": [true]}), "corners"),
+10 -14
View File
@@ -835,9 +835,10 @@ fn perspective_grid_commands_refuse_a_boolean_given_as_text() {
/// For an object in perspective, Move in Perspective by 0 (along its plane or its normal),
/// Transform in Perspective by the identity, Transform Again after each, and a Perspective Selection
/// drag that ends where it started record no undo step. So do a Move by 0 and a 1 pt Nudge that
/// Snap to Grid takes back to the gridlines the object's edges are on, and Transform Again after
/// each. With Copy, the identity copies the object in one undo step.
/// drag that ends where it started record no undo step. So do a Move by 0 of an object Snap to Grid
/// keeps on the gridlines its edges are on, and Transform Again after it. With Copy, the identity
/// copies the object in one undo step. (A Nudge in Perspective isn't snapped: it moves by its step,
/// see `arrow_keys_nudge_in_perspective_by_the_step_with_snap_to_grid`.)
#[test]
fn perspective_moves_that_move_nothing_record_no_undo_step() {
let mut s = session();
@@ -869,8 +870,8 @@ fn perspective_moves_that_move_nothing_record_no_undo_step() {
assert_eq!(s.journal.last().unwrap().0, "perspective.move");
let (undo, redo, _) = history(&s);
assert_eq!(((undo, redo), path(&s, a)), ((before.0, before.1), shape.clone()), "a drag back to its start");
// Snap to Grid takes a move that ends 0.3 pt past a gridline crossing onto the crossing. Then it
// takes a move by 0 and a 1 pt nudge back there, and Transform Again after each moves nothing.
// Snap to Grid takes a move that ends 0.3 pt past a gridline crossing onto the crossing. Then a
// move by 0 there, and Transform Again after it, moves nothing.
s.execute("perspective.grid.snap", &json!({"on": true})).unwrap();
let g = grid(&s);
let (_, _, b) = g.plane_bounds(&s.doc().unwrap().doc, &[a]).unwrap();
@@ -881,12 +882,7 @@ fn perspective_moves_that_move_nothing_record_no_undo_step() {
with_a_step_to_redo(&mut s);
let before = history(&s);
let on_grid = path(&s, a);
let calls = [
("perspective.move", json!({"from": [to.x, to.y], "to": [to.x, to.y]})),
("object.transformAgain", json!({})),
("perspective.nudge", json!({"dx": 1, "dy": 0})),
("object.transformAgain", json!({})),
];
let calls = [("perspective.move", json!({"from": [to.x, to.y], "to": [to.x, to.y]})), ("object.transformAgain", json!({}))];
for (c, p) in calls {
assert_eq!(s.execute(c, &p).unwrap(), json!({"ids": [a.0]}), "{c} {p}");
assert_eq!((history(&s), path(&s, a)), (before, on_grid.clone()), "{c} {p}");
@@ -898,7 +894,7 @@ fn perspective_moves_that_move_nothing_record_no_undo_step() {
}
/// Move in Perspective refuses a `copy`, `perpendicular` or `snap`, Transform in Perspective a `copy`,
/// and Nudge in Perspective a `big` or `copy`, given as text or as another value that is not true or
/// and Nudge in Perspective a `big`, `fine` or `copy`, given as text or as another value that is not true or
/// false: the object stays where it is, nothing is copied, and the undo history stays as it was. Null
/// is read as the key left out.
#[test]
@@ -916,7 +912,7 @@ fn perspective_moves_refuse_a_boolean_given_as_text() {
refuses_non_boolean(&mut s, "perspective.move", &json!({"from": from, "to": to, key: v}), key);
}
refuses_non_boolean(&mut s, "perspective.transform", &json!({"matrix": [1.5, 0, 0, 1.5, 0, 0], "copy": v}), "copy");
for key in ["big", "copy"] {
for key in ["big", "fine", "copy"] {
refuses_non_boolean(&mut s, "perspective.nudge", &json!({"dx": 1, "dy": 0, key: v}), key);
}
assert_eq!(state(&s), before, "{v}");
@@ -924,7 +920,7 @@ fn perspective_moves_refuse_a_boolean_given_as_text() {
let calls = [
("perspective.move", json!({"from": from, "to": to, "copy": null, "perpendicular": null, "snap": null})),
("perspective.transform", json!({"matrix": [1.5, 0, 0, 1.5, 0, 0], "copy": null})),
("perspective.nudge", json!({"dx": 1, "dy": 0, "big": null, "copy": null})),
("perspective.nudge", json!({"dx": 1, "dy": 0, "big": null, "fine": null, "copy": null})),
];
for (i, (c, p)) in calls.into_iter().enumerate() {
assert_eq!(s.execute(c, &p).unwrap(), json!({"ids": [a.0]}), "{c} {p}");
@@ -523,6 +523,7 @@ fn ids_null_takes_the_selection_in_every_command_that_falls_back_to_it() {
("addon.cleanup.deepUngroup", json!({}), rect),
("addon.cleanup.rejoin", json!({}), rect),
("addon.color.nearestSwatch", json!({}), rect),
("addon.color.randomFill", json!({"seed": 1}), rect),
("addon.pathtools.cornerSet", json!({"radius": 2}), rect),
("addon.pathtools.cornerRemove", json!({}), rect),
("addon.pathtools.shape.convert", json!({}), rect),
+1 -1
View File
@@ -435,7 +435,7 @@ fn alt_drag_of_30000_objects_takes_few_tree_walks() {
assert_eq!(s.doc().unwrap().history.undo.last().map(|e| e.label.as_str()), Some("Copy"));
// The squares stay; their copies move together.
let moved = bounds(&s, copies[0]).origin() - square_at(0).origin();
assert!(moved.x > 0.0, "{moved:?}");
assert!((moved.x - 80.0).abs() < 1e-6 && moved.y.abs() < 1e-6, "the copies move by the drag: {moved:?}");
for (k, (id, copy)) in ids.iter().zip(&copies).enumerate() {
assert_eq!(bounds(&s, *id), square_at(k));
assert_eq!(bounds(&s, *copy), square_at(k) + moved);
+83 -32
View File
@@ -647,13 +647,14 @@ fn rearrange_refuses_bad_indices_and_at() {
assert_eq!((r["indices"].clone(), boards(&s)[2]), (json!([2]), Rect::new(0.0, 500.0, 100.0, 550.0)));
}
/// A session whose New Document profiles are in a fresh folder for test `name` (not made yet).
fn with_profiles(name: &str) -> (Session, std::path::PathBuf) {
let dir = std::env::temp_dir().join(format!("vc-newdoc-profiles-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
/// A session whose New Document profiles are in a fresh folder for test `name` (not made yet),
/// inside the returned temporary folder, which is removed when dropped, also when the test fails.
fn with_profiles(name: &str) -> (Session, std::path::PathBuf, vectorcraft_testkit::TempDir) {
let root = vectorcraft_testkit::TempDir::new(&format!("newdoc-profiles-{name}"));
let dir = root.join(format!("vc-newdoc-profiles-{name}"));
let mut s = Session::new();
s.attach_new_doc_profiles(dir.clone());
(s, dir)
(s, dir, root)
}
fn swatch_names(s: &Session) -> Vec<String> {
@@ -721,7 +722,7 @@ fn edit_print_profile(s: &mut Session, dir: &std::path::Path) {
#[test]
fn an_edited_profile_starts_the_documents_of_its_category() {
let (mut s, dir) = with_profiles("edited");
let (mut s, dir, _root) = with_profiles("edited");
let listed = s.execute("file.newProfiles", &json!({})).unwrap();
let names: Vec<&str> = listed["profiles"].as_array().unwrap().iter().map(|p| p["name"].as_str().unwrap()).collect();
assert_eq!(names, ["Mobile", "Web", "Print", "Film & Video", "Art & Illustration", "Branding", "Social"]);
@@ -749,7 +750,6 @@ fn an_edited_profile_starts_the_documents_of_its_category() {
s.execute("file.new", &json!({"preset": "A4", "colorMode": "rgb"})).unwrap();
let red = s.doc().unwrap().doc.swatches.iter().find(|w| w.name == "Brand Red").cloned().expect("converted, not dropped");
assert!(matches!(red.paint, vectorcraft_color::Paint::Solid { color: vectorcraft_color::Color::Rgb { .. }, .. }), "{:?}", red.paint);
let _ = std::fs::remove_dir_all(&dir);
}
/// The fill, stroke and weight of `id` in the active document.
@@ -761,7 +761,7 @@ fn look(s: &Session, id: u64) -> (vectorcraft_color::Paint, vectorcraft_color::P
#[test]
fn a_redefined_default_graphic_style_in_a_profile_is_the_default_fill_and_stroke() {
use vectorcraft_color::Paint;
let (mut s, dir) = with_profiles("default-style");
let (mut s, _, _root) = with_profiles("default-style");
// The Print profile's Default Graphic Style becomes no fill and a 0.25 pt red stroke.
s.execute("file.newProfiles.edit", &json!({"name": "Print"})).unwrap();
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap();
@@ -812,12 +812,11 @@ fn a_redefined_default_graphic_style_in_a_profile_is_the_default_fill_and_stroke
assert_eq!(s.paint.fill, green);
s.execute("paint.default", &json!({})).unwrap();
assert_eq!(s.paint, vectorcraft_tools::PaintDefaults::default());
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn the_profile_follows_the_preset_access_and_reset() {
let (mut s, dir) = with_profiles("choice");
let (mut s, dir, _root) = with_profiles("choice");
edit_print_profile(&mut s, &dir);
// A request that may not read the folder gets the defaults, and the reason; edit is refused
// before anything is written.
@@ -857,7 +856,6 @@ fn the_profile_follows_the_preset_access_and_reset() {
assert_eq!(s.execute("file.newProfiles.reset", &json!({"name": "Print"})).unwrap(), json!({"name": "Print", "reset": false}));
let r = s.execute("file.new", &json!({"preset": "A4"})).unwrap();
assert!(r.get("profile").is_none() && !swatch_names(&s).contains(&"Brand Red".to_string()), "{r}");
let _ = std::fs::remove_dir_all(&dir);
}
/// The first run's style of text object `id`.
@@ -869,7 +867,7 @@ fn first_run(s: &Session, id: &Value) -> vectorcraft_doc::CharStyle {
#[test]
fn a_profiles_normal_character_style_is_the_default_font() {
let (mut s, dir) = with_profiles("default-font");
let (mut s, _, _root) = with_profiles("default-font");
// The Print profile's [Normal Character Style] becomes Source Serif 4 Regular at 9 pt.
s.execute("file.newProfiles.edit", &json!({"name": "Print"})).unwrap();
let attrs = json!({"font_family": "Source Serif 4", "font_style": "Regular", "size": 9, "charAlign": "emBoxBottom"});
@@ -907,13 +905,12 @@ fn a_profiles_normal_character_style_is_the_default_font() {
let st = first_run(&s, &made["id"]);
let default = vectorcraft_doc::CharStyle::default();
assert_eq!((st.font_family, st.size), (default.font_family, default.size));
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn an_open_document_takes_another_profiles_default_fill_stroke_and_font() {
use vectorcraft_color::Paint;
let (mut s, dir) = with_profiles("apply-defaults");
let (mut s, _, _root) = with_profiles("apply-defaults");
const GLOW: &str = r#"<filter id="Glow7653"><feOffset dx="3" dy="3"/></filter>"#;
// The CMYK Print profile: no fill and a 0.25 pt stroke of the global swatch Laser Red, with
// the SVG filter Glow7653, and red type in Source Serif 4 at 9 pt.
@@ -1003,7 +1000,6 @@ fn an_open_document_takes_another_profiles_default_fill_stroke_and_font() {
assert!(s.execute("file.newProfiles.applyDefaults", &json!({"name": "Posters"})).is_err());
assert!(s.execute("file.newProfiles.applyDefaults", &json!({})).is_err());
assert_eq!(s.doc().unwrap().history.step(), step);
let _ = std::fs::remove_dir_all(&dir);
}
/// With New Art Has Basic Appearance off, the selected object's look does not replace the profile's
@@ -1011,7 +1007,7 @@ fn an_open_document_takes_another_profiles_default_fill_stroke_and_font() {
#[test]
fn profile_defaults_stay_with_an_unrelated_object_selected() {
use vectorcraft_color::Paint;
let (mut s, dir) = with_profiles("apply-defaults-selected");
let (mut s, _, _root) = with_profiles("apply-defaults-selected");
s.execute("file.newProfiles.edit", &json!({"name": "Print"})).unwrap();
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap();
s.execute("paint.setFill", &json!({"none": true})).unwrap();
@@ -1029,7 +1025,6 @@ fn profile_defaults_stay_with_an_unrelated_object_selected() {
assert_eq!((s.paint.fill.clone(), s.paint.stroke_width), (Paint::None, 0.25));
let id = s.execute("shape.rectangle", &json!({"x": 60, "y": 80, "width": 30, "height": 30})).unwrap()["id"].as_u64().unwrap();
assert_eq!((look(&s, id).0, look(&s, id).2), (Paint::None, Some(0.25)));
let _ = std::fs::remove_dir_all(&dir);
}
/// A profile whose [Normal Character Style] is set in one of its composite fonts gives the open
@@ -1042,7 +1037,7 @@ fn profile_defaults_bring_the_composite_font_of_the_default_font() {
"roman": {"font": "JetBrains Mono", "size": roman},
}})
};
let (mut s, dir) = with_profiles("apply-defaults-composite");
let (mut s, _, _root) = with_profiles("apply-defaults-composite");
s.execute("file.newProfiles.edit", &json!({"name": "Print"})).unwrap();
s.execute("type.compositeFonts.set", &json!({"fonts": [font(50.0)]})).unwrap();
let t = s.execute("text.create", &json!({"x": 10, "y": 80, "text": "Ab", "font": "CF Profile 7653", "size": 12})).unwrap();
@@ -1068,12 +1063,11 @@ fn profile_defaults_bring_the_composite_font_of_the_default_font() {
s.execute("edit.undo", &json!({})).unwrap();
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(profile(&s), Some(100.0));
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn profile_errors_name_the_file_by_its_name_outside_the_read_roots() {
let (mut s, dir) = with_profiles("errors");
let (mut s, dir, _root) = with_profiles("errors");
let elsewhere = dir.with_extension("elsewhere");
std::fs::create_dir_all(&dir).unwrap();
std::fs::create_dir_all(&elsewhere).unwrap();
@@ -1100,22 +1094,19 @@ fn profile_errors_name_the_file_by_its_name_outside_the_read_roots() {
let inside = crate::file_access::AutomationRoots::new(&[dir.as_path()], &[dir.as_path()]).unwrap().unwrap();
let e = run(&mut s, &inside, "file.newProfiles.reset");
assert!(e.starts_with(&format!("{whole}: ")), "{e}");
let _ = std::fs::remove_dir_all(&elsewhere);
let _ = std::fs::remove_dir_all(&dir);
}
/// The new document's links find their files from the profile's file, as a document opened from
/// that file does; a document without a profile has no such file.
#[test]
fn the_new_document_links_from_the_profile_file() {
let (mut s, dir) = with_profiles("links");
let (mut s, dir, _root) = with_profiles("links");
edit_print_profile(&mut s, &dir);
assert_eq!(s.execute("file.new", &json!({"preset": "A4"})).unwrap()["profile"], "Print");
let file = dir.join("Print.vectorcraft").to_string_lossy().to_string();
assert_eq!(s.doc().unwrap().links_from.as_deref(), Some(file.as_str()));
s.execute("file.new", &json!({"preset": "Web 1920×1080"})).unwrap();
assert_eq!(s.doc().unwrap().links_from, None);
let _ = std::fs::remove_dir_all(&dir);
}
/// A color profile the profile's file carries is installed when this machine lacks it, as opening
@@ -1127,7 +1118,7 @@ fn a_profile_brings_the_color_profile_its_file_carries() {
return;
}
use vectorcraft_color::cms;
let (mut s, dir) = with_profiles("icc");
let (mut s, dir, _root) = with_profiles("icc");
let builtin = cms::profiles().into_iter().find(|p| p.kind == cms::ProfileKind::Rgb && p.builtin && p.name != cms::SRGB).unwrap();
let icc = cms::icc_bytes(&builtin.name).unwrap().to_vec();
let name = format!("Profile RGB {}", std::process::id());
@@ -1156,12 +1147,11 @@ fn a_profile_brings_the_color_profile_its_file_carries() {
std::fs::write(dir.join("Web.vectorcraft"), serde_json::to_vec(&v).unwrap()).unwrap();
let r = s.execute("file.new", &json!({"preset": "Web 1920×1080"})).unwrap();
assert!(r["profile"] == "Web" && r["warnings"][0].as_str().unwrap_or_default().contains(&broken), "{r}");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_damaged_or_oversized_profile_leaves_the_defaults_and_is_reported() {
let (mut s, dir) = with_profiles("damaged");
let (mut s, dir, _root) = with_profiles("damaged");
s.execute("file.new", &json!({"preset": "Letter", "profile": null})).unwrap();
let defaults = swatch_names(&s);
std::fs::create_dir_all(&dir).unwrap();
@@ -1178,23 +1168,84 @@ fn a_damaged_or_oversized_profile_leaves_the_defaults_and_is_reported() {
let r = s.execute("file.new", &json!({"preset": "Web 1920×1080"})).unwrap();
assert!(r["profileError"]["reason"].as_str().unwrap_or("").contains("larger than"), "{r}");
assert_eq!(s.doc().unwrap().doc.artboards[0].rect.width(), 1920.0);
let _ = std::fs::remove_dir_all(&dir);
}
#[cfg(unix)]
#[test]
fn a_profile_that_is_a_link_is_not_followed() {
let (mut s, dir) = with_profiles("link");
let (mut s, dir, root) = with_profiles("link");
s.execute("file.newProfiles.edit", &json!({"name": "Print"})).unwrap();
// A profile the folder held, moved out and linked back in.
let outside = std::env::temp_dir().join(format!("vc-newdoc-profile-outside-{}.vectorcraft", std::process::id()));
let outside = root.join("outside.vectorcraft");
std::fs::rename(dir.join("Print.vectorcraft"), &outside).unwrap();
std::os::unix::fs::symlink(&outside, dir.join("Print.vectorcraft")).unwrap();
let r = s.execute("file.new", &json!({"preset": "Letter"})).unwrap();
assert_eq!(r["profileError"]["reason"], "not a plain file", "{r}");
assert!(r.get("profile").is_none(), "{r}");
let _ = std::fs::remove_file(&outside);
let _ = std::fs::remove_dir_all(&dir);
}
/// The listing entry of profile `name`.
fn listed_profile(s: &mut Session, name: &str) -> Value {
let listed = s.execute("file.newProfiles", &json!({})).unwrap();
listed["profiles"].as_array().unwrap().iter().find(|p| p["name"] == name).cloned().unwrap()
}
#[cfg(unix)]
#[test]
fn a_linked_profile_is_listed_as_unusable_and_reset_removes_the_link() {
use crate::cmd::newdoc::ProfileFile;
let (mut s, dir, root) = with_profiles("linked-listing");
s.execute("file.newProfiles.edit", &json!({"name": "Print"})).unwrap();
assert_eq!(s.new_doc_profile_file("Print"), ProfileFile::Plain);
assert!(listed_profile(&mut s, "Print").get("unusable").is_none());
let outside = root.join("outside.vectorcraft");
std::fs::rename(dir.join("Print.vectorcraft"), &outside).unwrap();
std::os::unix::fs::symlink(&outside, dir.join("Print.vectorcraft")).unwrap();
// file.new does not read it, so the listing says so, and Edit does not open it.
assert_eq!(s.new_doc_profile_file("Print"), ProfileFile::NotPlain);
assert!(ProfileFile::NotPlain.resettable());
let p = listed_profile(&mut s, "Print");
assert_eq!((&p["customized"], &p["unusable"]), (&json!(true), &json!("not a plain file")), "{p}");
let e = s.execute("file.newProfiles.edit", &json!({"name": "Print"})).unwrap_err().to_string();
assert!(e.contains("not a plain file"), "{e}");
// Reset removes the link and leaves the file it led to.
assert_eq!(s.execute("file.newProfiles.reset", &json!({"name": "Print"})).unwrap()["reset"], true);
assert!(std::fs::symlink_metadata(dir.join("Print.vectorcraft")).is_err() && outside.is_file());
assert_eq!(s.new_doc_profile_file("Print"), ProfileFile::None);
}
#[cfg(unix)]
#[test]
fn a_profile_link_to_nothing_is_listed_and_edit_does_not_write_through_it() {
let (mut s, dir, root) = with_profiles("dangling");
std::fs::create_dir_all(&dir).unwrap();
let outside = root.join("outside.vectorcraft");
std::os::unix::fs::symlink(&outside, dir.join("Web.vectorcraft")).unwrap();
let p = listed_profile(&mut s, "Web");
assert_eq!((&p["customized"], &p["unusable"]), (&json!(true), &json!("not a plain file")), "{p}");
assert!(s.execute("file.newProfiles.edit", &json!({"name": "Web"})).is_err());
assert!(!outside.exists(), "Edit wrote the shipped profile where the link leads");
assert_eq!(s.execute("file.newProfiles.reset", &json!({"name": "Web"})).unwrap()["reset"], true);
}
#[test]
fn a_folder_in_a_profiles_place_is_listed_as_unusable() {
let (mut s, dir, _root) = with_profiles("folder");
std::fs::create_dir_all(dir.join("Mobile.vectorcraft")).unwrap();
let p = listed_profile(&mut s, "Mobile");
assert_eq!((&p["customized"], &p["unusable"]), (&json!(true), &json!("not a plain file")), "{p}");
let e = s.execute("file.newProfiles.edit", &json!({"name": "Mobile"})).unwrap_err().to_string();
assert!(e.contains("not a plain file"), "{e}");
let r = s.execute("file.new", &json!({"profile": "Mobile"})).unwrap();
assert_eq!(r["profileError"]["reason"], "not a plain file", "{r}");
// Reset does not delete a folder, and Manage Profiles turns it off.
let file = s.new_doc_profile_file("Mobile");
assert_eq!(file, crate::cmd::newdoc::ProfileFile::Folder);
assert!(file.customized() && !file.resettable());
let e = s.execute("file.newProfiles.reset", &json!({"name": "Mobile"})).unwrap_err().to_string();
assert!(e.contains("a folder"), "{e}");
assert!(dir.join("Mobile.vectorcraft").is_dir());
}
#[test]
+21
View File
@@ -104,6 +104,27 @@ fn assert_written(what: &str, d: &Document) {
assert!(diff < 0.02 && diff < without / 4.0, "{what}: read back {:.2}% off ({:.2}% without the effects)", diff * 100.0, without * 100.0);
}
#[test]
fn raster_pass_keeps_layers_and_a_previously_generated_image() {
use crate::cmd::rasterfx::effect_image;
let mut d = Document::new(200.0, 200.0);
let art = rect(&mut d, Rect::new(40.0, 40.0, 80.0, 80.0), Color::rgb(1.0, 0.0, 0.0));
let original_layer = Arc::clone(&d.layers[0]);
let first = effect_image(&mut d, &art, None, 1.0).unwrap();
let second = effect_image(&mut d, &first, None, 1.0).unwrap();
assert_eq!(d.layers.len(), 1);
assert!(Arc::ptr_eq(&d.layers[0], &original_layer));
assert_eq!(d.images.len(), 2);
add(&mut d, second);
let rendered = render(&d);
let at = (60 * rendered.width as usize + 60) * 4;
let pixel = &rendered.pixels[at..at + 4];
assert!(pixel[0] > 240 && pixel[1] < 15 && pixel[2] < 15, "the second pass still reads the first pass's image: {pixel:?}");
}
#[test]
fn groups_layers_type_images_and_symbols_keep_their_raster_effects() {
// A group's shadow (one shadow of both members).
+42
View File
@@ -561,6 +561,41 @@ fn transform_again_repeats_a_perspective_scale_and_copies() {
assert!(s.execute("perspective.transform", &json!({"matrix": [1, 0, 0, 1, 0, 0], "depth": f64::MAX})).is_err());
}
/// Snap to Grid (on by default) leaves the arrow keys' step alone: art whose edges are on
/// gridlines moves by the step (a tenth of it with Ctrl/Cmd) in one undo step each, instead of
/// being pulled back onto the gridlines and not moving at all.
#[test]
fn arrow_keys_nudge_in_perspective_by_the_step_with_snap_to_grid() {
let (mut s, id) = persp_session();
s.execute("perspective.grid.snap", &json!({"on": true})).unwrap();
// A move that ends 0.3 pt past a gridline crossing snaps the corner onto it.
let g = grid(&s);
let b = bounds_of(&plane_pts(&s, id, Plane::Right, 0.0));
let past = |v: f64| (v / g.cell).ceil() * g.cell + 0.3 - v;
let (c, dv) = (b.center(), Vec2::new(past(b.x0), past(b.y0)));
let (from, to) = (g.to_page(Plane::Right, c).unwrap(), g.to_page(Plane::Right, c + dv).unwrap());
s.execute("perspective.move", &json!({"from": [from.x, from.y], "to": [to.x, to.y]})).unwrap();
let on_grid = bounds_of(&plane_pts(&s, id, Plane::Right, 0.0));
assert!((on_grid.x0 / g.cell - (on_grid.x0 / g.cell).round()).abs() < 1e-6, "{on_grid:?}");
// The page step measured at the centre of the selection, as `perspective.nudge` measures it.
let page_step = |s: &Session, before: &[Point]| {
let after = plane_pts(s, id, Plane::Right, 0.0);
let h = grid(s).homography(Plane::Right).unwrap();
let c = bounds_of(before).center();
h.apply(c + (after[0] - before[0])).unwrap() - h.apply(c).unwrap()
};
let v = ViewInfo::default();
s.select_tool("perspectiveSelection", v).unwrap();
let k = s.prefs.keyboard_increment;
for (mods, step) in [(Mods::default(), k), (Mods { cmd: true, ..Default::default() }, k / 10.0)] {
let (before, n) = (plane_pts(&s, id, Plane::Right, 0.0), undo_len(&s));
s.tool_key(ToolKey::Right, mods, v).unwrap();
assert_eq!(undo_len(&s), n + 1, "{mods:?}");
let d = page_step(&s, &before);
assert!((d - Vec2::new(step, 0.0)).hypot() < 1e-6, "{mods:?} {d:?}");
}
}
#[test]
fn arrow_keys_nudge_in_perspective() {
let (mut s, id) = persp_session();
@@ -581,6 +616,13 @@ fn arrow_keys_nudge_in_perspective() {
let c = bounds_of(&before).center();
let step = h.apply(c + d).unwrap() - h.apply(c).unwrap();
assert!((step - Vec2::new(s.prefs.keyboard_increment, 0.0)).hypot() < 1e-6, "{step:?}");
// Ctrl/Cmd takes a tenth of a step.
let before = plane_pts(&s, id, Plane::Right, 0.0);
s.tool_key(ToolKey::Right, Mods { cmd: true, ..Default::default() }, v).unwrap();
let after = plane_pts(&s, id, Plane::Right, 0.0);
let c = bounds_of(&before).center();
let step = h.apply(c + (after[0] - before[0])).unwrap() - h.apply(c).unwrap();
assert!((step - Vec2::new(s.prefs.keyboard_increment / 10.0, 0.0)).hypot() < 1e-6, "{step:?}");
// Alt copies; Shift takes ten steps.
s.tool_key(ToolKey::Left, Mods { alt: true, shift: true, ..Default::default() }, v).unwrap();
let copy = *s.doc().unwrap().selection.objects.first().unwrap();
+3 -1
View File
@@ -739,6 +739,8 @@ fn linked_pages_read_the_file_once_and_a_blank_page_keeps_its_crop_box() {
let art = || PdfPage::new(100.0, 50.0, "1 0 0 rg 10 10 20 20 re f");
write(&src, &pdf(&[art(), PdfPage::new(80.0, 40.0, ""), art()], None));
let mut s = Session::new();
// A freed buffer that had the blob's address may have been read before, in another test.
let mark = vectorcraft_pdf::read_mark();
s.execute("document.open", &json!({"path": src, "linkPages": true, "cropTo": "bounding"})).unwrap();
let d = &s.doc().unwrap().doc;
let boards: Vec<Rect> = d.artboards.iter().map(|a| a.rect).collect();
@@ -748,7 +750,7 @@ fn linked_pages_read_the_file_once_and_a_blank_page_keeps_its_crop_box() {
// The pages are read from the one copy every page's blob keeps: a page that read the file
// again would count here.
let blob = d.images.values().next().map(|b| b.bytes.clone()).unwrap();
assert_eq!(vectorcraft_pdf::reads_of(&blob), 0, "the pages are read from the file read once");
assert_eq!(vectorcraft_pdf::reads_of_since(&blob, mark), 0, "the pages are read from the file read once");
}
#[test]
+4 -3
View File
@@ -1545,10 +1545,10 @@ fn kept_art_follows_the_swatches_once_a_replaced_plugin_paints() {
assert_eq!(draw(&s), (WHITE, RED), "without the swatch, the object as it is");
}
/// Whether `px` is within 40 levels of `want` on every channel. A blur leaves the middle of a
/// shape close to its color.
/// Whether `px` is within 2 levels of `want` on every channel. The samples sit well inside their
/// shapes, so a blur changes them only by rounding.
fn near(px: [u8; 4], want: [u8; 4]) -> bool {
px.iter().zip(want).all(|(a, b)| a.abs_diff(b) <= 40)
px.iter().zip(want).all(|(a, b)| a.abs_diff(b) <= 2)
}
/// A kept raster of a blur over a painted effect is made again when a swatch its piece names
@@ -2256,6 +2256,7 @@ fn a_script_loads_no_plugin_from_outside_its_folder_through_a_name_that_is_not_t
read: ScriptScope::of_folder(&inside),
write: ScriptScope::default(),
documents: vec![],
held: vec![],
linked: Default::default(),
also: None,
};
+43
View File
@@ -64,6 +64,49 @@ fn set_and_get_keyboard_increment_drives_nudge() {
assert!((b.x0 - 15.0).abs() < 1e-9);
}
/// Ctrl/Cmd+arrow (`fine`) nudges by a tenth of the keyboard increment, and Shift+Ctrl+arrow
/// (`big` and `fine`) by one increment: art, direct-selected anchors and ruler guides, one undo
/// step per press, and repeated fine nudges add up to whole increments.
#[test]
fn fine_nudge_moves_a_tenth_of_the_keyboard_increment() {
let mut s = Session::new();
s.execute("prefs.set", &json!({"key": "keyboardIncrement", "value": 5})).unwrap();
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
let r = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap();
let id = NodeId(r["id"].as_u64().unwrap());
let x0 = |s: &Session| s.doc().unwrap().doc.node(id).unwrap().geometric_bounds().unwrap().x0;
let undo = |s: &Session| s.doc().unwrap().history.undo.len();
let n = undo(&s);
s.execute("object.nudge", &json!({"dx": 1, "dy": 0, "fine": true})).unwrap();
assert!((x0(&s) - 10.5).abs() < 1e-9, "{}", x0(&s));
assert_eq!(undo(&s), n + 1, "one undo step per press");
s.execute("object.nudge", &json!({"dx": -1, "dy": 0, "big": true, "fine": true})).unwrap();
assert!((x0(&s) - 5.5).abs() < 1e-9, "Shift+Ctrl: one increment, {}", x0(&s));
for _ in 0..10 {
s.execute("object.nudge", &json!({"dx": 1, "dy": 0, "fine": true})).unwrap();
}
assert!((x0(&s) - 10.5).abs() < 1e-9, "ten fine nudges are one increment, {}", x0(&s));
assert_eq!(undo(&s), n + 12);
// Direct-selected anchors.
s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 0]]})).unwrap();
let p0 = |s: &Session| s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().subpaths[0].anchors[0].p;
let before = p0(&s);
s.execute("object.nudge", &json!({"dx": 0, "dy": 1, "fine": true})).unwrap();
let d = p0(&s) - before;
assert!(d.x.abs() < 1e-9 && (d.y - 0.5).abs() < 1e-9, "{d:?}");
// Ruler guides.
s.execute("select.none", &json!({})).unwrap();
s.execute("guide.add", &json!({"vertical": true, "pos": 100})).unwrap();
s.execute("guide.select", &json!({"indexes": [0]})).unwrap();
s.execute("object.nudge", &json!({"dx": 1, "dy": 0, "fine": true})).unwrap();
let pos = s.doc().unwrap().doc.ruler_guides()[0].pos;
assert!((pos - 100.5).abs() < 1e-9, "{pos}");
assert!(s.execute("object.nudge", &json!({"dx": 1, "fine": "true"})).is_err());
}
#[test]
fn set_rejects_out_of_range_and_wrong_types() {
let mut s = Session::new();
+14 -24
View File
@@ -119,33 +119,23 @@ fn mean_diff(a: &Rendered, b: &Rendered) -> f64 {
fn listed_applied_edited_and_undone() {
let (mut s, g) = striped();
let list = s.execute("effect.list", &json!({})).unwrap();
for (id, _) in EFFECTS {
let e = list["catalog"].as_array().unwrap().iter().find(|e| e["id"] == id).unwrap_or_else(|| panic!("{id} listed"));
assert_eq!(e["raster"], json!(true), "{id}");
assert!(e["params"].as_str().unwrap().contains("radius") || id == "blur.radial", "{id}");
}
let menus: Vec<Value> =
EFFECTS.iter().map(|(id, _)| list["catalog"].as_array().unwrap().iter().find(|e| e["id"] == *id).unwrap()["menu"].clone()).collect();
assert_eq!(menus, [json!(["Effect", "Blur"]), json!(["Effect", "Blur"]), json!(["Effect", "Sharpen"])]);
for (group, menu) in [
(ARTISTIC.as_slice(), "Artistic"),
(BRUSH_STROKES.as_slice(), "Brush Strokes"),
(DISTORT.as_slice(), "Distort"),
(PIXELATE.as_slice(), "Pixelate"),
(SKETCH.as_slice(), "Sketch"),
(TEXTURE.as_slice(), "Texture"),
(VIDEO.as_slice(), "Video"),
([("video.ntscColors", "{}")].as_slice(), "Video"),
// A few representative entries, one per kind of submenu, are listed as raster effects.
for (id, menu) in [
("blur.radial", "Blur"),
("sharpen.unsharpMask", "Sharpen"),
("artistic.cutout", "Artistic"),
("sketch.chrome", "Sketch"),
("video.ntscColors", "Video"),
] {
for (id, _) in group {
let e = list["catalog"].as_array().unwrap().iter().find(|e| e["id"] == *id).unwrap_or_else(|| panic!("{id} listed"));
assert_eq!((&e["raster"], &e["menu"]), (&json!(true), &json!(["Effect", menu])), "{id}");
}
let e = list["catalog"].as_array().unwrap().iter().find(|e| e["id"] == id).unwrap_or_else(|| panic!("{id} listed"));
assert_eq!((&e["raster"], &e["menu"]), (&json!(true), &json!(["Effect", menu])), "{id}");
}
assert!(list["catalog"].as_array().unwrap().iter().all(|e| e["id"] != "blur.notAnEffect"));
assert!(s.execute("effect.apply", &json!({"effect": "blur.notAnEffect", "ids": [g]})).is_err());
// Numbers far out of range are stored as given and read clamped; the canvas still draws.
// Radial Blur's Blur Center is refused outside 0 to 1 instead.
let center = |id: &str, k: &str| id == "blur.radial" && matches!(k, "centerX" | "centerY");
for (id, _) in EFFECTS {
for id in ["blur.radial", "sharpen.unsharpMask"] {
let defaults = vectorcraft_render::effects::default_params(id).unwrap();
let junk: serde_json::Map<String, Value> = defaults
.as_object()
@@ -161,11 +151,11 @@ fn listed_applied_edited_and_undone() {
assert!(s.execute("effect.apply", &json!({"effect": "blur.radial", "ids": [g], "params": {"centerX": 1e308}})).is_err());
let _ = render(&s);
let n = s.doc().unwrap().doc.node(NodeId(g)).unwrap().clone();
assert_eq!(n.appearance.effects.len(), 3);
assert_eq!(n.appearance.effects.len(), 2);
assert_eq!(n.appearance.effects[0].params["method"], json!("spin"), "defaults fill the rest");
s.execute("effect.setParams", &json!({"index": 0, "ids": [g], "params": {"method": "zoom"}})).unwrap();
assert_eq!(s.doc().unwrap().doc.node(NodeId(g)).unwrap().appearance.effects[0].params["method"], json!("zoom"));
for _ in 0..4 {
for _ in 0..3 {
s.execute("edit.undo", &json!({})).unwrap();
}
assert!(s.doc().unwrap().doc.node(NodeId(g)).unwrap().appearance.effects.is_empty());
+195 -18
View File
@@ -895,6 +895,87 @@ fn a_path_inside_a_compound_path_is_not_reordered() {
assert_eq!(out, vec![json!([1, 2])]);
}
/// [`doc`] with `a`, `b` and a rectangle `c` on top made into a clip group `g`, clipped by `c`. The
/// page items are `g`, `b`, `a` and `c`, topmost first.
fn clip_group() -> (Session, NodeId, NodeId, NodeId, NodeId) {
let (mut s, a, b) = doc();
let c = rect(&mut s, 0.0, 0.0, 200.0, 200.0);
s.execute("select.set", &json!({"ids": [a.0, b.0, c.0]})).unwrap();
let g = NodeId(s.execute("object.clippingMask.make", &json!({})).unwrap()["id"].as_u64().unwrap());
s.execute("select.none", &json!({})).unwrap();
assert_eq!(children_of(&s, g), [c, a, b], "the clipping path is at the bottom");
(s, g, a, b, c)
}
/// The ids of the children of `id`, bottom first.
fn children_of(s: &Session, id: NodeId) -> Vec<NodeId> {
s.active().unwrap().doc.node(id).unwrap().children().unwrap().iter().map(|n| n.id).collect()
}
#[test]
fn nothing_is_placed_below_a_clipping_path() {
let (mut s, g, a, b, c) = clip_group();
let d = rect(&mut s, 300.0, 10.0, 5.0, 5.0);
s.execute("select.none", &json!({})).unwrap();
let (before, steps) = (format!("{:?}", s.active().unwrap().doc.layers), undo_steps(&s));
// From outside the group, from above the clipping path inside it, a copy, and a copy of the
// clipping path below itself.
let out = log(
&mut s,
"var p = app.activeDocument.pageItems, mask = p[4], out = [];\
var tries = [function () { p[0].move(mask, ElementPlacement.PLACEAFTER); },\
function () { p[3].move(mask, ElementPlacement.PLACEAFTER); },\
function () { p[0].duplicate(mask, ElementPlacement.PLACEAFTER); },\
function () { mask.duplicate(mask, ElementPlacement.PLACEAFTER); }];\
for (var i = 0; i < tries.length; i++) { try { tries[i](); out.push('ran'); } catch (e) { out.push(e.message); } }\
vc.log(out);",
);
let messages = out[0].as_array().cloned().unwrap_or_default();
assert_eq!(messages.len(), 4, "{out:?}");
for m in &messages {
assert!(m.as_str().is_some_and(|m| m.contains("an object cannot go below a clipping mask")), "{out:?}");
}
assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before);
assert_eq!(undo_steps(&s), steps);
// Directly above the clipping path is allowed, and so is moving the clipping path beside itself.
log(&mut s, "var p = app.activeDocument.pageItems; p[0].move(p[4], ElementPlacement.PLACEBEFORE);");
assert_eq!(children_of(&s, g), [c, d, a, b]);
let steps = undo_steps(&s);
log(&mut s, "var p = app.activeDocument.pageItems; p[4].move(p[4], ElementPlacement.PLACEAFTER);");
assert_eq!((children_of(&s, g), undo_steps(&s)), (vec![c, d, a, b], steps));
}
#[test]
fn zorder_that_leaves_an_object_in_place_runs_no_command() {
// The topmost art of a layer with a ruler guide above it.
let (mut s, a, b) = doc();
let layer = s.active().unwrap().doc.layers[0].id;
s.execute("guide.add", &json!({"vertical": true, "pos": 50, "layer": layer.0})).unwrap();
let kids = s.active().unwrap().doc.layers[0].children().unwrap().clone();
assert!(kids.len() == 3 && kids[2].is_ruler_guide(), "the guide is above the art");
let steps = undo_steps(&s);
let r =
run(&mut s, "var p = app.activeDocument.pageItems; p[0].zOrder(ZOrderMethod.BRINGTOFRONT); p[0].zOrder(ZOrderMethod.BRINGFORWARD);").unwrap();
assert_eq!((&r["slowestCommands"], undo_steps(&s)), (&json!([]), steps));
assert_eq!(layer_order(&s)[..2], [a, b]);
// The lowest object above a clipping path, and the clipping path itself.
let (mut s, g, a, b, c) = clip_group();
let steps = undo_steps(&s);
let r = run(
&mut s,
"var p = app.activeDocument.pageItems, ways = [ZOrderMethod.BRINGTOFRONT, ZOrderMethod.BRINGFORWARD,\
ZOrderMethod.SENDBACKWARD, ZOrderMethod.SENDTOBACK];\
p[2].zOrder(ZOrderMethod.SENDBACKWARD); p[2].zOrder(ZOrderMethod.SENDTOBACK);\
for (var k = 0; k < ways.length; k++) p[3].zOrder(ways[k]);",
)
.unwrap();
assert_eq!((&r["slowestCommands"], undo_steps(&s)), (&json!([]), steps));
assert_eq!(children_of(&s, g), [c, a, b]);
// A change still runs the command.
log(&mut s, "app.activeDocument.pageItems[1].zOrder(ZOrderMethod.SENDTOBACK);");
assert_eq!((children_of(&s, g), undo_steps(&s)), (vec![c, b, a], steps + 1));
}
#[test]
fn moving_the_last_path_out_of_a_compound_path_keeps_the_compound_path() {
let (mut s, a, b) = doc();
@@ -970,7 +1051,11 @@ fn clearing_anchors_with_keep_empty_keeps_the_compound_path() {
s.execute("edit.clear", &json!({"keepEmpty": keep})).unwrap();
let d = &s.active().unwrap().doc;
assert!(d.node(a).is_none() && d.node(b).is_none(), "keepEmpty {keep}: both paths are deleted");
assert_eq!(d.node(compound).is_some_and(|n| n.children().is_some_and(|c| c.is_empty())), keep, "keepEmpty {keep}");
if keep {
assert!(d.node(compound).is_some_and(|n| n.children().is_some_and(|c| c.is_empty())), "keepEmpty true keeps it, empty");
} else {
assert!(d.node(compound).is_none(), "keepEmpty false deletes the compound path");
}
}
}
@@ -1002,11 +1087,23 @@ fn a_grid_by_column_takes_the_number_of_rows() {
let distinct = |mut v: Vec<i64>| {
v.sort_unstable();
v.dedup();
v.len()
v
};
let tops = distinct(boards.iter().map(|b| b.rect.y0.round() as i64).collect());
let lefts = distinct(boards.iter().map(|b| b.rect.x0.round() as i64).collect());
assert_eq!((tops, lefts), (rows, cols), "{layout} {count}");
assert_eq!((tops.len(), lefts.len()), (rows, cols), "{layout} {count}");
// Each artboard's row and column, counted from the top and from the left: a grid by column
// fills each column top to bottom, and the right-to-left grid starts at the rightmost column.
let index = |v: &[i64], x: f64| v.iter().position(|&t| t == x.round() as i64);
let placed: Vec<_> = boards.iter().map(|b| (index(&tops, b.rect.y0), index(&lefts, b.rect.x0))).collect();
let expected: Vec<_> = (0..count)
.map(|i| match layout {
"GridByRow" => (Some(i / cols), Some(i % cols)),
"GridByCol" => (Some(i % rows), Some(i / rows)),
_ => (Some(i % rows), Some(cols - 1 - i / rows)),
})
.collect();
assert_eq!(placed, expected, "{layout} {count}");
}
}
@@ -1408,6 +1505,18 @@ fn a_document_preset_is_an_instance_of_its_class() {
assert_eq!(out, vec![json!(true), json!("DocumentPreset"), json!(612)]);
}
/// A preset kept from an earlier run throws from `typename` and `toString()` as it does from its
/// settings.
#[test]
fn a_document_preset_from_an_earlier_run_throws_from_typename_and_to_string() {
let mut s = Session::new();
run(&mut s, "#targetengine keep\nvar p = new DocumentPreset();").unwrap();
for member in ["p.width", "p.typename", "p.toString()", "String(p)"] {
let e = failure(&mut s, &format!("#targetengine keep\n{member};"));
assert!(e.contains("TypeError") && e.contains("not a DocumentPreset"), "{member}: {e}");
}
}
/// The values the presets hold count against the run's heap, a value assigned again in place of
/// the one before it.
#[test]
@@ -1598,6 +1707,23 @@ fn headless_add_document_dialog_fails_without_creating() {
assert_eq!(s.documents().len(), 1);
}
/// `addDocumentNoUI(startupPreset)` makes the document `addDocument(startupPreset)` makes, and
/// ignores the arguments after the preset's name.
#[test]
fn add_document_no_ui_makes_the_startup_presets_document() {
let mut s = Session::new();
let out = log(
&mut s,
"var a = app.documents.addDocument('Web'); var p = new DocumentPreset(); p.width = 333;\
var b = app.documents.addDocumentNoUI('Web', p, true);\
vc.log([b.typename, b.width === a.width, b.height === a.height, b.width === 333, app.documents.length]);",
);
assert_eq!(out, vec![json!(["Document", true, true, false, 2])]);
let e = failure(&mut s, "app.documents.addDocumentNoUI('No Such Preset');");
assert!(e.contains("no startup preset called No Such Preset"), "{e}");
assert_eq!(s.documents().len(), 2);
}
#[test]
fn setting_selected_keeps_how_the_other_objects_are_selected() {
let (mut s, a, b) = doc();
@@ -1637,16 +1763,19 @@ fn add_document_takes_only_a_document_preset() {
#[test]
fn add_document_applies_the_profile_file_and_throws_when_it_cannot_be_read() {
let dir = std::env::temp_dir().join(format!("vc-script-add-document-profile-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let root = vectorcraft_testkit::TempDir::new("script-add-document-profile");
let dir = root.join("profiles");
let mut s = Session::new();
s.attach_new_doc_profiles(dir.clone());
// A profile with no file gives the defaults.
let out = log(&mut s, "vc.log(app.documents.addDocument('Web').typename);");
assert_eq!(out, vec![json!("Document")]);
assert_eq!(s.doc().unwrap().links_from, None);
// A script reads the profile's file in the app's own folder.
// A script reads the profile's file in the app's own folder, with no document open from it.
s.execute("file.newProfiles.edit", &json!({"name": "Print"})).unwrap();
while !s.documents().is_empty() {
s.execute("file.close", &json!({})).unwrap();
}
let file = dir.join("Print.vectorcraft").to_string_lossy().to_string();
log(&mut s, "app.documents.addDocument('Print');");
assert_eq!(s.doc().unwrap().links_from.as_deref(), Some(file.as_str()));
@@ -1673,13 +1802,12 @@ fn add_document_applies_the_profile_file_and_throws_when_it_cannot_be_read() {
// A startup preset with no profile reads no file.
let out = log(&mut s, "vc.log(app.documents.addDocument('Basic RGB').documentColorSpace);");
assert_eq!(out, vec![json!("DocumentColorSpace.RGB")]);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn add_document_names_a_color_profile_of_the_profile_file_that_cannot_be_used() {
let dir = std::env::temp_dir().join(format!("vc-script-add-document-warning-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let root = vectorcraft_testkit::TempDir::new("script-add-document-warning");
let dir = root.join("profiles");
let mut s = Session::new();
s.attach_new_doc_profiles(dir.clone());
s.execute("file.newProfiles.edit", &json!({"name": "Print"})).unwrap();
@@ -1697,7 +1825,6 @@ fn add_document_names_a_color_profile_of_the_profile_file_that_cannot_be_used()
let named = lines.iter().filter_map(Value::as_str).any(|l| l.starts_with("addDocument: ") && l.contains(&broken));
assert!(named, "{lines:?}");
assert_eq!(s.documents().len(), 1);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
@@ -1800,8 +1927,7 @@ fn setters_on_a_stale_item_report_it_before_a_bad_value() {
fn objects_read_before_a_revert_are_stale_and_ones_read_after_are_the_loaded_ones() {
// `pageItems[0]` is the topmost object, the one made last.
let (mut s, _, b) = doc();
let dir = std::env::temp_dir().join(format!("vc-dom-revert-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let dir = vectorcraft_testkit::TempDir::new("dom-revert");
let path = dir.join("saved.vectorcraft");
s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap();
for read in ["i.name", "i.name = 'after'", "app.activeDocument.selection = i", "l.name"] {
@@ -1817,7 +1943,6 @@ fn objects_read_before_a_revert_are_stale_and_ones_read_after_are_the_loaded_one
);
assert_eq!(out, vec![json!(2)]);
assert_eq!(s.active().unwrap().doc.node(b).unwrap().name.as_deref(), Some("loaded"));
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
@@ -2128,6 +2253,21 @@ fn get_is_file_open_cannot_probe_outside_script_scope() {
assert!(failure(&mut s, "app.getIsFileOpen(new Array(5000).join('a'));").contains("too long"));
}
/// Outside Windows a `\` is part of a file name: `<dir>/a\b.svg` is not the open `<dir>/a/b.svg`.
#[test]
fn get_is_file_open_keeps_a_backslash_in_a_unix_file_name() {
let (mut s, _, _) = doc();
let fixture = vectorcraft_testkit::TempDir::new("script-file-open-backslash");
let dir = fixture.join("a");
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("b.svg");
s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap();
let same = serde_json::to_string(&path.to_string_lossy()).unwrap();
let backslash = serde_json::to_string(&format!("{}\\b.svg", dir.to_string_lossy())).unwrap();
let out = log(&mut s, &format!("vc.log(app.getIsFileOpen({same})); vc.log(app.getIsFileOpen({backslash}));"));
assert_eq!(out, vec![json!(true), json!(cfg!(windows))]);
}
#[test]
fn a_menu_command_runs_its_command_on_the_selection() {
let (mut s, a, b) = doc();
@@ -3455,8 +3595,17 @@ fn the_selection_follows_page_items_and_costs_the_same_in_a_large_document() {
assert_eq!(out[0][0].as_array().map(Vec::len), Some(3));
// Each pass edits the document, so nothing kept from the last read can be reused.
let edits = "var d = app.activeDocument; for (var i = 0; i < 50; i++) d.selection[0].opacity = 50 + i % 2;";
// The script's fuel, and the host's calls and the bytes they count, which hold the work the
// host does for them: 64 KiB is less than one list of the large document's objects.
let cost = |s: &mut Session| {
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(1 << 16)));
let r = run(s, edits);
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None));
let r = r.unwrap_or_else(|e| panic!("the reads went over: {e}"));
(r["fuelUsed"].as_u64().unwrap(), r["hostCalls"].as_u64().unwrap())
};
s.execute("select.set", &json!({"ids": [c.0]})).unwrap();
let small = run(&mut s, edits).unwrap()["fuelUsed"].as_u64().unwrap();
let small = cost(&mut s);
// 3 objects doubled 11 times: 6,144.
s.execute("select.all", &json!({})).unwrap();
for _ in 0..11 {
@@ -3464,11 +3613,39 @@ fn the_selection_follows_page_items_and_costs_the_same_in_a_large_document() {
s.execute("select.all", &json!({})).unwrap();
}
s.execute("select.set", &json!({"ids": [c.0]})).unwrap();
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(1 << 16)));
let large = run(&mut s, edits);
assert_eq!(small, cost(&mut s));
}
/// Building a collection's list again after an edit counts the objects it lists against the
/// run's allowance, so a loop that edits and reads `pageItems`, `pathItems` or `textFrames` in a
/// large document ends with the limit instead of walking the document each time for nothing.
#[test]
fn rebuilding_a_collection_after_an_edit_counts_against_the_run() {
let (mut s, a, _) = doc();
let source = |list: &str| {
format!("var d = app.activeDocument, it = d.pageItems[0]; for (var i = 0; i < 40; i++) {{ it.opacity = 50 + i % 2; d.{list}.length; }}")
};
let lists = ["pageItems", "pathItems", "textFrames"];
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(1 << 20)));
let small: Vec<bool> = lists.iter().map(|l| run(&mut s, &source(l)).is_ok()).collect();
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None));
let large = large.unwrap_or_else(|e| panic!("the reads in a large document went over: {e}"))["fuelUsed"].as_u64().unwrap();
assert_eq!(small, large);
assert_eq!(small, vec![true; 3], "a small document stays under 1 MiB");
// 2 objects doubled 11 times: 4,096, a list of 64 KiB each time it is built again.
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
s.execute("select.all", &json!({})).unwrap();
for _ in 0..11 {
s.execute("edit.duplicate", &json!({})).unwrap();
s.execute("select.all", &json!({})).unwrap();
}
// Nothing selected, so putting the selection back after each edit passes no list of ids.
s.execute("select.none", &json!({})).unwrap();
for list in lists {
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(1 << 20)));
let r = run(&mut s, &source(list));
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None));
let e = r.map(|r| panic!("{list}: 40 lists of 4,096 objects stayed under 1 MiB: {r}")).unwrap_err().to_string();
assert!(e.contains("passed more data to and from commands"), "{list}: {e}");
}
}
/// A collection read with a name gives what `getByName` gives, and throws as it does for no match.
@@ -1695,6 +1695,34 @@ fn assigning_guides_refuses_paths_that_cannot_be_selected() {
assert_eq!((is_guide(&s, a), undo_steps(&s)), (true, steps), "the guide stays a guide");
}
#[test]
fn path_changes_refuse_paths_on_a_locked_artboard() {
let (mut s, a, _) = doc();
s.execute("artboard.setProps", &json!({"index": 0, "locked": true})).unwrap();
let (before, steps) = (art(&s), undo_steps(&s));
// Points (waiting and written at once), paint, stroke and a transform.
for change in [
"p.closed = false;",
"p.pathPoints[0].anchor = [1, 2];",
"p.setEntirePath([[0, 0], [10, 10]]);",
"p.filled = false;",
"p.strokeWidth = 7;",
"p.translate(5, 5);",
] {
let e = failure(&mut s, &format!("var p = app.activeDocument.pathItems[0]; {change}"));
assert!(e.contains(&format!("Cannot edit PathItem {}: it is on a locked artboard", a.0)), "{change}: {e}");
}
let e = failure(&mut s, "app.activeDocument.pathItems.removeAll();");
assert!(e.contains("cannot delete objects on a locked artboard"), "{e}");
assert_eq!((art(&s), undo_steps(&s)), (before.clone(), steps));
// A value the path has changes nothing and does not throw, and the path changes once the
// artboard is unlocked.
log(&mut s, "app.activeDocument.pathItems[0].closed = true;");
s.execute("artboard.setProps", &json!({"index": 0, "locked": false})).unwrap();
log(&mut s, "app.activeDocument.pathItems[0].strokeWidth = 7;");
assert_ne!(art(&s), before);
}
fn is_guide(s: &Session, id: NodeId) -> bool {
matches!(node(s, id).kind, NodeKind::Path { guide: true, .. })
}
+16 -35
View File
@@ -88,10 +88,10 @@ fn a_run_is_one_undo_step_in_each_document_it_changed() {
#[test]
fn a_run_that_changes_nothing_leaves_no_step_no_mark_and_no_journal_entry() {
let dir = fresh_folder("noop");
for source in ["", "var a = 1 + 2;", "vc.log(vc.document); vc.commands.length;"] {
let mut s = two_docs();
s.execute("document.save", &json!({"path": std::env::temp_dir().join(format!("vc-noop-{}.svg", std::process::id())).to_string_lossy()}))
.unwrap();
s.execute("document.save", &json!({"path": dir.join("noop.svg").to_string_lossy()})).unwrap();
let before = state(&s);
let revisions = |s: &Session| s.documents().iter().map(|d| d.revision).collect::<Vec<_>>();
let revisions_before = revisions(&s);
@@ -183,6 +183,11 @@ fn failed_script_report_keeps_message_and_adds_origin() {
("throw new RangeError('invalid array length');", "thrown", "RangeError: invalid array length", "script"),
("throw 'invalid array length';", "thrown", "invalid array length", "script"),
("throw 'ReferenceError: BridgeTalk is not defined';", "thrown", "ReferenceError: BridgeTalk is not defined", "script"),
("throw new ReferenceError('BridgeTalk is not defined');", "thrown", "ReferenceError: BridgeTalk is not defined", "script"),
("throw 'ReferenceError: Window is not defined';", "thrown", "ReferenceError: Window is not defined", "script"),
("throw new ReferenceError('Window is not defined');", "thrown", "ReferenceError: Window is not defined", "script"),
("throw 'ReferenceError: activeDocument is not defined';", "thrown", "ReferenceError: activeDocument is not defined", "script"),
("throw new ReferenceError('activeDocument is not defined');", "thrown", "ReferenceError: activeDocument is not defined", "script"),
("try { new Array(-1); } catch (e) { throw new Error(e.message); }", "thrown", "Error: invalid array length", "script"),
("new Array(-1);", "thrown", "RangeError: invalid array length", "built-in"),
("try { new Array(-1); } catch (e) { throw e; }", "thrown", "RangeError: invalid array length", "built-in"),
@@ -266,9 +271,7 @@ fn bad_parameters_are_refused_before_anything_runs() {
#[test]
fn files_are_checked_before_they_are_read() {
let dir = std::env::temp_dir().join(format!("vc-script-run-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let dir = fresh_folder("checked");
let write = |name: &str, bytes: &[u8]| {
let p = dir.join(name);
std::fs::write(&p, bytes).unwrap();
@@ -296,7 +299,6 @@ fn files_are_checked_before_they_are_read() {
assert_eq!(s.execute("script.run", &path(&upper)).unwrap()["log"], json!([3]));
std::fs::create_dir_all(dir.join("folder.js")).unwrap();
assert!(s.execute("script.run", &path(&dir.join("folder.js").to_string_lossy())).is_err());
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
@@ -341,7 +343,6 @@ fn a_js_script_reads_ecmascript_2015_and_a_jsx_script_does_not() {
assert_eq!(kept["log"], json!(["1xy"]), "{kept}");
let e = s.execute("script.run", &path(&write("pattern.jsx", "var [a] = [1];"))).unwrap_err().to_string();
assert!(e.contains("SyntaxError"), "{e}");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
@@ -367,7 +368,6 @@ fn a_js_script_reads_object_literal_extensions_and_function_names_and_a_jsx_scri
assert_eq!(legacy["log"], json!([false]), "{legacy}");
// Script text given without a file keeps the ExtendScript language.
assert!(run(&mut s, "var a = 1; var o = { a };").unwrap_err().to_string().contains("SyntaxError"));
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
@@ -390,7 +390,6 @@ fn a_js_script_reads_optional_chains_and_coalescing_and_a_jsx_script_does_not()
}
// Script text given without a file keeps the ExtendScript language.
assert!(run(&mut s, "vc.log(null ?? 1);").unwrap_err().to_string().contains("SyntaxError"));
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
@@ -417,7 +416,6 @@ fn a_js_script_runs_generators_and_a_jsx_script_does_not_read_them() {
s.execute("script.run", &path(&write("keep.jsx", "#targetengine genkept\nvar a = 1;"))).unwrap();
let e = s.execute("script.run", &path(&write("keep.js", "#targetengine genkept\nfunction* g() {}\ng();"))).unwrap_err().to_string();
assert!(e.contains("TypeError"), "{e}");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
@@ -451,7 +449,6 @@ fn every_script_reads_e4x_and_has_the_xml_objects() {
s.execute("script.run", &path(&write("first.js", "#targetengine xmlkept\nlet k = 1;"))).unwrap();
let later = s.execute("script.run", &path(&write("second.jsx", "#targetengine xmlkept\nvc.log(XML('<k>2</k>').toString());"))).unwrap();
assert_eq!(later["log"], json!(["2"]), "{later}");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
@@ -474,15 +471,11 @@ fn a_js_script_defines_classes_and_a_jsx_script_cannot() {
assert!(e.contains("SyntaxError"), "{name}: {e}");
}
assert!(run(&mut s, "var C = class {};").unwrap_err().to_string().contains("SyntaxError"));
let _ = std::fs::remove_dir_all(&dir);
}
/// A new empty folder for test `name`.
fn fresh_folder(name: &str) -> std::path::PathBuf {
let dir = std::env::temp_dir().join(format!("vc-script-run-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
dir
/// A new empty folder for test `name`, removed when dropped, also when the test fails.
fn fresh_folder(name: &str) -> vectorcraft_testkit::TempDir {
vectorcraft_testkit::TempDir::new(&format!("script-run-{name}"))
}
/// Starts `source` in the app after a folder dialog it opens first, and allows the script the folder
@@ -530,7 +523,6 @@ fn a_failed_batch_puts_back_the_session_and_names_a_file_it_wrote() {
assert!(!s.guides_locked(), "the failed batch's Lock Guides does not stay");
assert!(path.exists());
assert_eq!(r["written"], json!([p]), "{r}");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
@@ -544,7 +536,6 @@ fn an_export_that_fails_names_no_file() {
assert_eq!(r["log"], json!(["Error"]), "{r}");
assert!(!path.exists());
assert_eq!(r["written"], json!([]), "{r}");
let _ = std::fs::remove_dir_all(&dir);
}
/// The commands a script runs read and write only where its `File` and `Folder` objects may (its
@@ -594,7 +585,6 @@ fn a_scripts_commands_reach_only_its_own_places_and_the_open_documents() {
let r = run(&mut s, &call("document.save", &own)).unwrap();
assert_eq!(r["log"], json!(["ok"]), "a document's own file that was removed is made again: {r}");
assert!(own.exists());
let _ = std::fs::remove_dir_all(&dir);
}
/// The color at the middle of the PNG at `path`.
@@ -656,7 +646,6 @@ fn a_scripts_export_reads_the_files_the_documents_open_before_it_link_to() {
assert!(near(middle_color(&first), BLUE), "the linked file, not its preview: {:?}", middle_color(&first));
assert!(near(middle_color(&second), RED), "a document the script opened gets no linked file: {:?}", middle_color(&second));
assert_eq!(std::fs::read(&pic).unwrap(), png(600, 300, BLUE), "the linked file is not written");
let _ = std::fs::remove_dir_all(&dir);
}
/// A script line that runs command `id` with `params` and logs `ok`, or `denied` when the gate
@@ -674,7 +663,8 @@ fn tried(id: &str, params: &str) -> String {
#[test]
fn a_document_a_script_opened_from_a_linked_file_stays_read_only_in_later_runs() {
use crate::tests_links::{RED, open, place, png, save, session, write};
let art = fresh_folder("gate-linked-runs").join("art");
let root = fresh_folder("gate-linked-runs");
let art = root.join("art");
std::fs::create_dir_all(&art).unwrap();
let p = |f: std::path::PathBuf| f.to_string_lossy().into_owned();
let (pic, inner, poster) = (p(art.join("photo.png")), p(art.join("inner.vectorcraft")), p(art.join("poster.vectorcraft")));
@@ -704,7 +694,6 @@ fn a_document_a_script_opened_from_a_linked_file_stays_read_only_in_later_runs()
log.push(later["log"][0].clone());
assert_eq!(log, [json!("denied"), json!("denied")], "a save in the next run, then a read once nothing the person left links to it");
assert_eq!(std::fs::read(&inner).unwrap(), bytes, "the linked file is as it was");
let _ = std::fs::remove_dir_all(art.parent().unwrap());
}
/// A data set value a script gives a document, and a document a script opens, let no later run
@@ -741,7 +730,6 @@ fn what_a_script_adds_to_the_documents_lets_no_later_run_read_more() {
s.execute("document.save", &json!({"path": mine})).unwrap();
let saved = run(&mut s, &read_secret).unwrap();
assert_eq!(saved["log"], json!(["ok"]), "saved by the person: {saved}");
let _ = std::fs::remove_dir_all(&dir);
}
/// A save the person started before a script's command changed the document, and that finishes
@@ -766,7 +754,6 @@ fn a_save_started_before_a_scripts_change_lets_no_later_run_read_more() {
job.complete(&mut s, uid);
let r = run(&mut s, &tried("file.place", &format!("{{path: {secret:?}, at: [200, 150]}}"))).unwrap();
assert_eq!(r["log"], json!(["denied"]), "{r}");
let _ = std::fs::remove_dir_all(&dir);
}
/// A command a script runs does not save into the app's own libraries; the same command run
@@ -784,7 +771,6 @@ fn a_scripts_commands_do_not_save_into_the_apps_libraries() {
assert!(std::fs::read_dir(&user).map_or(true, |mut d| d.next().is_none()), "nothing is written in the user library folder");
s.execute("swatch.library.save", &json!({"user": true, "name": "Mine"})).unwrap();
assert_eq!(std::fs::read_dir(&user).unwrap().count(), 1);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
@@ -867,7 +853,6 @@ fn an_abandoned_run_reports_the_files_it_wrote() {
let report = s.script_report().unwrap();
assert_eq!((report["kind"].as_str(), report["written"].clone()), (Some("stopped"), json!([p])), "{report}");
assert!(s.script_failure_text().unwrap().contains(&p));
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
@@ -1544,15 +1529,13 @@ fn a_file_saved_before_a_failure_stays_written_and_is_named() {
assert!(e.contains(&p), "{e}");
assert_eq!(s.script_report().unwrap()["written"], json!([p]));
assert_eq!(state(&s), before, "the document does not keep the new path");
let _ = std::fs::remove_dir_all(&dir);
}
/// A run in the app's frames keeps the file-access scope its `script.run` came in, whatever scope
/// the frames that advance it run in.
#[test]
fn a_framed_run_keeps_the_file_access_scope_it_started_in() {
let dir = std::env::temp_dir().join(format!("vc-script-scope-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let dir = fresh_folder("scope");
let (allowed, outside) = (dir.join("allowed"), dir.join("outside"));
std::fs::create_dir_all(&allowed).unwrap();
std::fs::create_dir_all(&outside).unwrap();
@@ -1579,13 +1562,12 @@ fn a_framed_run_keeps_the_file_access_scope_it_started_in() {
let r = crate::file_access::confine(Some(&roots), || finish(&mut s)).unwrap();
assert_eq!(r["log"], json!(["ok"]), "a run the person started is not confined by a later caller: {r}");
assert!(user_target.exists());
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_committed_run_exports_what_it_drew() {
let path = std::env::temp_dir().join(format!("vc-script-export-{}.svg", std::process::id()));
let _ = std::fs::remove_file(&path);
let dir = fresh_folder("export");
let path = dir.join("export.svg");
let p = path.to_string_lossy().into_owned();
let mut s = Session::new();
s.execute("file.new", &json!({})).unwrap();
@@ -1596,7 +1578,6 @@ fn a_committed_run_exports_what_it_drew() {
assert_eq!(svg.matches("<rect").count() + svg.matches("<path").count(), 7, "{svg}");
let inspected = s.execute("document.inspect", &json!({})).unwrap();
assert_eq!(inspected["layers"][0]["children"].as_array().map(Vec::len), Some(7));
let _ = std::fs::remove_file(&path);
}
#[test]
File diff suppressed because it is too large Load Diff
+4
View File
@@ -197,6 +197,10 @@ fn transparency_dither_keeps_a_share_of_partly_transparent_pixels() {
let dithered = file(&mut s, p.clone());
let [left, right] = opaque_halves(&pixels(&dithered));
assert!((left - 0.25).abs() < 0.1 && (right - 0.75).abs() < 0.1, "{format} {method}: {left} {right}");
if method == "pattern" {
// The ordered pattern keeps exactly one pixel of each 2x2 cell at 25% and three at 75%.
assert_eq!([left, right], [0.25, 0.75], "{format}");
}
if format == "gif" {
assert_eq!(gif_transparent_index(&dithered), Some(0), "{method}");
}
+10
View File
@@ -679,6 +679,7 @@ fn structured_junk() {
("perspective.transform", json!({"matrix": [1, 0, 0, 1, 0, 0], "depth": -1e9, "plane": "left", "copy": true})),
("perspective.transform", json!({"matrix": [1, 0, 0, 1, 1e300, 0], "plane": "left"})),
("perspective.nudge", json!({"dx": 1e308, "dy": -1e308, "big": true, "copy": true})),
("perspective.nudge", json!({"dx": 1e308, "dy": -1e308, "fine": true})),
("perspective.plane.move", json!({"plane": "ground", "offset": 1e308, "objects": "copy"})),
("perspective.plane.move", json!({"plane": "left", "by": -1e7, "objects": "move"})),
("perspective.plane.move", json!({"plane": "none", "offset": 0})),
@@ -831,6 +832,9 @@ fn structured_junk() {
("addon.color.nearestSwatch", json!({"library": "spectrum-gradients", "fill": "x", "ids": [u64::MAX]})),
("addon.color.applyNearestSwatch", json!({"library": "web-safe-216", "fill": true, "stroke": true})),
("addon.color.applyNearestSwatch", json!({"library": "nope", "ids": "x", "stroke": 3})),
("addon.color.randomFill", json!({"seed": u64::MAX})),
("addon.color.randomFill", json!({"scheme": "gray", "min": f64::MAX, "max": -1e308, "seed": -1, "ids": [u64::MAX]})),
("addon.color.randomFill", json!({"scheme": "tint", "swatch": "[Registration]", "min": 100, "max": 0, "seed": 1e308, "ids": []})),
("effect.apply", json!({"effect": "no.such.effect"})),
("effect.remove", json!({"index": 99})),
("effect.remove", json!({"indices": [0, 99, u64::MAX]})),
@@ -1033,6 +1037,8 @@ fn structured_junk() {
("addon.arrange.match", json!({"source": "key", "rotate": true})),
("addon.arrange.match", json!({"source": "nope", "size": 3, "rotate": "x", "reference": u64::MAX})),
("addon.arrange.groupOverlapping", json!({"ids": "x", "junk": f64::MAX})),
("addon.arrange.groupRows", json!({"direction": "column"})),
("addon.arrange.groupRows", json!({"direction": "diagonal", "junk": f64::MAX})),
("addon.arrange.randomizeOpacity", json!({"min": 0, "max": 100, "seed": u64::MAX})),
("addon.arrange.randomizeOpacity", json!({"min": f64::MAX, "max": -1e308, "seed": -1, "ids": [u64::MAX]})),
("addon.arrange.randomizeOpacity", json!({"min": 100, "max": 0, "seed": 1e308, "ids": []})),
@@ -1041,6 +1047,10 @@ fn structured_junk() {
("addon.arrange.sort", json!({"by": "opacity", "apply": "y", "order": "descending", "ids": [u64::MAX]})),
("addon.arrange.sort", json!({"by": "x", "apply": "opacity", "distribute": true, "seed": 1e308, "ids": []})),
("addon.arrange.sort", json!({"by": "nope", "apply": null, "order": 3, "distribute": "x"})),
("addon.arrange.markBounds", json!({"style": "rectangle", "bounds": "visual", "weight": 1000, "color": "cmyk 0 100 100 0"})),
("addon.arrange.markBounds", json!({"length": 1e6, "weight": 0.01, "color": [0, 0, 1]})),
("addon.arrange.markBounds", json!({"length": f64::MAX, "weight": -1, "color": "#ff000080", "style": 3})),
("addon.arrange.markBounds", json!({"length": 1e-308, "bounds": "nope", "color": {"swatch": 1}})),
("addon.pathtools.divideDashes", json!({"dash": 1e-308, "gap": -1e308, "fit": "x"})),
("addon.pathtools.divideDashes", json!({"dash": 0.01, "gap": 1e6, "fit": true, "removeGaps": false})),
("addon.pathtools.divideDashes", json!({"dash": f64::MAX, "gap": [0], "removeGaps": null})),
+37 -16
View File
@@ -744,20 +744,41 @@ fn objects_beyond_the_document_range_are_left_out() {
assert!(loaded.warnings.iter().any(|w| w.contains("beyond the document range")), "{:?}", loaded.warnings);
}
#[test]
fn test_af_g_symbol_fill_is_white() {
let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../test.af");
let Ok(bytes) = std::fs::read(&path) else {
return;
};
let loaded = vectorcraft_engine::cmd::fileio::load("test.af", &bytes).unwrap();
assert!(!loaded.preview_only, "{:?}", loaded.warnings);
let d = &loaded.doc;
// The visible "g41" group holds the "g" symbol (path43).
let g41 = all(d).into_iter().find(|n| n.visible && n.name.as_deref() == Some("g41")).expect("visible g41 group must be present");
let path43 = g41.children().and_then(|c| c.iter().find(|n| n.name.as_deref() == Some("path43"))).expect("path43 inside g41 must be present");
let Some(AppearanceItem::Fill(fill)) = path43.appearance.items.first() else {
panic!("path43 has no fill: {:?}", path43.appearance);
};
assert_eq!(fill.paint, Paint::solid(Color::rgb(1.0, 1.0, 1.0)), "The 'g' symbol must have a white fill in test.af, got {:?}", fill.paint);
/// A magenta rectangle with a Recolor adjustment (`RcRA`) attached, at `lightness`.
fn recolored(visible: bool, lightness: f64) -> F {
let mut node = rectangle(10, (0.0, 0.0), (50.0, 50.0));
let recolor = F::Def(
20,
vec![tag(b"RcRA")],
vec![
(tag(b"Visi"), F::Bool(visible)),
(tag(b"AdjP"), F::Obj(tag(b"RecP"), vec![(tag(b"RecH"), F::F64(0.0)), (tag(b"RecS"), F::F64(1.0)), (tag(b"RecL"), F::F64(lightness))])),
],
);
if let F::Def(_, _, fields) = &mut node {
fields.push((tag(b"AdCh"), F::Shared(vec![recolor])));
}
node
}
fn first_fill(n: &Node) -> Paint {
let Some(AppearanceItem::Fill(fill)) = n.appearance.items.first() else { panic!("no fill: {:?}", n.appearance) };
fill.paint.clone()
}
#[test]
fn attached_recolor_adjustments_recolor_the_shape() {
// Lightness 1 recolors to white.
let loaded = open("recolor.af", &canvas_with(vec![recolored(true, 1.0)], None));
assert!(!loaded.warnings.iter().any(|w| w.contains("attached to other layers")), "{:?}", loaded.warnings);
let rect = named(&loaded.doc, "Magenta box");
assert!(rect.appearance.effects.is_empty());
assert_eq!(first_fill(rect), Paint::solid(Color::rgb(1.0, 1.0, 1.0)));
// Lightness 0.5 at hue 0 and full saturation is pure red.
let d = open("red.af", &canvas_with(vec![recolored(true, 0.5)], None)).doc;
let [r, g, b, a] = pixel(&d, 25, 25);
assert!(r > 250 && g < 5 && b < 5 && a == 255, "{:?}", [r, g, b, a]);
// A hidden adjustment leaves the shape as it is.
let d = open("hidden.af", &canvas_with(vec![recolored(false, 1.0)], None)).doc;
assert_eq!(first_fill(named(&d, "Magenta box")), Paint::solid(Color::cmyk(0.0, 1.0, 0.0, 0.0)));
}
@@ -39,12 +39,17 @@ const OUTSIDE: &[(&str, &str, &str)] = &[
("Folder.prototype.execute", "var d = new Folder(p); d.execute();", "filesOpened"),
("Document.prototype.exportVariables", "app.activeDocument.exportVariables(f);", "filesWritten"),
("ExternalObject", "var lib = new ExternalObject(n);", "nativeCode"),
("Document.prototype.saveAs", "app.activeDocument.saveAs(f);", "filesWritten"),
("Document.prototype.exportFile", "app.activeDocument.exportFile(f, ExportType.PNG24);", "filesWritten"),
("SaveOptions.SAVECHANGES", "app.activeDocument.close(SaveOptions.SAVECHANGES);", "filesWritten"),
];
/// The names the host adds that stay inside the document and the run, by the object that has them.
/// Reading a file or a folder, a file dialog, a message to the person and a ScriptUI dialog do not
/// change anything outside it. The document model (`app`, its classes and the enumerations) acts on
/// the open documents; `Document.saveAs` and `close` throw "not available yet".
/// the open documents; `Document.close` closes a document, and saves it to its own file only when it
/// is given `SaveOptions.SAVECHANGES`, which has its row above. `Document.fullName` and
/// `Document.path` only name its file and folder. `app.open` reads the file it is given.
const INSIDE: &[(&str, &str)] = &[
("", "$ File Folder UnitValue Window alert confirm localize prompt toSource"),
("Window.", "alert confirm length prompt prototype"),
@@ -92,8 +97,8 @@ const INSIDE: &[(&str, &str)] = &[
(
"Application.prototype.",
"activeDocument activeDocument= beep beep= constructor coordinateSystem coordinateSystem= documents doScript \
executeMenuCommand getIsFileOpen loadAction loadAction= redo redraw selection selection= selectTool textFonts toString \
typename undo unloadAction unloadAction=",
executeMenuCommand getIsFileOpen loadAction loadAction= open redo redraw selection selection= selectTool textFonts \
toString typename undo unloadAction unloadAction= userInteractionLevel userInteractionLevel=",
),
("DocumentPreset.", "prototype"),
(
@@ -104,18 +109,18 @@ const INSIDE: &[(&str, &str)] = &[
toString transparencyGrid transparencyGrid= typename units units= width width=",
),
("Documents.", "prototype"),
("Documents.prototype.", "add addDocument constructor getByName index length parent toString typename"),
("Documents.prototype.", "add addDocument addDocumentNoUI constructor getByName index length parent toString typename"),
("Document.", "prototype"),
(
"Document.prototype.",
"activeLayer activeLayer= artboards characterStyles close close= compoundPathItems constructor convertCoordinate \
"activeLayer activeLayer= artboards characterStyles close compoundPathItems constructor convertCoordinate \
defaultFillColor defaultFillColor= defaultFillOverprint defaultFillOverprint= defaultFilled defaultFilled= \
defaultStrokeCap defaultStrokeCap= defaultStrokeColor defaultStrokeColor= defaultStrokeDashOffset \
defaultStrokeDashOffset= defaultStrokeDashes defaultStrokeDashes= defaultStrokeJoin defaultStrokeJoin= \
defaultStrokeMiterLimit defaultStrokeMiterLimit= defaultStrokeOverprint defaultStrokeOverprint= \
defaultStrokeWidth defaultStrokeWidth= defaultStroked defaultStroked= documentColorSpace groupItems \
height layers name pageItems paragraphStyles parent pathItems rulerOrigin \
rulerOrigin= rulerUnits saveAs saveAs= scaleFactor selection selection= stories swatches swatches= \
defaultStrokeWidth defaultStrokeWidth= defaultStroked defaultStroked= documentColorSpace fullName groupItems \
height layers name pageItems paragraphStyles parent path pathItems rulerOrigin \
rulerOrigin= rulerUnits saved saved= scaleFactor selection selection= stories swatches swatches= \
symbols symbols= tags textFrames toString typename views width",
),
("Views.", "prototype"),
@@ -221,6 +226,58 @@ const INSIDE: &[(&str, &str)] = &[
("StrokeJoin.", "BEVELENDJOIN MITERENDJOIN ROUNDENDJOIN"),
("Transformation.", "BOTTOM BOTTOMLEFT BOTTOMRIGHT CENTER DOCUMENTORIGIN LEFT RIGHT TOP TOPLEFT TOPRIGHT"),
("ZOrderMethod.", "BRINGFORWARD BRINGTOFRONT SENDBACKWARD SENDTOBACK"),
// The enumerations of saving, exporting and opening.
(
"",
"ColorConversion ColorDestination ColorProfile Compatibility CompressionQuality DownsampleMethod EPSPostScriptLevelEnum \
EPSPreview ExportType MonochromeCompression OutputFlattening PDFBoxType PDFChangesAllowedEnum PDFCompatibility \
PDFOverprint PDFPrintAllowedEnum PDFTrimMarkWeight PDFXStandard PageMarksTypes SVGCSSPropertyLocation SVGDTDVersion \
SVGDocumentEncoding SVGFontSubsetting SVGFontType SaveOptions UserInteractionLevel",
),
("ColorConversion.", "COLORCONVERSIONREPURPOSE COLORCONVERSIONTODEST None"),
(
"ColorDestination.",
"COLORDESTINATIONDOCCMYK COLORDESTINATIONDOCRGB COLORDESTINATIONPROFILE COLORDESTINATIONWORKINGCMYK \
COLORDESTINATIONWORKINGRGB None",
),
("ColorProfile.", "INCLUDEALLPROFILE INCLUDEDESTPROFILE INCLUDERGBPROFILE LEAVEPROFILEUNCHANGED None"),
(
"CompressionQuality.",
"AUTOMATICJPEG2000HIGH AUTOMATICJPEG2000LOSSLESS AUTOMATICJPEG2000LOW AUTOMATICJPEG2000MAXIMUM AUTOMATICJPEG2000MEDIUM \
AUTOMATICJPEG2000MINIMUM AUTOMATICJPEGHIGH AUTOMATICJPEGLOW AUTOMATICJPEGMAXIMUM AUTOMATICJPEGMEDIUM AUTOMATICJPEGMINIMUM \
JPEG2000HIGH JPEG2000LOSSLESS JPEG2000LOW JPEG2000MAXIMUM JPEG2000MEDIUM JPEG2000MINIMUM JPEGHIGH JPEGLOW JPEGMAXIMUM \
JPEGMEDIUM JPEGMINIMUM None ZIP4BIT ZIP8BIT",
),
("DownsampleMethod.", "AVERAGEDOWNSAMPLE BICUBICDOWNSAMPLE NODOWNSAMPLE SUBSAMPLE"),
("MonochromeCompression.", "CCIT3 CCIT4 MONOZIP None RUNLENGTH"),
("OutputFlattening.", "PRESERVEAPPEARANCE PRESERVEPATHS"),
(
"PDFChangesAllowedEnum.",
"CHANGE128ANYCHANGES CHANGE128COMMENTING CHANGE128EDITPAGE CHANGE128FILLFORM CHANGE128NONE CHANGE40ANYCHANGES \
CHANGE40COMMENTING CHANGE40NONE CHANGE40PAGELAYOUT",
),
("PDFPrintAllowedEnum.", "PRINT128HIGHRESOLUTION PRINT128LOWRESOLUTION PRINT128NONE PRINT40HIGHRESOLUTION PRINT40NONE"),
("PDFTrimMarkWeight.", "TRIMMARKWEIGHT0125 TRIMMARKWEIGHT025 TRIMMARKWEIGHT05"),
("PDFXStandard.", "PDFX1A2001 PDFX1A2003 PDFX32002 PDFX32003 PDFX42007 PDFXNONE"),
("PageMarksTypes.", "Japanese Roman"),
("SVGCSSPropertyLocation.", "ENTITIES PRESENTATIONATTRIBUTES STYLEATTRIBUTES STYLEELEMENTS"),
("SVGDTDVersion.", "SVG1_0 SVG1_1 SVGBASIC1_1 SVGTINY1_1 SVGTINY1_1PLUS SVGTINY1_2"),
("SVGDocumentEncoding.", "ASCII UTF16 UTF8"),
("SVGFontSubsetting.", "ALLGLYPHS COMMONENGLISH COMMONROMAN GLYPHSUSED GLYPHSUSEDPLUSENGLISH GLYPHSUSEDPLUSROMAN None"),
("SVGFontType.", "CEFFONT OUTLINEFONT SVGFONT"),
(
"Compatibility.",
"ILLUSTRATOR10 ILLUSTRATOR11 ILLUSTRATOR12 ILLUSTRATOR13 ILLUSTRATOR14 ILLUSTRATOR15 ILLUSTRATOR16 ILLUSTRATOR17 \
ILLUSTRATOR19 ILLUSTRATOR8 ILLUSTRATOR9 JAPANESEVERSION3",
),
("EPSPostScriptLevelEnum.", "LEVEL2 LEVEL3"),
("EPSPreview.", "BWTIFF COLORTIFF None TRANSPARENTCOLORTIFF"),
("ExportType.", "AutoCAD FLASH GIF JPEG PNG24 PNG8 SVG TIFF"),
("PDFBoxType.", "PDFARTBOX PDFBLEEDBOX PDFBOUNDINGBOX PDFCROPBOX PDFMEDIABOX PDFTRIMBOX"),
("PDFCompatibility.", "ACROBAT4 ACROBAT5 ACROBAT6 ACROBAT7 ACROBAT8"),
("PDFOverprint.", "DISCARDPDFOVERPRINT PRESERVEPDFOVERPRINT"),
("SaveOptions.", "DONOTSAVECHANGES PROMPTTOSAVECHANGES"),
("UserInteractionLevel.", "DISPLAYALERTS DONTDISPLAYALERTS"),
(
"",
"CharacterAttributes CharacterStyle CharacterStyleAttributes CharacterStyles Characters Justification \
@@ -351,10 +408,11 @@ const INSIDE: &[(&str, &str)] = &[
];
/// The classes the host adds with nothing but a prototype and its constructor: the page item types
/// that have no members of their own, and the color classes.
/// that have no members of their own, the color classes, and the save and export option classes.
const BARE_CLASSES: &str = "BlendItem CMYKColor EnvelopeItem GradientColor GraphItem GrayColor IntertwineItem LabColor \
MeshItem NoColor PatternColor PlacedDocumentItem PlacedItem RGBColor RasterItem RepeatItem SpotColor SymbolItem \
cmykColor";
cmykColor EPSSaveOptions ExportOptionsJPEG ExportOptionsPNG24 ExportOptionsSVG IllustratorSaveOptions \
PDFSaveOptions";
/// The name the checker does not read, which also stands for its members: `vc` is VectorCraft's
/// own API, and what `vc.run` does depends on the command it runs.
+60
View File
@@ -88,6 +88,66 @@ fn path_of(p: &std::path::Path) -> String {
p.to_string_lossy().into_owned()
}
#[test]
fn scripted_open_converts_importer_output_to_the_requested_color_space() {
let mut s = Session::new();
install(&mut s, &tpl::returning(&tpl::importer("test.scriptcolorspace", r#"["tscmyk"]"#, "{}"), RECT));
let dir = tmp_dir("scriptcolorspace");
s.attach_script_data(dir.join("settings/Script Data"));
let file = dir.join("drawing.tscmyk");
std::fs::write(&file, b"importer input").unwrap();
let script = dir.join("main.jsx");
let path = serde_json::to_string(&file.to_string_lossy()).unwrap();
for (argument, mode) in [
("", vectorcraft_doc::ColorMode::Rgb),
(", DocumentColorSpace.CMYK", vectorcraft_doc::ColorMode::Cmyk),
(", DocumentColorSpace.RGB", vectorcraft_doc::ColorMode::Rgb),
] {
std::fs::write(&script, format!("Folder.userData; var d = app.open(new File({path}){argument}); vc.log(d.documentColorSpace);")).unwrap();
let count = s.documents().len();
let out = s.execute("script.run", &json!({"path": script.to_string_lossy()})).unwrap();
assert_eq!(s.documents().len(), count + 1);
let doc = &s.doc().unwrap().doc;
assert_eq!(doc.color_mode, mode, "{argument}: {out}");
let color = doc.layers[0].children().unwrap()[0].appearance.fill_paint().color().unwrap();
if mode == vectorcraft_doc::ColorMode::Cmyk {
assert!(matches!(color, vectorcraft_color::Color::Cmyk { .. }), "{color:?}");
assert_eq!(out["log"], json!(["DocumentColorSpace.CMYK"]));
} else {
assert!(matches!(color, vectorcraft_color::Color::Rgb { .. }), "{color:?}");
assert_eq!(out["log"], json!(["DocumentColorSpace.RGB"]));
}
}
let _ = std::fs::remove_dir_all(dir);
}
/// A script's PDF open options are refused for a file the named importer reads, which is given
/// only the params, even when the file's extension is a PDF one.
#[test]
fn scripted_pdf_open_options_are_refused_for_an_importer() {
let mut s = Session::new();
install(&mut s, &tpl::returning(&tpl::importer("test.scriptpdfoptions", r#"["ai"]"#, "{}"), RECT));
let dir = tmp_dir("scriptpdfoptions");
s.attach_script_data(dir.join("settings/Script Data"));
let file = dir.join("x.ai");
std::fs::write(&file, b"importer input").unwrap();
let script = dir.join("main.jsx");
let path = serde_json::to_string(&file.to_string_lossy()).unwrap();
for option in ["page: 1", "cropTo: 'media'", "pages: '1'", "crop: 'media'"] {
std::fs::write(
&script,
format!("Folder.userData; vc.run('document.open', {{path: {path}, importer: 'plugin.test.scriptpdfoptions', {option}}});"),
)
.unwrap();
let count = s.documents().len();
let out = s.execute("script.run", &json!({"path": script.to_string_lossy()}));
let text = format!("{out:?}");
assert!(text.contains("PDF open options require a PDF file"), "{option}: {text}");
assert_eq!(s.documents().len(), count, "{option}");
}
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn an_importer_adds_a_read_only_format_while_it_is_installed() {
let mut s = Session::new();
+12 -4
View File
@@ -64,8 +64,12 @@ fn type42_descendants_draw_their_own_glyphs() {
}
// The H, then the I one H's width along; both stand on the baseline, a cap height tall.
let (bh, bi) = (bounds(paths[0]), bounds(paths[1]));
assert!((bh.x0 - 10.0).abs() < 8.0 && bh.width() > 20.0 && bh.width() < 50.0 * wh, "{bh:?}");
assert!((bh.height() - bi.height()).abs() < 0.5 && bh.height() > 25.0 && bh.height() < 40.0, "{bh:?} {bi:?}");
// The bundled font's H spans (90, 0)–(562, 656) of its 1000-unit em: at 50 pt from x = 10 that
// is 14.5 to 38.1, 32.8 tall.
assert!((bh.x0 - 14.5).abs() < 0.01 && (bh.width() - 23.6).abs() < 0.01 && (bh.height() - 32.8).abs() < 0.01, "{bh:?}");
// In the y-down document the baseline at y = 20 lands at 80, and the cap height 32.8 above it at 47.2.
assert!((bh.y0 - 47.2).abs() < 0.01 && (bh.y1 - 80.0).abs() < 0.01, "{bh:?}");
assert!((bh.height() - bi.height()).abs() < 0.5, "{bh:?} {bi:?}");
assert!(bi.x0 > 10.0 + 50.0 * wh - 1.0 && bi.x1 < 10.0 + 50.0 * (wh + wi), "{bi:?}");
}
@@ -78,8 +82,12 @@ fn type42_descendants_measure_space_and_outline_their_glyphs() {
check(format!("(\\000\\001\\000\\002) stringwidth pop {} sub abs 0.01 lt", 50.0 * (wh + wi)));
// xyshow places each character where its numbers say.
check("gsave nulldevice 10 20 moveto (\\000\\001\\000\\002) [30 0 7 0] xyshow currentpoint grestore pop 47 sub abs 0.01 lt".into());
// charpath outlines them.
check("newpath 10 20 moveto (\\000\\001) true charpath pathbbox exch pop sub abs 25 gt exch 10 sub abs 8 lt and".into());
// charpath outlines them: the H's box is (14.5, 20)–(38.1, 52.8).
check(
"newpath 10 20 moveto (\\000\\001) true charpath pathbbox 52.8 sub abs 0.01 lt exch 38.1 sub abs 0.01 lt and \
exch 20 sub abs 0.01 lt and exch 14.5 sub abs 0.01 lt and"
.into(),
);
}
/// A descendant that is a font by name only (its program isn't run) sets its characters as type,
+6 -1
View File
@@ -1382,7 +1382,12 @@ mod tests {
"{n}: {b:?}"
);
let area = p.subpaths[0].area().abs();
assert!((area - PI * 50.0 * 30.0).abs() / area < if n == 2 { 0.1 } else { 0.01 }, "{n}: {area}");
if n == 2 {
// Two cubics with handles 4/3 of the half height long: each encloses 2/5 of the box.
assert!((area - 0.8 * 100.0 * 60.0).abs() < 1e-8, "{n}: {area}");
} else {
assert!((area - PI * 50.0 * 30.0).abs() / area < 0.01, "{n}: {area}");
}
}
// A box with no height leaves the path flat rather than dividing by zero.
let flat = ellipse_with_anchors(Rect::new(0.0, 5.0, 40.0, 5.0), 6);
+15 -2
View File
@@ -314,8 +314,21 @@ fn get_at(interp: &mut Interp, o: ObjId, k: f64) -> JsResult<Value> {
interp.get_from(o, &key_of(k), &Value::Object(o))
}
fn has_at(interp: &mut Interp, o: ObjId, k: f64) -> JsResult<bool> {
interp.has_property_indexed(o, &key_of(k))
/// The element at `k` when the object or its prototypes have one: [[HasProperty]], then [[Get]].
/// An object of a host class with an indexer answers an array index with one call of the indexer,
/// made as `k in object` makes it, and has the element when the answer is not `undefined`.
fn element_at(interp: &mut Interp, o: ObjId, k: f64) -> JsResult<Option<Value>> {
let key = key_of(k);
if crate::value::array_index(&key).is_some()
&& let Some(f) = interp.host_indexer(o)?
{
let v = interp.host_index(&f, o, crate::Data::Number(k), true)?;
return Ok((!matches!(v, Value::Undefined)).then_some(v));
}
if !interp.has_property_indexed(o, &key)? {
return Ok(None);
}
interp.get_from(o, &key, &Value::Object(o)).map(Some)
}
/// The estimated bytes a new element adds.
+8 -9
View File
@@ -5,11 +5,12 @@
//! the range is much longer than the object has properties (a sparse array such as
//! `new Array(4294967295)`), so a long empty range costs nothing and no index is allocated for
//! it. The list of indices is made again whenever a script adds an index property to any object
//! while the method runs. Every index visited takes a unit of fuel.
//! while the method runs. An object of a host class with an indexer has every index of the range
//! visited, since its elements are not properties. Every index visited takes a unit of fuel.
use super::{
Builder, ELEMENT_BYTES, arg, constructor, create_at, delete_at, get_at, has_at, length_of, method, native, new_array, object_to_string, put_at,
require_callable, to_integer,
Builder, ELEMENT_BYTES, arg, constructor, create_at, delete_at, element_at, get_at, length_of, method, native, new_array, object_to_string,
put_at, require_callable, to_integer,
};
use crate::heap::{Class, NativeKind, ObjId};
use crate::interp::{Abrupt, Interp, JsResult, strict_eq};
@@ -121,7 +122,9 @@ fn chain(interp: &Interp, obj: ObjId) -> Vec<(ObjId, usize)> {
impl Indices {
fn new(interp: &mut Interp, obj: ObjId, lo: u64, hi: u64, ascending: bool, maps: Vec<Map>) -> JsResult<Self> {
let mut it = Indices { obj, lo, hi, ascending, maps, sparse: None };
if hi.saturating_sub(lo) > DENSE_SPAN {
// An object of a host class with an indexer holds its elements in the host, not in
// properties, so every index of the range is visited.
if hi.saturating_sub(lo) > DENSE_SPAN && interp.host_indexer(obj)?.is_none() {
let present: usize = chain(interp, obj).iter().map(|(_, n)| *n).fold(0, usize::saturating_add);
if hi - lo > (present as u64).saturating_mul(8) {
it.sparse = Some(it.gather(interp)?);
@@ -206,11 +209,7 @@ impl Indices {
/// The element at `k` when the object or its prototypes have one.
fn element(interp: &mut Interp, o: ObjId, k: u64) -> JsResult<Option<Value>> {
let k = k as f64;
if !has_at(interp, o, k)? {
return Ok(None);
}
get_at(interp, o, k).map(Some)
element_at(interp, o, k as f64)
}
/// ToObject of `this`, kept reachable while `f` runs.
+8 -5
View File
@@ -624,11 +624,14 @@ fn math_functions_follow_the_special_cases() {
fn math_random_is_seeded_from_the_os_random_source() {
// On wasm32-unknown-unknown `RandomState`'s keys come from memory addresses, which are the
// same on every page load: the seed must come from the OS (the browser's crypto) instead.
let src = include_str!("interp.rs");
let Some(start) = src.find("fn random_seed()") else { panic!("interp.rs has no random_seed") };
let body = &src[start..];
let body = &body[..body.find("\n}").unwrap_or(body.len())];
assert!(body.contains("random_seed_from(getrandom::u64())"), "Math.random isn't seeded from the OS random source");
// The OS value is the generator's only state: realms given the same value draw the same
// numbers, and a different value draws different ones.
let draws = |os: u64| match Realm::with_os_random(Ok(os)).run("[Math.random(), Math.random(), Math.random()].join()") {
Ok(JsValue::String(s)) => s,
other => panic!("{other:?}"),
};
assert_eq!(draws(0x1234_5678_9abc_def0), draws(0x1234_5678_9abc_def0));
assert_ne!(draws(0x1234_5678_9abc_def0), draws(0x0fed_cba9_8765_4321));
// The OS value is the seed, made odd so it's never zero; a failed read still gives a seed.
assert_eq!(crate::interp::random_seed_from(Ok(0x40)), 0x41);
assert_eq!(crate::interp::random_seed_from(Ok(0)), 1);

Some files were not shown because too many files have changed in this diff Show More