Merge main into fix/census-behavior-tables

This commit is contained in:
dotCooCoo committed 2026-12-01 22:52:50 -08:00
commit 0338960bc2
257 files changed
+10433 -2903

No files matched your search

Generated
+87 -86
View File
@@ -1231,7 +1231,7 @@ dependencies = [
[[package]]
name = "craft"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
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=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
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=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
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=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
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=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
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=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
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=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
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=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
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=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
dependencies = [
"egui",
]
@@ -1381,7 +1381,7 @@ dependencies = [
[[package]]
name = "craft-cms"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
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=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
[[package]]
name = "craft-color-ui"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
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=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
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=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
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=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
dependencies = [
"rayon",
]
@@ -1444,7 +1444,7 @@ dependencies = [
[[package]]
name = "craft-dialogs"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
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=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
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=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
dependencies = [
"serde",
]
@@ -1494,7 +1494,7 @@ dependencies = [
[[package]]
name = "craft-draw"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
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=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
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=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
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=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
[[package]]
name = "craft-font-catalog"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
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=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
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=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
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=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
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=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
[[package]]
name = "craft-gif"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
dependencies = [
"gif",
]
@@ -1619,7 +1619,7 @@ dependencies = [
[[package]]
name = "craft-gzip"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
dependencies = [
"flate2",
]
@@ -1627,7 +1627,7 @@ dependencies = [
[[package]]
name = "craft-host"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
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=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
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=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
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=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
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=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
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=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
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=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
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=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
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=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
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=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
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=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
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=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
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=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
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=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
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=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
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=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
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=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
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=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
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=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
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=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
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=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
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=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
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=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
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=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
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=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
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=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
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=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
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=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
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=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
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=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
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=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
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=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
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=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
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=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
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=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
[[package]]
name = "craft-ui"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
dependencies = [
"craft-cloud-ui",
"craft-ui-canvas",
@@ -2165,9 +2165,10 @@ dependencies = [
[[package]]
name = "craft-ui-canvas"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
dependencies = [
"craft-behavior",
"craft-font-catalog",
"craft-i18n",
"craft-keymap",
"craft-theme",
@@ -2181,7 +2182,7 @@ dependencies = [
[[package]]
name = "craft-ui-contract"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
dependencies = [
"accesskit",
"craft-behavior",
@@ -2219,7 +2220,7 @@ dependencies = [
[[package]]
name = "craft-ui-macros"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
dependencies = [
"proc-macro-crate",
"proc-macro2",
@@ -2230,7 +2231,7 @@ dependencies = [
[[package]]
name = "craft-ui-panels"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
dependencies = [
"craft-behavior",
"craft-host",
@@ -2248,7 +2249,7 @@ dependencies = [
[[package]]
name = "craft-ui-patterns"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
dependencies = [
"craft-behavior",
"craft-host",
@@ -2269,7 +2270,7 @@ dependencies = [
[[package]]
name = "craft-ui-shell"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
dependencies = [
"craft-behavior",
"craft-host",
@@ -2290,7 +2291,7 @@ dependencies = [
[[package]]
name = "craft-ui-widgets"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
dependencies = [
"craft-behavior",
"craft-host",
@@ -2309,7 +2310,7 @@ dependencies = [
[[package]]
name = "craft-update"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
dependencies = [
"base64 0.22.1",
"chrono",
@@ -2341,7 +2342,7 @@ dependencies = [
[[package]]
name = "craft-vectorcraft-format"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
dependencies = [
"flate2",
"serde",
@@ -2352,7 +2353,7 @@ dependencies = [
[[package]]
name = "craft-wayland"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
dependencies = [
"raw-window-handle",
"wayland-backend",
@@ -2362,7 +2363,7 @@ dependencies = [
[[package]]
name = "craft-web-api"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
dependencies = [
"js-sys",
"serde_json",
@@ -2373,7 +2374,7 @@ dependencies = [
[[package]]
name = "craft-win32"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
dependencies = [
"winsafe",
]
@@ -2381,7 +2382,7 @@ dependencies = [
[[package]]
name = "craft-window"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
dependencies = [
"craft-appkit",
"craft-atomic",
@@ -2413,7 +2414,7 @@ dependencies = [
[[package]]
name = "craft-xml"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
dependencies = [
"quick-xml 0.41.0",
"serde",
@@ -3772,7 +3773,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a"
[[package]]
name = "hayro-cmap"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
dependencies = [
"brotli 8.0.4",
"hayro-postscript",
@@ -3781,7 +3782,7 @@ dependencies = [
[[package]]
name = "hayro-interpret"
version = "0.7.0"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
dependencies = [
"bitflags 2.13.2",
"hayro-cmap",
@@ -3799,7 +3800,7 @@ dependencies = [
[[package]]
name = "hayro-jbig2"
version = "0.3.0"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
dependencies = [
"fearless_simd",
"hayro-ccitt",
@@ -3817,12 +3818,12 @@ dependencies = [
[[package]]
name = "hayro-postscript"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
[[package]]
name = "hayro-syntax"
version = "0.7.2"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
dependencies = [
"flate2",
"hayro-ccitt",
@@ -4805,7 +4806,7 @@ dependencies = [
[[package]]
name = "krilla"
version = "0.8.2"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
dependencies = [
"base64 0.22.1",
"bumpalo",
@@ -4962,7 +4963,7 @@ checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4"
[[package]]
name = "linesweeper"
version = "0.5.0"
source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"
source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6"
dependencies = [
"arrayvec",
"kurbo 0.13.1",
+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 = "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" }
craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" }
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6", default-features = false, features = ["interpret", "write"] }
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" }
craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" }
# Language packs: the Craft apps' shared font store installs them (#4936).
craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" }
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" }
craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" }
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" }
# 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 = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" }
craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" }
craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" }
craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" }
# `.pcraft` documents: their manifest, full-size composite, preview, layer pixels and ICC profile.
craft-doc = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0", features = ["pcraft-pixels"] }
craft-doc = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6", features = ["pcraft-pixels"] }
# Native Affinity documents (craft-libs#914).
craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" }
craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" }
# Bounded CDR (v1-v27) and CMX (32-bit) reader (craft-libs#778).
craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" }
craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" }
# SVG parsing, limits, SVGZ and writer (craft-libs#778).
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0", features = ["tree"] }
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" }
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6", features = ["tree"] }
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" }
# EPS container, previews, ASCII85 and DSC comments (craft-libs#778).
craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" }
craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" }
# DXF tags, reader and writer (craft-libs#778, #926, #927).
craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" }
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" }
craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" }
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" }
# WMF, EMF and EMF+ reader (craft-libs#778).
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" }
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" }
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" }
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" }
craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" }
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" }
craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6", default-features = false, features = ["read", "write"] }
craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" }
craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" }
craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" }
craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" }
# 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 = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" }
craft = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" }
# 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 = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" }
craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" }
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" }
craft-color-ui = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" }
craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" }
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" }
# Nightly profile isolation, launch protocol, and security fence.
craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" }
craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" }
# 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 = "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" }
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" }
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" }
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" }
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" }
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" }
krilla = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" }
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" }
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
View File
@@ -155,6 +155,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
- 2026-11-19: Quick Pen tool, in the Pen tool's group (Alt+P, Option+P on macOS): clicks or drags add straight lines, continuous arcs or sharp-corner arcs; Alt tapped on its own switches the action, C flips the last arc, `[` and `]` size it, a click on the first point closes the path and a click on an open end continues it (`path.quickPen`, part of #2660). Headline numbers unchanged.
- 2026-11-19: Quick Pen length handles: a handle beyond the start and the end of the path being drawn, or of the selected path, makes the line or arc there longer or shorter when dragged; a line keeps its direction and an arc its circle (`path.quickPenLength`, part of #2660). Headline numbers unchanged.
- 2026-11-19: Quick Pen toolbar on the canvas while the tool is active: Straight Line, Continuous Arc and Sharp Corner Arc, Flip Arc, and More Options with Hide Toolbar, Pin Toolbar Position and Reset Toolbar Position; it follows the drawing beside the path's last point and its handle drags it (`tool.quickPen.flipArc`, `window.quickPenToolbar`, Window › Quick Pen Toolbar; part of #2660). Headline numbers unchanged.
- 2026-11-19: Quick Pen arc size with Ctrl+wheel: over the canvas, a touchpad scroll or a mouse wheel turned with Ctrl makes the arc size 15° larger or smaller per step, as `]` and `[` do, and the view stays put (`tool.quickPen.arcLarger`, `tool.quickPen.arcSmaller`; part of #2660). Headline numbers unchanged.
- 2026-11-19: Quick Pen editing: with no path being drawn, a drag on an anchor or a segment of a selected path moves it, a line staying a line and an arc an arc beside a moved corner anchor (at a smooth anchor the handles stay in line and the segments bend to meet); a click selects an anchor, Shift-click adds one, and the canvas context menu's Delete removes the selected anchors (`path.moveAnchors`, `edit.clear`; #2660). Headline numbers unchanged.
- 2026-10-31: Pattern libraries: Window › Swatch Libraries › Patterns and the Swatches panel's library menu open Geometric Patterns, a built-in library of eleven pattern swatches (dots, stripes, checks, a grid and shapes); clicking one adds its pattern and swatch to the document, once, and applies it to the active fill or stroke (`swatch.library.add`).
- 2026-11-11: Pattern libraries: Patterns › Grit Textures, a second built-in pattern library, holds eight seamless black textures (Fine Grain, Coarse Grit, Sand, Speckle, Stipple, Scratches, Sparse Flecks and Dense Flecks) on tiles of 18 to 36 pt, each drawn the same way every time; marks that reach past a tile edge continue on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged.
@@ -182,6 +183,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
- 2026-11-28: The Three-Point Arc tool joins an arc to the open paths whose ends its ends are placed on, with Join to Open Path Ends (Tool Options, or J while drawing; `shape.threePointArc` `join`), and in direction mode snaps the third point to where the arc carries an open path on, the same way or turned back (Snap Where the Arc Continues a Path, on by default). Headline numbers unchanged.
- 2026-11-15: Smooth Bridge joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): two selected circles become one closed outline joined by two concave arcs that touch both circles, so every anchor is smooth; the arcs' radius is a percentage of the smaller circle's radius (1 to 1000%, 100% by default), and Keep Originals adds the outline above the circles instead of replacing them. A dialog with Preview, one undo step (`addon.pathtools.bridge`). A VectorCraft addition: headline numbers unchanged.
- 2026-11-18: Smooth Bridge also joins three or more circles: every two whose outlines are within Reach (10 pt by default) are joined, the bridges that connect become one shape each, and a circle bridged to no other stays as it is (at most 2000 circles); with Constant Gap the arcs' radius is the smaller circle's radius plus a gap (#8030). A VectorCraft addition: headline numbers unchanged.
- 2026-12-01: Common Tangents and Smooth Bridge are one dialog, Common Tangents… (#10465): Connect tangents joins the two tangents of each kind into one closed shape, and with External, Straight or Curved picks between the tangent lines and Smooth Bridge's curved outline, with Radius, Constant Gap, Reach and Keep Originals; the Smooth Bridge… menu item is gone, and `addon.pathtools.bridge` still runs and opens the dialog with External and Curved (`connect` and `curved` on `addon.pathtools.commonTangents`). A VectorCraft addition: headline numbers unchanged.
- 2026-11-03: Text Tweaker, the first tool of the Type Tools add-on (Object › Plug-ins › Type Tools): one character attribute (size, baseline shift, rotation, horizontal or vertical scale, tracking, leading or stroke weight) goes letter by letter from a start value to an end value along a straight ramp, an ease, a bow, a spike or at random with a seed, set as the Character panel sets it, while the text stays live; a dialog with Preview, one undo step (`addon.type.textTweaker`, #4924). A VectorCraft addition: headline numbers unchanged.
- 2026-11-01: Group Overlapping Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects whose visual bounds overlap or touch, chains included, go into one group each, within their own layer or group, at the stacking place of their frontmost member; objects that overlap nothing stay as they are. One undo step, a sweep along x so thousands of loose pieces group quickly (at most 20000 objects). A VectorCraft addition: headline numbers unchanged.
- 2026-10-31: Export for Screens works as the reference app's dialog: Artboards and Assets tabs with a grid or list of thumbnails, Clear Selection and Prefix, Create Sub-folders by Scale or Format (on by default), Export PDFs As Single File (the chosen artboards as one PDF's pages, `pdfs: "single"`) or Multiple Files, iOS and Android rows, format presets in a ☰ menu, and a count of the files the export writes (#4895). About 55 community PRs and fixes landed the same day: Find Font, Replace Font, Outline Stroke and Expand leave hidden and locked art alone (with a warning); DXF export writes LINE and ELLIPSE entities and outlines only the strokes a CAD line can't draw; Blob Brush Angle and Roundness; Shift-constrained Perspective Selection; Grid Repeat Options Preview; a gradient mesh from a file budgeted at about a million quads; width-profile strokes keep their shape zoomed out; `.ai`/EPS import fidelity (area type, envelopes, transparency in dictionaries, character styles); PDF import finds hyphenated and CMap-suffixed font names; Windows renders follow the process's core affinity; Enter or Escape in a floating panel's field no longer reaches the canvas (#4803); Properties shows Blend Options for any selected blend (#4817); Artwork Cleanup finds doubled type (#4835) and joins stacked lines into one object (Join Point Text, #4826). Headline numbers unchanged.
+1 -2
View File
@@ -656,8 +656,7 @@ mod tests {
let held = rss_mb();
drop(buffer);
let (Some((held, _)), Some((now, peak))) = (held, rss_mb()) else {
eprintln!("no memory reading (Linux without `ps`): nothing to check");
return;
panic!("rss_mb gave no memory reading");
};
assert!(peak.is_some_and(|peak| peak > held - 16.0), "holding 64 MB: {held:.1} MB, after freeing it: {now:.1} MB, peak {peak:?}");
}
+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 = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0", version = "0.1.0" }
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6", version = "0.1.0" }
wasm-bindgen = "0.2"
serde_json = { workspace = true }
+3 -4
View File
@@ -553,10 +553,9 @@ fn the_saved_engine_preference_is_found() {
let saved = prefs.to_json();
assert_eq!(power_preference(saved.get("gpuPreference").and_then(serde_json::Value::as_str), None), power);
}
// Every choice Preferences offer means something here.
for (value, _) in vectorcraft_engine::cmd::prefscmds::GPU_PREFERENCES {
assert!(["automatic", "lowPower", "highPerformance"].contains(value), "{value}");
}
// Preferences offer the three choices read above, and no other.
let offered: Vec<&str> = vectorcraft_engine::cmd::prefscmds::GPU_PREFERENCES.iter().map(|(value, _)| *value).collect();
assert_eq!(offered, ["automatic", "lowPower", "highPerformance"]);
}
#[test]
+11 -2
View File
@@ -4,7 +4,7 @@ use std::path::PathBuf;
use std::sync::{Mutex, PoisonError};
use std::time::{Duration, Instant};
use craft::settings::{LegacyFile, LoadReport, Location, OpenOptions, SettingsStore, SharedSettings};
use craft::settings::{LegacyFile, LoadReport, Location, OpenOptions, SectionError, SettingsStore, SharedSettings};
use vectorcraft_ui_egui::{AppSettings, from_app, parse_legacy};
use super::{VectorcraftApp, prefs_dir};
@@ -18,6 +18,15 @@ fn legacy_dir() -> Option<PathBuf> {
prefs_dir::profile::prefs_dir(true)
}
/// Parses the one `ui.json` slot of a legacy import: its bytes, or why it could not be read.
fn parse_legacy_slot(slots: &[Result<Option<&[u8]>, &std::io::Error>]) -> Result<(AppSettings, Vec<SectionError>), String> {
match slots.first() {
Some(Ok(Some(bytes))) => parse_legacy(bytes),
Some(Err(e)) => Err(e.to_string()),
_ => Err("the preferences file is missing".to_string()),
}
}
/// Where the log files live: `logs` in the preferences folder (see `logging`).
pub(crate) fn log_dir() -> Option<PathBuf> {
Some(prefs_dir::prefs_dir()?.join("logs"))
@@ -34,7 +43,7 @@ pub(crate) fn prefs_enabled() -> bool {
pub(crate) fn open_store() -> (SharedSettings<AppSettings>, LoadReport) {
let (location, legacy) = match prefs_dir::prefs_dir().filter(|_| prefs_enabled()) {
Some(dir) => {
let file = |dir: PathBuf| LegacyFile { path: dir.join(LEGACY_FILE), parse: parse_legacy };
let file = |dir: PathBuf| LegacyFile { paths: vec![dir.join(LEGACY_FILE)], parse: parse_legacy_slot };
let legacy = std::iter::once(file(dir.clone())).chain(legacy_dir().map(file)).collect();
(Location::Dir(dir), legacy)
}
+3
View File
@@ -28,6 +28,9 @@ impl PrintService for SystemPrint {
fn setup(&mut self, printer: Option<&str>) -> Result<(), String> {
system::setup(printer)
}
fn scripts_may_print(&self) -> bool {
true
}
}
/// The status after the job `title` went to `printer` (the default one without a name), with the
+7 -1
View File
@@ -2220,7 +2220,10 @@ fn brushes_without_modes_vary_randomly_as_before() {
serde_json::to_value(Variation::ALL).unwrap(),
serde_json::json!(["fixed", "random", "pressure", "tilt", "bearing", "rotation", "stylusWheel"])
);
assert!(Variation::ALL.iter().all(|v| Variation::parse(v.id()) == Some(*v) && serde_json::to_value(v).unwrap() == v.id()));
let ids: Vec<&str> = Variation::ALL.iter().map(|v| v.id()).collect();
assert_eq!(serde_json::to_value(Variation::ALL).unwrap(), serde_json::json!(ids), "saved names are the ids");
assert_eq!(Variation::parse("stylusWheel"), Some(Variation::StylusWheel));
assert_eq!(Variation::parse("wheel"), None);
assert!(!Variation::offered(false).contains(&Variation::StylusWheel) && Variation::offered(true).contains(&Variation::StylusWheel));
}
@@ -2228,6 +2231,7 @@ fn brushes_without_modes_vary_randomly_as_before() {
#[test]
fn junk_pressure_brushes_draw_finite_art() {
let bp = preview_path(120.0, 24.0);
let mut drawn = 0;
for (size, var) in [(1e308, 1e308), (-1e308, 1e308), (0.0, -1e308), (f64::MAX, f64::MAX)] {
for profile in [vec![], vec![(0.0, 2.0), (0.0, -1.0), (5.0, 0.5)], vec![(1.0, 1.0), (0.0, 0.0)]] {
let out = stroke_pieces(&Document::new(1.0, 1.0), &pressure_calli(size, var), &bp, &pressed(profile));
@@ -2236,8 +2240,10 @@ fn junk_pressure_brushes_draw_finite_art() {
all_points(n, &mut pts);
}
assert!(pts.iter().all(|p| p.x.is_finite() && p.y.is_finite()), "{size} {var}");
drawn += usize::from(!pts.is_empty());
}
}
assert_eq!(drawn, 12, "brushes that draw");
}
/// A scatter brush of 10 × 4 pt rectangles whose size goes from `lo` % to `hi` % as `mode` says.
+1 -1
View File
@@ -131,7 +131,7 @@ fn pens_pick_colors_and_widths() {
let i = plot("IN;SP1;PW1;PD0,0,10,0;PU;PW2,2;SP2;PD0,10,10,10;PU;SP1;PD0,20,10,20;PU;IN;SP1;PD0,30,10,30;");
let widths: Vec<f64> = leaves(&i.document).iter().map(|n| stroke(n).width).collect();
let want = [MM, 2.0 * MM, MM, 0.35 * MM];
assert!(widths.iter().zip(want).all(|(a, b)| (a - b).abs() < 1e-9), "{widths:?}");
assert!(widths.len() == want.len() && widths.iter().zip(want).all(|(a, b)| (a - b).abs() < 1e-9), "{widths:?}");
}
#[test]
+2 -1
View File
@@ -1448,7 +1448,8 @@ fn crop_keeps_an_instance_whose_art_reaches_the_region() {
let art = path(&mut d, shapes::rectangle(Rect::new(100.0, 50.0, 140.0, 90.0)), Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0);
d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Far".into(), art: Arc::new(art) });
let o = DxfOptions { crop: true, ..opts(&d) };
assert!(!kinds(&export(&d, &o).unwrap()).is_empty());
// The red fill: its outline and its hatch.
assert_eq!(kinds(&export(&d, &o).unwrap()), ["LWPOLYLINE", "HATCH"]);
}
/// An instance stained blue by its fill writes its symbol's red art in blue, as the canvas draws it.
+5 -3
View File
@@ -313,8 +313,10 @@ mod tests {
assert_eq!(BlendMode::parse("ColorBurn"), Some(BlendMode::ColorBurn));
assert_eq!(BlendMode::parse("soft_light"), Some(BlendMode::SoftLight));
assert_eq!(BlendMode::parse("nope"), None);
for m in BlendMode::ALL {
assert_eq!(BlendMode::parse(m.label()), Some(m));
}
assert_eq!(BlendMode::parse(""), None);
// A label that starts another one names its own mode.
assert_eq!(BlendMode::parse("Color"), Some(BlendMode::Color));
assert_eq!(BlendMode::parse("Color Dodge"), Some(BlendMode::ColorDodge));
assert_eq!(BlendMode::parse("HARD-LIGHT"), Some(BlendMode::HardLight));
}
}
+31 -21
View File
@@ -15,11 +15,14 @@ fn de(a: [f32; 3], b: [f32; 3]) -> f32 {
#[test]
fn intents_parse_and_name() {
for i in Intent::ALL {
assert_eq!(Intent::parse(i.id()), Some(i));
assert_eq!(Intent::parse(i.label()), Some(i));
}
// The id settings save and the label the menu shows both read back, in any case and spacing.
assert_eq!(Intent::RelativeColorimetric.id(), "relative");
assert_eq!(Intent::parse("relative"), Some(Intent::RelativeColorimetric));
assert_eq!(Intent::parse("Relative Colorimetric"), Some(Intent::RelativeColorimetric));
assert_eq!(Intent::parse("absolute_colorimetric"), Some(Intent::AbsoluteColorimetric));
assert_eq!(Intent::parse("PERCEPTUAL"), Some(Intent::Perceptual));
assert_eq!(Intent::parse("bogus"), None);
assert_eq!(Intent::parse(""), None);
}
#[test]
@@ -322,22 +325,29 @@ fn bad_icc_rejected() {
assert!(matches!(register_icc(b"not a profile", None), Err(CmsError::BadProfile(_))));
}
#[cfg(target_os = "macos")]
// test-lint: allow never-run macOS only; CI runs tests on Linux and FreeBSD
/// A profile file is read and registered as its bytes are: a missing file is an I/O error naming
/// the path, a file that is not a profile is refused as one, and a file holding a built-in
/// profile is refused for its name.
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn loads_system_cmyk_icc() {
let path = std::path::Path::new("/System/Library/ColorSync/Profiles/Generic CMYK Profile.icc");
if !path.exists() {
return;
fn loads_icc_files_and_refuses_bad_ones() {
let dir = std::env::temp_dir().join(format!("vectorcraft-color-icc-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let missing = dir.join("missing.icc");
match load_icc_file(&missing) {
Err(CmsError::Io(e)) => assert!(e.contains("missing.icc"), "{e}"),
other => panic!("{other:?}"),
}
let info = load_icc_file(path).unwrap();
assert_eq!(info.kind, ProfileKind::Cmyk);
assert!(profiles().iter().any(|p| p.name == info.name && !p.builtin));
let c = Cms::new(&ColorSettings { cmyk: info.name.clone(), ..Default::default() }).unwrap();
let rgb = [0.7, 0.5, 0.4];
let back = c.cmyk_to_srgb(c.srgb_to_cmyk(rgb, Intent::RelativeColorimetric), false);
assert!(de(rgb, back) < 5.0, "{back:?}");
assert_eq!(c.cmyk_to_srgb([0.0; 4], false).map(|v| (v * 255.0).round() as u8), [255, 255, 255]);
let junk = dir.join("junk.icc");
std::fs::write(&junk, b"not a profile").unwrap();
assert!(matches!(load_icc_file(&junk), Err(CmsError::BadProfile(_))));
let builtin = dir.join("generic.icc");
std::fs::write(&builtin, &*icc_bytes(GENERIC_CMYK).unwrap()).unwrap();
match load_icc_file(&builtin) {
Err(CmsError::Unsupported(e)) => assert!(e.contains("built-in"), "{e}"),
other => panic!("{other:?}"),
}
std::fs::remove_dir_all(&dir).unwrap();
}
/// With black-point compensation, sRGB black separates to the press's black point and that black
@@ -569,10 +579,10 @@ fn a_document_gets_the_same_context_for_the_same_profiles() {
/// settings saved before the policies existed read with the default policy.
#[test]
fn policies_parse_and_default_in_saved_settings() {
for p in Policy::CMYK {
assert_eq!(Policy::parse(p.id()), Some(p));
}
assert_eq!(Policy::parse("preserveNumbers"), Some(Policy::PreserveNumbers));
assert_eq!(Policy::parse("convert"), Some(Policy::Convert));
assert_eq!(Policy::parse("bogus"), None);
assert_eq!(Policy::parse("Preserve Numbers"), None, "only ids parse");
assert!(!Policy::RGB.contains(&Policy::PreserveNumbers));
let old: ColorSettings =
serde_json::from_str(r#"{"rgb": "sRGB IEC61966-2.1", "cmyk": "Device CMYK (uncalibrated)", "intent": "perceptual", "bpc": false}"#).unwrap();
+1 -1
View File
@@ -395,5 +395,5 @@ fn cmyk_to_cmyk_compensates_the_black_point() {
assert_ne!(convert(true), convert(false));
// White is untouched.
let white = generic.to_same_model_of(&device, &[0.0; 4], rel, true).unwrap();
assert!(white.iter().all(|v| *v < 0.01), "{white:?}");
assert!(white.len() == 4 && white.iter().all(|v| *v < 0.01), "{white:?}");
}
+1
View File
@@ -108,6 +108,7 @@ fn the_fit_predicts_patches_it_left_out() {
let corner = |p: &measured::Patch| p.cmyk.iter().all(|v| *v == 0.0 || *v == 1.0);
let first = |p: &measured::Patch| patches.iter().position(|q| q.cmyk == p.cmyk).unwrap_or(0);
let (kept, left): (Vec<&measured::Patch>, Vec<_>) = patches.iter().partition(|p| first(p) % 4 != 3 || corner(p));
assert!(!left.is_empty(), "{}: nothing left out", c.reference);
assert!(left.iter().all(|l| kept.iter().all(|k| k.cmyk != l.cmyk)), "{}", c.reference);
let kept: Vec<measured::Patch> = kept.into_iter().copied().collect();
let left: Vec<measured::Patch> = left.into_iter().copied().collect();
+3 -2
View File
@@ -464,9 +464,10 @@ impl Gradient {
self.repeats.clamp(1, MAX_REPEATS)
}
/// Does it paint something other than its end colors past the ends of its stops, or run its
/// stops more than once: a linear, radial, conic or diamond gradient that repeats or reflects?
/// stops more than once: a linear, radial, conic or diamond gradient with stops that repeats or
/// reflects? One without stops paints as one that pads.
pub fn is_spread(&self) -> bool {
!self.spread.is_pad() && self.kind != GradientKind::Freeform
!self.spread.is_pad() && self.kind != GradientKind::Freeform && !self.stops.is_empty()
}
/// The spread and count as the gradient paints them: Pad and 1 for one that pads (whatever
/// count it keeps) and for a freeform one, else its spread and [`Self::repeat_count`]. Equal
@@ -36,6 +36,10 @@ fn spread_maps_the_parameter_to_a_place_along_the_stops() {
let free = spread(GradientKind::Freeform, GradientSpread::Repeat, 3);
assert_eq!(free.spread_param(0.7), 0.7);
assert!(!free.is_spread() && !pad.is_spread() && repeat.is_spread());
// Without stops it paints as one that pads.
let empty = Gradient { stops: vec![], ..repeat.clone() };
assert!(!empty.is_spread());
assert_eq!(empty.painted_spread(), (GradientSpread::Pad, 1));
assert!(repeat.spread_param(f64::NAN).is_nan());
// A count out of range (set in code) counts as the nearest one in range.
assert_eq!(spread(GradientKind::Linear, GradientSpread::Repeat, 0).repeat_count(), 1);
+4 -1
View File
@@ -184,6 +184,7 @@ fn reverse_mirrors_midpoints() {
r.reverse();
let mids: Vec<f32> = r.stops.iter().map(|s| s.midpoint).collect();
let want: Vec<f32> = g.stops.iter().rev().skip(1).map(|s| 1.0 - s.midpoint).chain([0.5]).collect();
assert_eq!(mids.len(), g.stops.len(), "reversing keeps every stop");
assert!(mids.iter().zip(&want).all(|(a, b)| (a - b).abs() < 1e-6), "{mids:?} {want:?}");
for i in 0..=20 {
let t = i as f32 / 20.0;
@@ -291,6 +292,7 @@ fn remove_keeps_two() {
fn move_reorders_and_tracks_index() {
let g = g3();
let (v, i) = move_stop(&g.stops, 0, 0.8);
assert_eq!(v.len(), g.stops.len(), "moving keeps every stop");
assert_eq!(i, 1);
assert_eq!(v[1].color.to_hex(), "#ffffff");
assert!(v.windows(2).all(|w| w[0].offset <= w[1].offset));
@@ -1176,7 +1178,8 @@ fn a_conic_with_no_extent_or_bad_numbers_still_sweeps() {
assert!(t(90.0, 50.0).abs() < 1e-12, "{g:?}");
assert!((t(50.0, 90.0) - 0.25).abs() < 1e-12, "{g:?}");
let wedges = g.conic_wedges(Rect::new(0.0, 0.0, 100.0, 100.0), 4, false);
assert!(wedges.iter().flat_map(|(pts, _)| pts).all(|p| p.is_finite()), "{g:?}");
assert_eq!(wedges.len(), 4, "{g:?}");
assert!(wedges.iter().all(|(pts, _)| pts.len() >= 3 && pts.iter().all(|p| p.is_finite())), "{g:?}: {wedges:?}");
}
// A flat extent keeps the vector's direction and the sign of its aspect.
let down = GradientGeom { end: Point::new(50.0, 80.0), ..conic_at(c, 30.0, 0.0) };
+9 -6
View File
@@ -177,20 +177,23 @@ mod tests {
fn harmonies_keep_the_base_model() {
let base = Color::cmyk(0.0, 1.0, 1.0, 0.0);
for h in Harmony::ALL {
assert!(apply(h, base).iter().all(|c| matches!(c, Color::Cmyk { .. })), "{}", label(h));
let colors = apply(h, base);
assert!(colors.len() >= 2 && colors.iter().all(|c| matches!(c, Color::Cmyk { .. })), "{}: {colors:?}", label(h));
}
let Color::Cmyk { c, m, y, .. } = apply(Harmony::Complementary, base)[1] else { panic!("a CMYK complement") };
assert!(c > m && c > y, "the complement of red is a cyan: {c} {m} {y}");
let g = Guide::new(Color::gray(0.4), Harmony::Triad, &GuideOptions::default());
assert!(g.grid.iter().flatten().all(|c| matches!(c, Color::Gray { .. })));
let cells: Vec<&Color> = g.grid.iter().flatten().collect();
assert!(!cells.is_empty() && cells.iter().all(|c| matches!(c, Color::Gray { .. })), "{cells:?}");
}
#[test]
fn rules_parse_by_id_and_label() {
for h in Harmony::ALL {
assert_eq!(parse(h.id()), Some(h));
assert_eq!(parse(label(h)), Some(h));
}
// A label reads back as its rule, its spaces and case ignored, and so does an id.
assert_eq!(parse("Split Complementary"), Some(Harmony::SplitComplementary));
assert_eq!(parse("high contrast 3"), Some(Harmony::HighContrast3));
assert_eq!(parse("tetrad2"), Some(Harmony::Tetrad2));
assert_eq!(parse(""), None);
assert_eq!(Harmony::SplitComplementary.id(), "splitComplementary");
assert_eq!(Harmony::HighContrast3.id(), "highContrast3");
assert_eq!(parse("square"), None);
-12
View File
@@ -825,16 +825,4 @@ mod tests {
let [l, ..] = to_oklab(&stop("Violet Edge", 4));
assert!(l < 0.5 && to_oklab(&stop("Prism Veil", 2))[0] > 0.95, "{l}");
}
#[test]
fn the_other_libraries_keep_classic_mixing_and_centered_midpoints() {
for b in builtins().filter(|b| !["organic-fades", "holographic"].contains(&b.id)) {
for s in builtin_library(b.id).unwrap().iter() {
if let Paint::Gradient(g) = &s.paint {
assert_eq!(g.gradient.method, GradientMethod::Classic, "{}", s.name);
assert!(g.gradient.stops.iter().all(|st| st.midpoint == 0.5), "{}", s.name);
}
}
}
}
}
+4 -4
View File
@@ -796,12 +796,12 @@ mod tests {
#[test]
fn methods_parse_by_id_and_label() {
for m in Method::ALL {
assert_eq!(Method::parse(m.id()), Some(m));
assert_eq!(Method::parse(m.label()), Some(m));
}
assert_eq!(Method::parse("preserveTints"), Some(Method::PreserveTints));
assert_eq!(Method::parse("Hue Shift"), Some(Method::HueShift));
assert_eq!(Method::parse("Tints and Shades"), Some(Method::TintsShades));
assert_eq!(Method::parse("tints & shades"), Some(Method::TintsShades));
assert_eq!(Method::parse("nope"), None);
assert_eq!(Method::parse(""), None);
}
#[test]
+15 -8
View File
@@ -186,13 +186,20 @@ mod tests {
#[test]
fn default_swatches_parse() {
// `solid`/`grad` fall back to black or white on a bad literal instead of panicking; make sure
// none falls back.
let src = include_str!("swatch.rs");
let hexes: Vec<&str> = src.split('"').filter(|t| t.starts_with('#') && t.len() == 7).collect();
assert!(hexes.len() > 30);
for h in hexes {
assert!(Color::from_hex(h).is_some(), "{h}");
}
// `solid` and `grad` fall back to black or white on a bad hex literal. A fallback gives a
// solid the color of Black or White, and a gradient a stop that differs from the swatch
// its hex literal names.
let (s, g) = default_swatches(Model::Rgb);
let solids: Vec<Color> = s.iter().chain(g.iter().flat_map(|g| &g.swatches)).filter_map(|w| w.paint.color()).collect();
assert!(solids.len() > 40, "{}", solids.len());
let repeated: Vec<&Color> = solids.iter().enumerate().filter(|(i, c)| solids[..*i].contains(c)).map(|(_, c)| c).collect();
assert_eq!(repeated, Vec::<&Color>::new(), "colors of more than one default swatch");
let color = |name: &str| s.iter().find(|w| w.name == name).and_then(|w| w.paint.color());
let stops = |name: &str| match s.iter().find(|w| w.name == name).map(|w| &w.paint) {
Some(Paint::Gradient(gp)) => gp.gradient.stops.iter().map(|st| Some(st.color)).collect::<Vec<_>>(),
other => panic!("{name}: {other:?}"),
};
assert_eq!(stops("Sunset"), [color("Amber"), color("Rose")]);
assert_eq!(stops("Ocean"), [color("Cyan"), color("Blue")]);
}
}
+4 -3
View File
@@ -208,10 +208,11 @@ mod tests {
#[test]
fn category_ids_parse_back() {
for c in Category::ALL {
assert_eq!(Category::parse(c.id()), Some(c));
}
// Commands and saved settings name a category by its id, exactly.
assert_eq!(Category::parse("largeText"), Some(Category::LargeText));
assert_eq!(Category::parse("graphics"), Some(Category::Graphics));
assert_eq!(Category::parse("NormalText"), None);
assert_eq!(Category::parse("Large Text"), None, "a label is not an id");
}
fn hue(srgb: [f32; 3]) -> f64 {
+17 -3
View File
@@ -2784,10 +2784,13 @@ mod tests {
Paint::Gradient(Box::new(GradientPaint::new(Gradient { stops, ..Gradient::default() })))
};
let Paint::Gradient(m) = lerp_paint(&spot_gradient(0.2), &spot_gradient(1.0), 0.5) else { panic!() };
assert_eq!(m.gradient.stops.len(), 2);
assert!(m.gradient.stops.iter().all(|s| s.swatch.as_deref() == Some("Spot") && (s.tint - 0.6).abs() < 1e-6), "{:?}", m.gradient.stops);
let Paint::Gradient(m) = lerp_paint(&tinted(0.2), &spot_gradient(1.0), 0.5) else { panic!() };
assert_eq!(m.gradient.stops.len(), 2);
assert!(m.gradient.stops.iter().all(|s| s.swatch.as_deref() == Some("Spot") && (s.tint - 0.6).abs() < 1e-6), "{:?}", m.gradient.stops);
let Paint::Gradient(m) = lerp_paint(&Paint::solid(Color::BLACK), &spot_gradient(1.0), 0.5) else { panic!() };
assert_eq!(m.gradient.stops.len(), 2);
assert!(m.gradient.stops.iter().all(|s| s.swatch.is_none()), "{:?}", m.gradient.stops);
}
@@ -2840,6 +2843,7 @@ mod tests {
let a = gradient_paint(vec![spot_stop(0.0, 0.2, Some(p)), spot_stop(1.0, 0.2, Some(p))]);
let b = gradient_paint(vec![spot_stop(0.0, 1.0, Some(q)), spot_stop(1.0, 1.0, Some(q))]);
let Paint::Gradient(m) = lerp_paint(&a, &b, 0.25) else { panic!() };
assert_eq!(m.gradient.stops.len(), 2);
for s in &m.gradient.stops {
assert_eq!(s.swatch.as_deref(), Some("Spot"));
assert!((s.tint - 0.4).abs() < 1e-6, "{}", s.tint);
@@ -2848,6 +2852,7 @@ mod tests {
// Without plates on either side the steps print the spot ink alone, as before.
let bare = |tint| gradient_paint(vec![spot_stop(0.0, tint, None), spot_stop(1.0, tint, None)]);
let Paint::Gradient(m) = lerp_paint(&bare(0.2), &bare(1.0), 0.5) else { panic!() };
assert_eq!(m.gradient.stops.len(), 2);
assert!(m.gradient.stops.iter().all(|s| s.plates.is_none()), "{:?}", m.gradient.stops);
}
@@ -2882,10 +2887,12 @@ mod tests {
let with = gradient_paint(vec![spot_stop(0.0, 1.0, Some(p)), spot_stop(1.0, 1.0, Some(p))]);
let without = gradient_paint(vec![spot_stop(0.0, 1.0, None), spot_stop(1.0, 1.0, None)]);
let Paint::Gradient(m) = lerp_paint(&without, &with, 0.25) else { panic!() };
assert_eq!(m.gradient.stops.len(), 2);
assert!(m.gradient.stops.iter().all(|s| s.swatch.as_deref() == Some("Spot")), "{:?}", m.gradient.stops);
m.gradient.stops.iter().for_each(|s| assert_plates(s.plates, [0.1, 0.2, 0.0, 0.05]));
// The ends keep their own plates.
let Paint::Gradient(m) = lerp_paint(&without, &with, 0.0) else { panic!() };
assert_eq!(m.gradient.stops.len(), 2);
assert!(m.gradient.stops.iter().all(|s| s.plates.is_none()), "{:?}", m.gradient.stops);
// Another swatch, or an unlinked stop: process steps with no plates, as before.
@@ -2897,6 +2904,7 @@ mod tests {
let plain = gradient_paint(vec![plain.clone(), GradientStop { offset: 1.0, ..plain }]);
for b in [&other, &plain] {
let Paint::Gradient(m) = lerp_paint(&with, b, 0.5) else { panic!() };
assert_eq!(m.gradient.stops.len(), 2);
assert!(m.gradient.stops.iter().all(|s| s.swatch.is_none() && s.plates.is_none()), "{:?}", m.gradient.stops);
}
}
@@ -2906,11 +2914,14 @@ mod tests {
let p = [0.4, 0.8, 0.0, 0.2];
let gradient = gradient_paint(vec![spot_stop(0.0, 1.0, Some(p)), spot_stop(1.0, 1.0, Some(p))]);
let Paint::Gradient(g) = &gradient else { panic!() };
assert!(solid_gradient(Color::BLACK, Some("Spot"), 0.2, &g.gradient).stops.iter().all(|s| s.plates.is_none()));
let linked = solid_gradient(Color::BLACK, Some("Spot"), 0.2, &g.gradient);
assert_eq!(linked.stops.len(), 2);
assert!(linked.stops.iter().all(|s| s.plates.is_none() && s.swatch.as_deref() == Some("Spot") && s.tint == 0.2), "{:?}", linked.stops);
let solid = Paint::Solid { color: Color::cmyk(1.0, 0.7, 0.0, 0.4).tinted(0.2), swatch: Some("Spot".into()), tint: 0.2 };
// The solid's end has no plates: they grow from none toward the gradient's, both ways round.
for (a, b, t) in [(&solid, &gradient, 0.25), (&gradient, &solid, 0.75)] {
let Paint::Gradient(m) = lerp_paint(a, b, t) else { panic!() };
assert_eq!(m.gradient.stops.len(), 2);
for s in &m.gradient.stops {
assert_eq!(s.swatch.as_deref(), Some("Spot"));
assert!((s.tint - 0.4).abs() < 1e-6, "{}", s.tint);
@@ -2919,6 +2930,7 @@ mod tests {
}
// A process solid unlinks the steps, and they take no plates.
let Paint::Gradient(m) = lerp_paint(&Paint::solid(Color::BLACK), &gradient, 0.5) else { panic!() };
assert_eq!(m.gradient.stops.len(), 2);
assert!(m.gradient.stops.iter().all(|s| s.swatch.is_none() && s.plates.is_none()), "{:?}", m.gradient.stops);
}
@@ -3401,7 +3413,8 @@ mod tests {
#[test]
fn odd_dash_blends_to_solid_with_closed_gaps() {
let d = lerp_dash(Some(&Dash { pattern: vec![2.0, 3.0, 4.0], ..Default::default() }), None, 1.0).unwrap();
assert!(d.pattern.iter().skip(1).step_by(2).all(|g| *g == 0.0), "{:?}", d.pattern);
// Doubled to dash, gap, dash, gap, dash, gap; each dash takes the gap after it.
assert_eq!(d.pattern, [5.0, 0.0, 6.0, 0.0, 7.0, 0.0]);
}
#[test]
@@ -3412,7 +3425,8 @@ mod tests {
let mid = lerp_node(&a, &b, 0.4);
let mut ids = vec![];
mid.walk(&mut |n| ids.push(n.id));
assert!(ids.iter().all(|i| *i == NodeId(0)), "{ids:?}");
// The step and its two members, all of them new.
assert_eq!(ids, [NodeId(0); 3]);
}
/// A blend of `a` and `b` spaced by `spacing`.
+4 -5
View File
@@ -64,11 +64,10 @@ mod tests {
#[test]
fn modes_read_back_and_unknown_ones_are_add() {
for m in ShapeMode::ALL {
let v = serde_json::to_value(m).unwrap();
assert_eq!(v, serde_json::json!(m.name()));
assert_eq!(serde_json::from_value::<ShapeMode>(v).unwrap(), m);
}
assert_eq!(serde_json::to_value(ShapeMode::Subtract).unwrap(), serde_json::json!("subtract"));
assert_eq!(serde_json::from_value::<ShapeMode>(serde_json::json!("exclude")).unwrap(), ShapeMode::Exclude);
assert_eq!(ShapeMode::parse("intersect"), Some(ShapeMode::Intersect));
assert_eq!(ShapeMode::parse("Intersect"), None);
for v in [serde_json::json!("divide"), serde_json::json!(3), serde_json::json!(null), serde_json::json!({"a": [1]})] {
assert_eq!(serde_json::from_value::<ShapeMode>(v).unwrap(), ShapeMode::Add);
}
+1
View File
@@ -613,6 +613,7 @@ mod tests {
d.limit_depth_noting(&mut warnings);
assert_eq!(warnings, [symbols_note()]);
assert!(!d.too_deep(None), "{count} {last}");
assert_eq!(d.symbols.len(), count, "every symbol is kept");
assert!(d.symbols.iter().all(|s| s.art.children().is_some()), "the art is still a group");
}
// An edit that makes one hold itself is seen, whatever else stayed as it was.
+1
View File
@@ -253,6 +253,7 @@ mod tests {
let mut a = Node::group(NodeId(1), vec![Arc::new(text)]);
apply(&mut a, &[SymbolOverride { path: vec![0], stroke: Some(red.clone()), ..Default::default() }]);
let Some(NodeKind::Text(t)) = part(&a, &[0]).map(|n| &n.kind) else { panic!("type") };
assert_eq!(t.runs.len(), 1);
assert!(t.runs.iter().all(|r| r.style.stroke == red && r.style.stroke_width == 1.0), "the stroke draws at 1 pt");
// A path whose stroke has neither paint nor weight gets 1 pt too.
+4 -5
View File
@@ -217,11 +217,10 @@ fn indic_digits_map_to_their_scripts_block() {
assert_eq!(map(d, "a-Z ٪"), "a-Z ٪");
}
assert_eq!(map(Digits::Devanagari, "page 12"), "page १२");
for d in Digits::ALL {
assert_eq!(serde_json::to_value(d).unwrap(), d.id());
assert_eq!(serde_json::from_value::<Digits>(d.id().into()).unwrap(), d);
assert_eq!(Digits::from_id(d.id()), Some(d));
}
assert_eq!(serde_json::to_value(Digits::Devanagari).unwrap(), "devanagari");
assert_eq!(serde_json::from_value::<Digits>("farsi".into()).unwrap(), Digits::Farsi);
assert_eq!(Digits::Malayalam.id(), "malayalam");
assert_eq!(Digits::from_id("default"), Some(Digits::Default));
assert_eq!(Digits::from_id("roman"), None);
assert!(serde_json::from_value::<Digits>("roman".into()).is_err());
}
+4 -5
View File
@@ -98,11 +98,10 @@ mod tests {
#[test]
fn ids_round_trip_and_unknown_views_show_the_result() {
for v in TraceView::ALL {
assert_eq!(TraceView::from_id(v.id()), Some(v));
assert_eq!(TraceView::from_id(&v.id().to_ascii_uppercase()), Some(v));
assert!(v.shows_result() || v.shows_outlines() || v.shows_source(), "{v:?} shows something");
}
assert_eq!(TraceView::Source.id(), "sourceImage");
assert_eq!(TraceView::from_id("outlinesWithSourceImage"), Some(TraceView::OutlinesWithSource));
assert_eq!(TraceView::from_id("TRACINGRESULT"), Some(TraceView::Result), "case does not matter");
assert_eq!(TraceView::from_id("tracing"), None);
let mut g = Node::group(crate::NodeId(1), vec![]);
assert_eq!(g.trace_view(), TraceView::Result);
g.extras_mut().trace = Some(Box::new(serde_json::json!({"view": "outlines"})));
+3 -4
View File
@@ -109,10 +109,9 @@ mod tests {
#[test]
fn the_effects_are_colour_adjustments_in_their_own_menu() {
for id in EFFECTS {
assert!(crate::is_adjustment(id), "{id}");
assert_eq!(crate::effect_info(id).unwrap().menu, ["Effect", "Color Effects"]);
}
assert!(crate::is_adjustment(DUOTONE));
assert_eq!(crate::effect_info(DUOTONE).unwrap().menu, ["Effect", "Color Effects"]);
assert!(!crate::is_adjustment("stylize.dropShadow"), "an effect outside the add-on is not one");
}
#[test]
+146 -22
View File
@@ -90,16 +90,10 @@ impl DotShape {
fn path(self, t: f64, s: f64) -> PathData {
let square = |side: f64| shapes::rectangle(Rect::from_center_size(Point::ZERO, (side, side)));
match self {
DotShape::Circle => {
let r = s * (t / std::f64::consts::PI).sqrt();
shapes::ellipse(Rect::from_center_size(Point::ZERO, (2.0 * r, 2.0 * r)))
}
DotShape::Ellipse => {
let r = s * (t / std::f64::consts::PI).sqrt();
shapes::ellipse(Rect::from_center_size(Point::ZERO, (2.6 * r, 2.0 * r / 1.3)))
}
DotShape::Circle => cell_dot(t, s / 2.0, CellKind::Circle),
DotShape::Ellipse => cell_dot(t, s / 2.0, CellKind::Ellipse),
DotShape::Square => square(s * t.sqrt()),
DotShape::Diamond => square(s * t.sqrt()).transformed(Affine::rotate(std::f64::consts::FRAC_PI_4)),
DotShape::Diamond => cell_dot(t, s / 2.0, CellKind::Diamond),
// Cells along a row join into a line as thick as the tone.
DotShape::Line => shapes::rectangle(Rect::from_center_size(Point::ZERO, (s * 1.001, s * t))),
DotShape::Euclidean => PathData::from_bezpath(&spot(t, s / 2.0, SpotKind::Euclidean)),
@@ -296,6 +290,9 @@ fn spot_quadrant(u: f64, h: f64, kind: SpotKind) -> Vec<CubicBez> {
/// the cell with the dot of the opposite tone cut out at each corner, so the dark joins up and the
/// light becomes holes.
fn spot(t: f64, h: f64, kind: SpotKind) -> BezPath {
if t <= 0.5 {
return four_quadrants(&spot_quadrant(t, h, kind));
}
let mut bp = BezPath::new();
let mut add = |curves: Vec<CubicBez>, first: bool| {
for (k, c) in curves.iter().enumerate() {
@@ -305,20 +302,129 @@ fn spot(t: f64, h: f64, kind: SpotKind) -> BezPath {
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);
// Round the corners counterclockwise, each one's hole the dot of the opposite tone.
let q1 = spot_quadrant(1.0 - t.min(1.0), h, kind);
add(reversed(&mapped(&q1, |p| Point::new(h - p.x, h - p.y))), true);
add(mapped(&q1, |p| Point::new(p.x - h, h - p.y)), false);
add(reversed(&mapped(&q1, |p| Point::new(p.x - h, p.y - h))), false);
add(mapped(&q1, |p| Point::new(h - p.x, p.y - h)), false);
bp.close_path();
bp
}
/// The dots that grow past their cell's sides: drawn clipped to the cell, so neighbors meet along
/// the shared side instead of overlapping, sized so the clipped dot covers the tone, and the whole
/// cell at full tone.
#[derive(Clone, Copy)]
enum CellKind {
Circle,
/// 1.69 times as wide as tall.
Ellipse,
Diamond,
}
static CELL_CIRCLE: OnceLock<Vec<f64>> = OnceLock::new();
static CELL_ELLIPSE: OnceLock<Vec<f64>> = OnceLock::new();
static CELL_DIAMOND: OnceLock<Vec<f64>> = OnceLock::new();
impl CellKind {
/// The first quadrant of the dot of size `r` clipped to the quadrant [0, 1]², from the x axis to
/// the y axis. Circle: radius `r`; Ellipse: semi-axes 1.3 `r` and `r` / 1.3; Diamond: half
/// diagonal `r`.
fn quadrant(self, r: f64) -> Vec<CubicBez> {
let corner = Point::new(1.0, 1.0);
match self {
CellKind::Diamond if r <= 1.0 => vec![segment(Point::new(r, 0.0), Point::new(0.0, r))],
CellKind::Diamond if r < 2.0 => vec![
segment(Point::new(1.0, 0.0), Point::new(1.0, r - 1.0)),
segment(Point::new(1.0, r - 1.0), Point::new(r - 1.0, 1.0)),
segment(Point::new(r - 1.0, 1.0), Point::new(0.0, 1.0)),
],
CellKind::Diamond => vec![segment(Point::new(1.0, 0.0), corner), segment(corner, Point::new(0.0, 1.0))],
CellKind::Circle | CellKind::Ellipse => {
let (a, b) = if matches!(self, CellKind::Circle) { (r, r) } else { (1.3 * r, r / 1.3) };
// The ellipse stays inside x ≤ 1 from angle tx and inside y ≤ 1 up to angle ty.
let tx = (1.0 / a).min(1.0).acos();
let ty = (1.0 / b).min(1.0).asin();
if tx >= ty {
return vec![segment(Point::new(1.0, 0.0), corner), segment(corner, Point::new(0.0, 1.0))];
}
let at = |th: f64| Point::new(a * th.cos(), b * th.sin());
let mut out = vec![];
if a > 1.0 {
out.push(segment(Point::new(1.0, 0.0), at(tx)));
}
ellipse_arc(&mut out, a, b, tx, ty);
if b > 1.0 {
out.push(segment(at(ty), Point::new(0.0, 1.0)));
}
out
}
}
}
/// The size at which the dot covers the whole quadrant.
fn max_size(self) -> f64 {
match self {
CellKind::Circle => std::f64::consts::SQRT_2,
// 1 / (1.3 r)² + (1.3 / r)² = 1 at the corner.
CellKind::Ellipse => (1.0 / 1.69 + 1.69_f64).sqrt(),
CellKind::Diamond => 2.0,
}
}
fn table(self) -> &'static OnceLock<Vec<f64>> {
match self {
CellKind::Circle => &CELL_CIRCLE,
CellKind::Ellipse => &CELL_ELLIPSE,
CellKind::Diamond => &CELL_DIAMOND,
}
}
/// For tones `k / SIZE_STEPS`, the size of the dot whose clipped quadrant covers that tone.
fn sizes(self) -> Vec<f64> {
(0..=SIZE_STEPS)
.map(|k| {
let target = k as f64 / SIZE_STEPS as f64;
let (mut lo, mut hi) = (0.0, self.max_size());
for _ in 0..50 {
let mid = (lo + hi) / 2.0;
if curves_area(&self.quadrant(mid)) < target { lo = mid } else { hi = mid }
}
(lo + hi) / 2.0
})
.collect()
}
}
/// The `kind` dot for tone `t` (0..1) in a cell of half side `h` centered on the origin, clipped to
/// the cell ([`CellKind`]).
fn cell_dot(t: f64, h: f64, kind: CellKind) -> PathData {
let sizes = kind.table().get_or_init(|| kind.sizes());
let x = t.clamp(0.0, 1.0) * SIZE_STEPS as f64;
let i = (x.floor() as usize).min(SIZE_STEPS - 1);
let (lo, hi) = (sizes.get(i).copied().unwrap_or(0.0), sizes.get(i + 1).copied().unwrap_or(0.0));
let r = lo + (hi - lo) * (x - i as f64);
let q1 = mapped(&kind.quadrant(r), |p| Point::new(p.x * h, p.y * h));
PathData::from_bezpath(&four_quadrants(&q1))
}
/// The closed path through `q1` (from the x axis to the y axis) and its mirror images in the other
/// three quadrants, counterclockwise.
fn four_quadrants(q1: &[CubicBez]) -> BezPath {
let mut bp = BezPath::new();
let mut add = |curves: Vec<CubicBez>, first: bool| {
for (k, c) in curves.iter().enumerate() {
if k == 0 {
if first { bp.move_to(c.p0) } else { bp.line_to(c.p0) }
}
bp.curve_to(c.p1, c.p2, c.p3);
}
};
add(q1.to_vec(), true);
add(reversed(&mapped(q1, |p| Point::new(-p.x, p.y))), false);
add(mapped(q1, |p| Point::new(-p.x, -p.y)), false);
add(reversed(&mapped(q1, |p| Point::new(p.x, -p.y))), false);
bp.close_path();
bp
}
@@ -709,6 +815,24 @@ mod tests {
assert_eq!((DotShape::parse("Euclidean"), DotShape::parse("elliptical")), (Some(DotShape::Euclidean), Some(DotShape::Elliptical)));
}
#[test]
fn round_and_diamond_dots_stay_in_their_cell_and_fill_it_at_full_tone() {
for shape in [DotShape::Circle, DotShape::Ellipse, DotShape::Diamond] {
for t in [0.2, 0.6, 0.85, 0.97] {
// The dot never reaches into a neighbor's cell, so dots of different tones meet
// along the shared side instead of overlapping into notches.
let b = shape.path(t, 2.0).control_bounds().unwrap();
assert!(b.x0 >= -1.0 - 1e-9 && b.x1 <= 1.0 + 1e-9 && b.y0 >= -1.0 - 1e-9 && b.y1 <= 1.0 + 1e-9, "{shape:?} at {t}: {b:?}");
// What it covers of the cell is the tone.
let area = shape.path(t, 2.0).to_bezpath().area().abs() / 4.0;
assert!((area - t).abs() < 2e-3, "{shape:?} at {t}: {area}");
}
// Full tone is the whole cell, its corners included.
assert!(covers(shape, 1.0, (0.49, 0.49)) && covers(shape, 1.0, (-0.49, 0.49)), "{shape:?}");
assert!(!covers(shape, 0.9, (0.499, 0.499)), "{shape:?}");
}
}
#[test]
fn euclidean_dots_meet_corner_to_corner_at_half() {
let s = DotShape::Euclidean;
-54
View File
@@ -1065,60 +1065,6 @@ fn linear_light_blur_mixes_light_not_values() {
}
}
/// Timings on a 2000 × 2000 raster (`cargo test -p vectorcraft-effects --release -- --ignored
/// --nocapture pixel_timings`).
#[test]
#[ignore]
fn pixel_timings() {
let (w, h) = (2000, 2000);
let src = image(w, h, |x, y| [(x % 256) as u8, (y % 256) as u8, ((x ^ y) % 256) as u8, 255]);
let s = PixelSpace {
to_doc: Affine::IDENTITY,
px: 1.0,
center: Point::new(1000.0, 1000.0),
size: vectorcraft_geom::Vec2::new(2000.0, 2000.0),
channels: Channels::Rgb,
line: 1.0,
extent: 0.0,
};
let cases = [
("blur.radial", json!({"quality": "draft"})),
("blur.radial", json!({"quality": "good"})),
("blur.radial", json!({"quality": "best", "method": "zoom"})),
("blur.smart", json!({"quality": "low"})),
("blur.smart", json!({"quality": "high", "radius": 30})),
("sharpen.unsharpMask", json!({"radius": 20})),
("brushStrokes.accentedEdges", json!({"edgeWidth": 14})),
("brushStrokes.angledStrokes", json!({"strokeLength": 50})),
("brushStrokes.crosshatch", json!({"strokeLength": 50, "strength": 3})),
("brushStrokes.darkStrokes", json!({})),
("brushStrokes.inkOutlines", json!({"strokeLength": 50})),
("brushStrokes.spatter", json!({"sprayRadius": 25})),
("brushStrokes.sprayedStrokes", json!({"strokeLength": 20, "sprayRadius": 25})),
("brushStrokes.sumiE", json!({"strokeWidth": 15})),
("pixelate.colorHalftone", json!({"maxRadius": 4})),
("pixelate.crystallize", json!({"cellSize": 3})),
("pixelate.crystallize", json!({"cellSize": 300})),
("pixelate.mezzotint", json!({"type": "grainyDots"})),
("pixelate.pointillize", json!({"cellSize": 3})),
("pixelate.pointillize", json!({"cellSize": 300})),
("texture.craquelure", json!({"crackSpacing": 2})),
("texture.craquelure", json!({"crackSpacing": 100})),
("texture.grain", json!({"grainType": "clumped"})),
("texture.mosaicTiles", json!({"tileSize": 2})),
("texture.patchwork", json!({"squareSize": 0})),
("texture.stainedGlass", json!({"cellSize": 2})),
("texture.texturizer", json!({"texture": "sandstone", "scaling": 50})),
("texture.texturizer", json!({"texture": "burlap"})),
];
for (id, p) in cases {
let mut d = src.clone();
let t = std::time::Instant::now();
fx(id, p.clone()).apply(&mut d, w, h, &s);
println!("{id} {p}: {:?}", t.elapsed());
}
}
#[test]
fn pixelate_params_take_defaults_and_stay_in_range() {
assert_eq!(fx("pixelate.colorHalftone", json!({})), PixelFx::ColorHalftone { max_radius: 8.0, angles: [108.0, 162.0, 90.0, 45.0] });
+4 -2
View File
@@ -466,14 +466,16 @@ fn wireframe_mode_is_checked_against_the_edges_it_draws() {
assert!(refused.contains("simplify the gradient"), "{refused}");
assert_eq!(crate::validate_revolve(&n, &wire), Ok(()));
n.appearance.effects.push(crate::new_effect(crate::REVOLVE, &wire).unwrap());
assert!(leaves(&drawn(&n)).iter().all(|(_, filled, stroke)| !filled && stroke.is_some()));
let edges = leaves(&drawn(&n));
assert!(!edges.is_empty() && edges.iter().all(|(_, filled, stroke)| !filled && stroke.is_some()), "{} pieces", edges.len());
// On the fill.
let fx = n.appearance.effects.remove(0);
let at = n.appearance.items.iter().position(|i| matches!(i, AppearanceItem::Fill(_))).unwrap();
assert!(crate::revolve::validate_item_revolve(&n, &shaded, at, 0).is_err());
assert_eq!(crate::revolve::validate_item_revolve(&n, &wire, at, 0), Ok(()));
n.appearance.items[at].effects_mut().push(fx);
assert!(leaves(&drawn(&n)).iter().all(|(_, filled, stroke)| !filled && stroke.is_some()));
let edges = leaves(&drawn(&n));
assert!(!edges.is_empty() && edges.iter().all(|(_, filled, stroke)| !filled && stroke.is_some()), "{} pieces", edges.len());
}
/// A 3D (Classic) effect ignores a `render` it does not take in a loaded file: it draws as before.
+1
View File
@@ -155,6 +155,7 @@ fn fitted_dashes_on_curves_and_degenerate_paths_stay_finite() {
s.profile = profile.clone();
});
let o = line_outline(&mixed, &st, 4.0, 0.01);
assert!(!o.elements().is_empty(), "{pat:?}: the curve's dashes are drawn");
assert!(o.elements().iter().filter_map(|e| e.end_point()).all(|p| p.x.is_finite() && p.y.is_finite()), "{pat:?}");
}
}
+3 -1
View File
@@ -301,7 +301,9 @@ fn a_spread_gradient_runs_its_stops_along_the_stroke_that_many_times() {
let mut st = stroke(10.0, mode);
let g = Gradient { spread, repeats: 3, ..Gradient::default() };
st.paint = Paint::Gradient(Box::new(GradientPaint::new(g.clone())));
for s in slices(&bp, &st) {
let pieces = slices(&bp, &st);
assert!(!pieces.is_empty(), "{mode:?} {spread:?}: the stroke is painted in slices");
for s in pieces {
let Paint::Gradient(p) = s.paint(&g.unrolled()) else { panic!("a gradient slice") };
let geom = p.geom.unwrap();
for u in [0.1, 0.5, 0.9] {
+6 -19
View File
@@ -247,15 +247,14 @@ fn a_warp_draws_with_the_map_its_version_names() {
fn a_warp_bends_a_flat_box_as_the_middle_of_its_patch() {
let anchors = |p: &PathData| p.subpaths.iter().flat_map(|s| s.anchors.clone()).collect::<Vec<_>>();
let vertical = shapes::line(Point::new(100.0, 0.0), Point::new(100.0, 100.0));
let out = run("warp.arc", json!({"bend": 50, "version": 1}), &vertical);
assert!(anchors(&out).iter().all(|a| close(a.p.x, 100.0, 1e-9) && close(a.h_in.x, 100.0, 1e-9) && close(a.h_out.x, 100.0, 1e-9)), "{out:?}");
let out = anchors(&run("warp.arc", json!({"bend": 50, "version": 1}), &vertical));
assert!(out.len() >= 2, "{out:?}");
assert!(out.iter().all(|a| close(a.p.x, 100.0, 1e-9) && close(a.h_in.x, 100.0, 1e-9) && close(a.h_out.x, 100.0, 1e-9)), "{out:?}");
let horizontal = shapes::line(Point::new(0.0, 50.0), Point::new(200.0, 50.0));
for style in ["bulge", "fisheye", "inflate", "squeeze"] {
let out = run(&format!("warp.{style}"), json!({"bend": 50, "version": 1}), &horizontal);
assert!(
anchors(&out).iter().all(|a| close(a.p.y, 50.0, 1e-9) && close(a.h_in.y, 50.0, 1e-9) && close(a.h_out.y, 50.0, 1e-9)),
"{style}: {out:?}"
);
let out = anchors(&run(&format!("warp.{style}"), json!({"bend": 50, "version": 1}), &horizontal));
assert!(out.len() >= 2, "{style}: {out:?}");
assert!(out.iter().all(|a| close(a.p.y, 50.0, 1e-9) && close(a.h_in.y, 50.0, 1e-9) && close(a.h_out.y, 50.0, 1e-9)), "{style}: {out:?}");
}
}
@@ -2084,18 +2083,6 @@ fn bad_params_fall_back_to_defaults() {
assert!(close(out.bounds().unwrap().width(), 124.0, 0.1));
}
#[test]
#[ignore]
fn bench_catalog_lookup() {
let t = std::time::Instant::now();
let mut n = 0;
for _ in 0..10_000 {
n += crate::is_geometry("distort.roughen") as usize;
n += crate::merged_params("stylize.dropShadow", &serde_json::Value::Null).as_object().unwrap().len();
}
eprintln!("10k lookups: {:?} ({n})", t.elapsed());
}
#[test]
fn a_repeat_of_a_symbol_whose_art_is_a_repeat_shares_the_instance_budget() {
use std::sync::Arc;
+16 -4
View File
@@ -1035,10 +1035,11 @@ fn a_baked_group_with_type_keeps_a_shadow_on_each_copy() {
use vectorcraft_doc::text::{CharStyle, TextObject};
let style = CharStyle { size: 40.0, fill: Paint::solid(Color::BLACK), ..Default::default() };
let words = Node::new(NodeId(161), vectorcraft_doc::NodeKind::Text(Box::new(TextObject::point(Point::new(5.0, 60.0), "IIII", style))));
if !crate::outline_text(&words).is_some_and(|o| paths_in(&o) > 0) {
if !fonts() {
eprintln!("skipped: built without fonts (enable vectorcraft-text's bundled-fonts to run it)");
return;
}
assert!(crate::outline_text(&words).is_some_and(|o| paths_in(&o) > 0), "the type outlines to paths");
let g = group(160, vec![words, square(162, vec![])], vec![shadow(10.0, 0.0, 0.0), transform(json!({"moveH": 150, "copies": 1}))]);
let b = baked(g);
assert!(near(&shadows_in(&b), &[(10.0, 0.0), (10.0, 0.0)]), "{:?}", shadows_in(&b));
@@ -1640,6 +1641,17 @@ fn type_node(id: u64, effects: Vec<Effect>) -> Node {
n
}
/// Whether the face of the default character style is installed, so that type lays out glyphs.
/// When it is, `type_node`'s type must outline to paths.
fn fonts() -> bool {
let style = vectorcraft_doc::text::CharStyle::default();
if vectorcraft_text::FontDb::global().face(&style.font_family, &style.font_style).is_none() {
return false;
}
assert!(crate::outline_text(&type_node(95, vec![])).is_some_and(|o| paths_in(&o) > 0), "{}: the type outlines to paths", style.font_family);
true
}
/// An instance at (50, 50) with `effects` of a symbol, and the symbol's art: a black 20 pt square
/// centered on its origin.
fn instance(id: u64, effects: Vec<Effect>) -> (Node, Node) {
@@ -1660,7 +1672,7 @@ fn instance(id: u64, effects: Vec<Effect>) -> (Node, Node) {
/// image and the instance are checked.
#[test]
fn each_copy_of_type_an_image_or_a_symbol_instance_carries_the_shadow_listed_before_it() {
let fonts = crate::outline_text(&type_node(95, vec![])).is_some_and(|o| paths_in(&o) > 0);
let fonts = fonts();
if !fonts {
eprintln!("type skipped: built without fonts (enable vectorcraft-text's bundled-fonts to run it)");
}
@@ -1702,7 +1714,7 @@ fn each_copy_of_type_an_image_or_a_symbol_instance_carries_the_shadow_listed_bef
/// listed before that effect, as the canvas draws it, rather than staying type under one shadow.
#[test]
fn baked_type_whose_transform_moves_its_copies_keeps_a_shadow_on_each() {
if !crate::outline_text(&type_node(99, vec![])).is_some_and(|o| paths_in(&o) > 0) {
if !fonts() {
eprintln!("skipped: built without fonts (enable vectorcraft-text's bundled-fonts to run it)");
return;
}
@@ -1738,7 +1750,7 @@ fn type_carries_its_fills_shadow_on_each_copy() {
n
};
let copying = vec![shadow(10.0, 0.0, 0.0), transform(json!({"moveH": 100, "copies": 1}))];
if !crate::outline_text(&type_node(95, vec![])).is_some_and(|o| paths_in(&o) > 0) {
if !fonts() {
eprintln!("type skipped: built without fonts (enable vectorcraft-text's bundled-fonts to run it)");
return;
}
+2 -1
View File
@@ -1002,7 +1002,8 @@ pub use variablecmds::{VariableSort, VariableSortKey, variable_order};
/// Command ids kept only so older scripts keep working: `(alias, the command it duplicates)`.
/// They run as before but the command palette leaves them out (it lists the command once).
pub const ALIASES: &[(&str, &str)] = &[("object.convertDocumentColorMode", "file.documentColorMode")];
pub const ALIASES: &[(&str, &str)] =
&[("object.convertDocumentColorMode", "file.documentColorMode"), ("addon.pathtools.bridge", "addon.pathtools.commonTangents")];
/// Is `id` an [`ALIASES`] entry?
pub fn is_alias(id: &str) -> bool {
@@ -32,15 +32,15 @@ pub(super) fn specs() -> Vec<CommandSpec> {
vec![cmd!(
"addon.pathtools.bridge",
"Smooth Bridge",
["Object", "Plug-ins", "Path Precision Tools"],
[],
None,
"{radius?: % 1..1000 (100; the radius of each bridge's two arcs as a percentage of the smaller circle's radius: larger makes a wider, gentler bridge), gap?: pt 0..1000 (instead of radius: the arcs' radius is the smaller circle's radius plus this gap, so each arc stays this gap away from a circle of the smaller circle's size about the arc's center; for equal circles this gap apart that is where a third circle this gap from both sits, as in a triangular grid, so the channels around an empty place in such a grid are one width; giving both is an error), reach?: pt 0..10000 (10; with three or more circles: how far apart two circles' outlines may be for a bridge between them, overlapping ones included; two circles are bridged at any distance), keepOriginals?: bool (false: each outline replaces its circles, painted as the topmost of them, 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",
"{radius?: % 1..1000 (100; the radius of each bridge's two arcs as a percentage of the smaller circle's radius: larger makes a wider, gentler bridge), gap?: pt 0..1000 (instead of radius: the arcs' radius is the smaller circle's radius plus this gap, so each arc stays this gap away from a circle of the smaller circle's size about the arc's center; for equal circles this gap apart that is where a third circle this gap from both sits, as in a triangular grid, so the channels around an empty place in such a grid are one width; giving both is an error), reach?: pt 0..10000 (10; with three or more circles: how far apart two circles' outlines may be for a bridge between them, overlapping ones included; two circles are bridged at any distance), keepOriginals?: bool (false: each outline replaces its circles, painted as the topmost of them, and a group or compound path the other circles leave empty goes; true: it goes directly above that circle and the circles stay), ids?: [id] (default: the selection; a group, other than a clipping group, gives the objects inside it)} join circles (paths whose outline is a circle, not hidden or locked) into metaball (aka meatball) shapes. Two circles become one closed outline: around each circle on its side away from the other, and along two concave arcs, one on each side, that touch both circles so the outline runs on smoothly into them. With three or more, every two circles within reach are bridged the same way, and the bridges that connect are united into one shape each (holes smaller than 1% of the smallest circle's area are filled); a pair within reach but too far apart for the radius gets no bridge, and so does one whose neck would be thinner than the precision its shape is united at, and a circle bridged to no other is left as it is. Overlapping and touching circles are joined too. An object that is not a circle is an error that says why (an ellipse whose width and height differ, a compound path, a hidden or locked object, or another object). One circle inside another (among three or more, any such pair within reach) is an error; so are two circles too far apart for the radius (the arcs would not reach both, or would cross), or three or more with no pair the arcs can join, which suggests a larger radius or gap when the largest one would bridge them; so are no two circles within reach, more than 2000 circles and more than 8000 bridges. One undo step; the outlines (and the circles left as they are) are selected → {ids, alone}, with {id} too for two circles (kept for older scripts: Common Tangents makes the same outline with `curved`, and the command palette leaves this command out)",
has_selection,
bridge
)]
}
fn bridge(s: &mut Session, p: &Value) -> Result<Value> {
pub(super) fn bridge(s: &mut Session, p: &Value) -> Result<Value> {
let percent = given(p, "radius", Some(RADII), C)?;
let gap = given(p, "gap", Some(GAPS), C)?;
let reach = given(p, "reach", Some(REACHES), C)?.unwrap_or(REACH);
@@ -31,7 +31,7 @@ pub(super) fn specs() -> Vec<CommandSpec> {
"Common Tangents",
["Object", "Plug-ins", "Path Precision Tools"],
None,
"{tangents?: \"external\" (both paths on the same side of each line) | \"internal\" (the lines that run between them) | \"all\" (\"all\"), centerline?: bool (false: true also adds the line joining the two centers, an ellipse's center or a path's center of area), ids?: [id, id] (default: the selection)} add the common tangent lines of two convex closed paths as separate open paths, each from where it touches the first path to where it touches the second (the whole stretch where a straight side lies along it), stroked with the current stroke color and weight (black when the stroke is None) and unfilled, directly above the upper of the two, as one undo step; the new lines are selected. An ellipse drawn with the Ellipse tool, turned or scaled, is measured as an exact ellipse; any other path must be closed, have one outline, bend the same way all around and have at most 10000 segments. Separate paths have two external and two internal tangents; overlapping paths only external ones; one path inside the other has none. Paths that touch, from outside or from inside, share one tangent there instead: a line centered on the point where they touch and as long as the narrower path is wide along it; paths that meet at a corner or along a shared stretch of outline get one such line, at the middle of the directions that touch both. Paths count as touching when the gap between them is at most a billionth of the larger of their sizes and the distance between their centers. One of the two may be a point (a path of one anchor): the lines then run from the point to where they touch the path, two when the point lies outside it (one that lies along a straight side covers the whole side), one when the point lies on its outline, that is, at most the touching tolerance from it, with the point's distance from the path's center in place of the distance between centers (centered on the point and as long as the path is wide along it, or the whole straight side the point lies on), none when it lies inside; every `tangents` value gives the same lines, counted as internal when `tangents` is \"internal\" and as external otherwise, and the centerline runs from the point to the path's center; two points are refused. When there is no tangent of the kind asked for, nothing changes and the result has a `warning` → {ids, external, internal, centerline (its id or null), warning?}",
"{tangents?: \"external\" (both paths on the same side of each line) | \"internal\" (the lines that run between them) | \"all\" (\"all\"), centerline?: bool (false: true also adds the line joining the two centers, an ellipse's center or a path's center of area), connect?: bool (false: true joins the two tangents of each kind into one closed path, along the chords between where they touch each path; a kind with one tangent stays a line), curved?: bool (false: true joins the selected circles into one outline along concave arcs that touch both, as `addon.pathtools.bridge` does, in place of the external tangents; `tangents` other than \"external\", `centerline` and `connect: false` are then an error), radius?: % 1..1000 (100; with curved, as for `addon.pathtools.bridge`), gap?: pt 0..1000 (with curved, instead of radius), reach?: pt 0..10000 (10; with curved, for three or more circles), keepOriginals?: bool (false; with curved), ids?: [id, id] (default: the selection; with curved, two or more circles)} add the common tangent lines of two convex closed paths (with curved, join circles with a smooth bridge into metaball, aka meatball, shapes instead) as separate open paths, each from where it touches the first path to where it touches the second (the whole stretch where a straight side lies along it), stroked with the current stroke color and weight (black when the stroke is None) and unfilled, directly above the upper of the two, as one undo step; the new lines are selected. An ellipse drawn with the Ellipse tool, turned or scaled, is measured as an exact ellipse; any other path must be closed, have one outline, bend the same way all around and have at most 10000 segments. Separate paths have two external and two internal tangents; overlapping paths only external ones; one path inside the other has none. Paths that touch, from outside or from inside, share one tangent there instead: a line centered on the point where they touch and as long as the narrower path is wide along it; paths that meet at a corner or along a shared stretch of outline get one such line, at the middle of the directions that touch both. Paths count as touching when the gap between them is at most a billionth of the larger of their sizes and the distance between their centers. One of the two may be a point (a path of one anchor): the lines then run from the point to where they touch the path, two when the point lies outside it (one that lies along a straight side covers the whole side), one when the point lies on its outline, that is, at most the touching tolerance from it, with the point's distance from the path's center in place of the distance between centers (centered on the point and as long as the path is wide along it, or the whole straight side the point lies on), none when it lies inside; every `tangents` value gives the same lines, counted as internal when `tangents` is \"internal\" and as external otherwise, and the centerline runs from the point to the path's center; two points are refused. When there is no tangent of the kind asked for, nothing changes and the result has a `warning` → {ids, external, internal, centerline (its id or null), warning?}, or with curved `addon.pathtools.bridge`'s {ids, alone, id?}",
has_selection,
common_tangents
)]
@@ -71,9 +71,36 @@ fn refusal(e: pt::OutlineError) -> EngineError {
)
}
/// The parameters that shape a curved bridge.
const CURVED_KEYS: [&str; 4] = ["radius", "gap", "reach", "keepOriginals"];
fn common_tangents(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = COMMON_TANGENTS;
let kinds = choice(p, C, "tangents", &KINDS)?.unwrap_or("all");
let given = |key: &str| p.get(key).is_some_and(|v| !v.is_null());
let kinds = choice(p, C, "tangents", &KINDS)?;
let connect = if given("connect") { Some(switch_or(p, "connect", false, C)?) } else { None };
if switch_or(p, "curved", false, C)? {
if kinds.is_some_and(|k| k != "external") {
return Err(bad(C, "`curved` joins the circles along their external tangents: give `tangents` \"external\" or leave it out"));
}
if given("centerline") {
return Err(bad(C, "`centerline` applies to the tangent lines: leave it out with `curved`"));
}
if connect == Some(false) {
return Err(bad(C, "a curved bridge is always connected: leave `connect` out or set it true"));
}
// The outline is Smooth Bridge's.
let mut bridged = serde_json::Map::new();
for key in CURVED_KEYS.iter().chain(&["ids"]).filter(|k| given(k)) {
bridged.insert((*key).to_owned(), p[*key].clone());
}
return super::bridge::bridge(s, &Value::Object(bridged));
}
if let Some(key) = CURVED_KEYS.iter().find(|k| given(k)) {
return Err(bad(C, format!("`{key}` applies to a curved bridge: give `curved` with it")));
}
let kinds = kinds.unwrap_or("all");
let connect = connect.unwrap_or(false);
let centerline = switch_or(p, "centerline", false, C)?;
let roots = checked_ids_or_selection(s, p, C)?;
let d = &s.doc()?.doc;
@@ -105,6 +132,33 @@ fn common_tangents(s: &mut Session, p: &Value) -> Result<Value> {
_ => (count(pt::TangentKind::External), count(pt::TangentKind::Internal)),
};
let lines: Vec<(Point, Point)> = kept.iter().map(|t| (t.from, t.to)).collect();
// With `connect`, the two tangents of each kind and the chords between their ends on each path make one closed
// shape; a kind with one tangent (paths that touch) keeps it as a line. A point's lines are all one kind.
let shapes: Vec<(Vec<Point>, bool)> = if connect {
let mut out = vec![];
for kind in [pt::TangentKind::External, pt::TangentKind::Internal] {
let of: Vec<&pt::Tangent> = kept.iter().copied().filter(|t| point || t.kind == kind).collect();
match of.as_slice() {
[l, m] => {
// A point's two lines share the point, which then closes the ring once.
let same = |q: Point, p: Point| (q - p).hypot() <= 1e-9 * a.size().max(b.size());
let mut ring = vec![l.from, l.to, m.to, m.from];
ring.dedup_by(|q, p| same(*q, *p));
if ring.len() > 2 && same(ring[0], ring[ring.len() - 1]) {
ring.pop();
}
out.push((ring, true));
}
_ => out.extend(of.iter().map(|t| (vec![t.from, t.to], false))),
}
if point {
break;
}
}
out
} else {
lines.iter().map(|&(from, to)| (vec![from, to], false)).collect()
};
if lines.is_empty() && point {
// Written as `EngineError::Other` so that the i18n message scan finds it.
let warning = EngineError::Other("The point lies inside the path, so it has no tangents".into());
@@ -133,13 +187,14 @@ fn common_tangents(s: &mut Session, p: &Value) -> Result<Value> {
let (parent, idx, _) = d.position(top).ok_or(EngineError::NoNode(top))?;
let mut ids = vec![];
let mut center_id = None;
for (k, (from, to)) in lines.iter().copied().chain(center).enumerate() {
let center = center.map(|(from, to)| (vec![from, to], false));
for (k, (points, closed)) in shapes.iter().cloned().chain(center).enumerate() {
let id = d.alloc_id();
let path = PathData::single(SubPath::polyline(&[from, to], false));
let path = PathData::single(SubPath::polyline(&points, closed));
let mut n = Node::new(id, NodeKind::Path { path, rule: FillRule::NonZero, live: None, clipping: false, guide: false });
look.apply(d, &mut n);
d.insert(parent, idx + 1 + k, n)?;
if k == lines.len() {
if k == shapes.len() {
center_id = Some(id);
}
ids.push(id);
@@ -354,3 +354,113 @@ fn bad_selections_and_params_are_refused() {
let g = group_of(&mut s, &[b]);
assert!(err(&mut s, json!({"ids": [a.0, g.0]})).contains("select two closed paths"));
}
/// The one closed outline of path `id`.
fn outline(s: &Session, id: NodeId) -> vectorcraft_geom::SubPath {
let n = s.doc().unwrap().doc.node(id).unwrap();
let NodeKind::Path { path, .. } = &n.kind else { panic!("not a path") };
let [sp] = path.subpaths.as_slice() else { panic!("{} subpaths", path.subpaths.len()) };
assert!(sp.closed);
sp.clone()
}
/// The anchors of path `id`'s one closed outline.
fn corners(s: &Session, id: NodeId) -> Vec<Point> {
outline(s, id).anchors.iter().map(|a| a.p).collect()
}
#[test]
fn connect_joins_the_external_tangents_and_the_chords_into_one_closed_shape_in_one_step() {
let mut s = session();
let (a, b) = (circle(&mut s, 100.0, 100.0, 20.0), circle(&mut s, 200.0, 100.0, 20.0));
let (before, count) = (steps(&s), s.doc().unwrap().doc.node_count());
let r = s.execute(C, &json!({"tangents": "external", "connect": true, "ids": [a.0, b.0]})).unwrap();
assert_eq!(steps(&s), before + 1, "one undo step");
let ids = r["ids"].as_array().unwrap();
assert_eq!(ids.len(), 1, "one shape in place of two lines");
assert_eq!(s.doc().unwrap().doc.node_count(), count + 1, "the circles stay");
let found = corners(&s, NodeId(ids[0].as_u64().unwrap()));
assert_eq!(found.len(), 4);
// The tangents above and below both circles, joined by each circle's vertical diameter.
for p in [Point::new(100.0, 80.0), Point::new(200.0, 80.0), Point::new(200.0, 120.0), Point::new(100.0, 120.0)] {
assert!(found.iter().any(|&q| near(p, q)), "{p:?} in {found:?}");
}
// In order around the band, not crossing itself: the area is the 100 by 40 rectangle's.
let area = found.iter().zip(found.iter().cycle().skip(1)).map(|(p, q)| p.x * q.y - q.x * p.y).sum::<f64>() / 2.0;
assert!((area.abs() - 4000.0).abs() < 1e-6, "area {area} of {found:?}");
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().doc.node_count(), count);
}
#[test]
fn connect_with_all_makes_one_shape_of_each_kind_and_a_point_makes_a_triangle() {
let mut s = session();
let (ca, cb) = ((Point::new(100.0, 100.0), 20.0), (Point::new(220.0, 140.0), 40.0));
let (a, b) = (circle(&mut s, ca.0.x, ca.0.y, ca.1), circle(&mut s, cb.0.x, cb.0.y, cb.1));
let r = s.execute(C, &json!({"connect": true, "centerline": true, "ids": [a.0, b.0]})).unwrap();
let ids: Vec<NodeId> = r["ids"].as_array().unwrap().iter().map(|v| NodeId(v.as_u64().unwrap())).collect();
assert_eq!(ids.len(), 3, "an external shape, an internal shape and the centerline");
for &id in &ids[..2] {
let found = corners(&s, id);
assert_eq!(found.len(), 4);
let on = |(c, r): (Point, f64)| found.iter().filter(|p| ((**p - c).hypot() - r).abs() < 1e-6).count();
assert_eq!((on(ca), on(cb)), (2, 2), "two corners where the tangents touch each circle: {found:?}");
}
assert_ne!(corners(&s, ids[0]), corners(&s, ids[1]));
assert_eq!(r["centerline"], json!(ids[2].0));
let mut s = session();
let (p, c) = (point(&mut s, 0.0, 100.0), circle(&mut s, 100.0, 100.0, 20.0));
let r = s.execute(C, &json!({"connect": true, "ids": [p.0, c.0]})).unwrap();
let ids = r["ids"].as_array().unwrap();
assert_eq!(ids.len(), 1);
let found = corners(&s, NodeId(ids[0].as_u64().unwrap()));
assert_eq!(found.len(), 3, "the point and where its two lines touch the circle: {found:?}");
assert!(found.iter().any(|&q| near(q, Point::new(0.0, 100.0))));
}
#[test]
fn curved_makes_the_bridge_the_smooth_bridge_command_makes() {
let build = || {
let mut s = session();
let ids = [circle(&mut s, 100.0, 100.0, 20.0), circle(&mut s, 150.0, 100.0, 20.0), circle(&mut s, 125.0, 140.0, 20.0)];
select(&mut s, &ids);
s
};
for (merged, old) in [
(json!({"curved": true}), json!({})),
(
json!({"tangents": "external", "connect": true, "curved": true, "gap": 5, "reach": 30, "keepOriginals": true}),
json!({"gap": 5, "reach": 30, "keepOriginals": true}),
),
] {
let (mut s, mut t) = (build(), build());
let r = s.execute(C, &merged).unwrap();
let q = t.execute("addon.pathtools.bridge", &old).unwrap();
assert_eq!(r, q, "{merged}");
let kinds = |s: &Session| s.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|n| n.kind.clone()).collect::<Vec<_>>();
assert_eq!(kinds(&s), kinds(&t), "{merged}");
}
}
#[test]
fn options_of_the_other_mode_are_refused() {
let mut s = session();
let (a, b) = (circle(&mut s, 100.0, 100.0, 20.0), circle(&mut s, 200.0, 100.0, 20.0));
select(&mut s, &[a, b]);
let before = (steps(&s), s.doc().unwrap().doc.node_count());
let err = |s: &mut Session, p: Value| s.execute(C, &p).unwrap_err().to_string();
for (p, says) in [
(json!({"connect": "yes"}), "connect"),
(json!({"curved": true, "tangents": "all"}), "external"),
(json!({"curved": true, "centerline": true}), "centerline"),
(json!({"curved": true, "connect": false}), "connected"),
(json!({"radius": 50}), "curved"),
(json!({"connect": true, "keepOriginals": true}), "curved"),
(json!({"curved": true, "radius": 50, "gap": 2}), "not both"),
(json!({"curved": true, "radius": 0}), "radius"),
] {
assert!(err(&mut s, p.clone()).contains(says), "{p}: {}", err(&mut s, p.clone()));
}
assert_eq!((steps(&s), s.doc().unwrap().doc.node_count()), before, "nothing changes");
}
+6 -5
View File
@@ -86,7 +86,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Make",
["Object", "Live Paint"],
Some("Cmd+Alt+X"),
"{ids?|id?} build a Live Paint group from the selected paths (paths, compound paths and groups of them; type, images and other objects are refused, nothing changes); each covered face starts with the fill rows that draw (shown, with paint and an opacity above 0) of its front-most covering source that has one and an opacity above 0, and each edge with the stroke rows that draw (also a weight above 0) of its source, in order with their settings and with that source's opacity and blending mode (on a path cut into several edges, dashes go on along the path with the lengths set, without the fit of dashes aligned to corners and path ends, arrowheads stay at its own ends, and a width profile or brush stays only on an edge that runs the whole path); a face or edge given no such row has one unpainted row; with a Live Paint group among them, add the others to it as livePaint.merge does; a Live Paint group alone has nothing to add, so it is selected and nothing changes (no undo step) → {id, faces, edges}",
"{ids?|id?} build a Live Paint group from the selected paths (paths, compound paths and groups of them; type, images and other objects are refused, nothing changes); each covered face starts with the fill rows that draw (shown, with paint and an opacity above 0) of its front-most covering source that has one and an opacity above 0, and each edge with the stroke rows that draw (also a weight above 0) of its source, in order with their settings and with that source's opacity and blending mode (on a path cut into several edges, dashes go on along the path with the lengths set, without the fit of dashes aligned to corners and path ends, arrowheads stay at its own ends, and a width profile or brush stays only on an edge that runs the whole path); a face or edge given no such row has one unpainted row; with a Live Paint group among them, add the others to it as livePaint.merge does; a Live Paint group alone has nothing to add, so it is selected and nothing changes (no undo step). The command stops with an error and leaves the art unchanged when the paths are too many or too complex to map. This happens when the paths have more than 131,072 pieces once cut where they meet, or exceed the sweep's work budget, which counts pairs of segments with overlapping bounds. → {id, faces, edges}",
has_selection_or_ids,
lp_make
),
@@ -95,7 +95,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Merge",
["Object", "Live Paint"],
None,
"{ids?|id?} add the other selected paths (compound paths, groups of paths and Live Paint groups too; type, images and other objects are refused, nothing changes) to the bottom-most Live Paint group, keeping its id, its paint and its own properties (name, lock, visibility, transparency, appearance, opacity mask, graphic style link); a Live Paint group alone has nothing to add, so it is selected and nothing changes (no undo step) → {id, faces, edges}",
"{ids?|id?} add the other selected paths (compound paths, groups of paths and Live Paint groups too; type, images and other objects are refused, nothing changes) to the bottom-most Live Paint group, keeping its id, its paint and its own properties (name, lock, visibility, transparency, appearance, opacity mask, graphic style link); a Live Paint group alone has nothing to add, so it is selected and nothing changes (no undo step). The command stops with an error and leaves the art unchanged when the paths are too many or too complex to map. This happens when the paths have more than 131,072 pieces once cut where they meet, or exceed the sweep's work budget, which counts pairs of segments with overlapping bounds. → {id, faces, edges}",
has_multi_or_ids,
lp_merge
),
@@ -122,7 +122,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Gap Options",
[],
None,
"{id?, ids?: [id…] (instead of id; default: the selected Live Paint groups), detect?: bool (Gap Detection: paint stops at gaps up to size wide), size?: \"small\" (3 pt) | \"medium\" (6 pt) | \"large\" (12 pt) | pt (custom, over 0 up to 72) (Paint Stops At), color?: #rrggbb or a layer color's name such as \"Red\" (Gap Preview Color; a hex color with an alpha part, #rrggbbaa or #rgba, is an error), closeGaps?: bool (add an unpainted path across each gap up to size wide to the group's paths)} set the Gap Options of Live Paint groups (what is not given stays as it was; a group starts with detect false, small and Red) and make their faces again, keeping their paint; when every group already has the options and closeGaps finds no gap, nothing changes (no undo step) → {ids, faces, gaps: [[x0,y0,x1,y1]…] (the gaps up to size wide that no path closes, from a loose end of a path to where it closes to; detect closes them for paint), closed (paths added)}",
"{id?, ids?: [id…] (instead of id; default: the selected Live Paint groups), detect?: bool (Gap Detection: paint stops at gaps up to size wide), size?: \"small\" (3 pt) | \"medium\" (6 pt) | \"large\" (12 pt) | pt (custom, over 0 up to 72) (Paint Stops At), color?: #rrggbb or a layer color's name such as \"Red\" (Gap Preview Color; a hex color with an alpha part, #rrggbbaa or #rgba, is an error), closeGaps?: bool (add an unpainted path across each gap up to size wide to the group's paths)} set the Gap Options of Live Paint groups (what is not given stays as it was; a group starts with detect false, small and Red) and make their faces again, keeping their paint; when every group already has the options and closeGaps finds no gap, nothing changes (no undo step). The command stops with an error and leaves the art unchanged when a group's paths are too many or too complex to map. This happens when the paths have more than 131,072 pieces once cut where they meet, or exceed the sweep's work budget, which counts pairs of segments with overlapping bounds. The paths include lines across the gaps when detect is on. → {ids, faces, gaps: [[x0,y0,x1,y1]…] (the gaps up to size wide that no path closes, from a loose end of a path to where it closes to; detect closes them for paint), closed (paths added)}",
has_selection_or_ids,
lp_gap_options
),
@@ -740,12 +740,13 @@ fn build_children(d: &mut Document, sources: Vec<Arc<Node>>, max_gap: Option<f64
src_group.visible = false;
children.push(Arc::new(src_group));
// Every path is an edge, open ones included; faces are the areas they enclose.
let too_many = |e: po::TooManyPieces| EngineError::Other(format!("Live Paint: {e} to paint"));
let (regs, edges) = match max_gap {
Some(gap) => {
let (regs, edges, _) = po::live_paint_with_gaps(&shapes, gap);
let (regs, edges, _) = po::try_live_paint_with_gaps(&shapes, gap).map_err(too_many)?;
(regs, edges)
}
None => po::live_paint(&shapes),
None => po::try_live_paint(&shapes).map_err(too_many)?,
};
if regs.is_empty() && edges.is_empty() {
return Err(EngineError::Other("Live Paint: these paths are too degenerate to paint".into()));
+1 -1
View File
@@ -24,7 +24,7 @@ pub fn specs() -> Vec<CommandSpec> {
"New…",
["File"],
None,
"{preset?: a name from file.newPresets (start from it; the other params change it), name?|title?: document name (default Untitled-N), width?: pt=612|\"210 mm\", height?: pt=792 (each more than 0 and at most 3,999,856 pt, as artboard.new takes them), units?: \"Pixels\"|\"Points\"|\"Picas\"|\"Inches\"|\"Millimeters\"|\"Centimeters\"|\"Feet\"|\"Yards\"|\"Meters\"|\"Feet & Inches\" (default: prefs unitsGeneral, as print presets; screen presets: Pixels), orientation?: \"portrait\"|\"landscape\" (swaps width and height to match), artboards?: n (1–1000), artboardLayout?: {layout?: \"gridByRow\"|\"gridByColumn\"|\"row\"|\"column\", columns?: n (default: all in one row), rows?: n (gridByColumn only, an error with another layout: that many rows, in place of columns; a preset keeps them until columns without rows or another layout is given), spacing?: pt=20, rightToLeft?: bool}, bleed?: pt|[top, bottom, left, right]|{top?, …} (0–72 pt), backgroundContents?: \"transparent\"|\"white\" (a white artboard background, not an object), colorMode?: \"rgb\"|\"cmyk\" (a CMYK document starts with CMYK swatches and stores the colours applied to it as CMYK), rasterEffectsPpi?: 72|150|300 (1–2400), previewMode?: \"default\"|\"pixel\"|\"overprint\" (overprint turns Overprint Preview on, pixel Pixel Preview in the app; default leaves both), alignNewObjectsToPixelGrid?: bool (Advanced Options › Align New Objects to Pixel Grid: paths drawn in the document are pixel-aligned; default on for the Mobile and Web presets, else off; document.setup changes it later), profile?: a category of file.newPresets|null (the New Document profile the document starts from, see file.newProfiles; default: a built-in preset's category, kept by the saved and Recent presets made from it; null or no preset: the defaults), created?: Unix seconds|null (File Info's created date; default now, recorded in the journal so a replay matches), size?: a preset's size label (a preset file.newPresets lists can be passed back; ignored)} → {index, previewMode, profile?: the profile applied, warnings?: [text] (a color profile the profile's file carries that can't be used), profileError?: {profile, reason} (its file is a link or a folder, could not be read, was larger than 64 MiB or is not a native document, or the request may not read the profiles folder, a reason that leaves out the folder's path: the document has the defaults)}; the size is remembered in file.newPresets' Recent",
"{preset?: a name from file.newPresets (start from it; the other params change it), name?|title?: document name (default Untitled-N), width?: pt=612|\"210 mm\", height?: pt=792 (each more than 0 and at most 3,999,856 pt, as artboard.new takes them), units?: \"Pixels\"|\"Points\"|\"Picas\"|\"Inches\"|\"Millimeters\"|\"Centimeters\"|\"Feet\"|\"Yards\"|\"Meters\"|\"Feet & Inches\" (default: prefs unitsGeneral, as print presets; screen presets: Pixels), orientation?: \"portrait\"|\"landscape\" (swaps width and height to match), artboards?: n (a whole number, 1–1000), artboardLayout?: {layout?: \"gridByRow\"|\"gridByColumn\"|\"row\"|\"column\", columns?: n (a whole number, 1–1000; default: all in one row), rows?: n (a whole number, 1–1000; gridByColumn only, an error with another layout: that many rows, in place of columns; a preset keeps them until columns without rows or another layout is given), spacing?: pt=20, rightToLeft?: bool}, bleed?: pt|[top, bottom, left, right]|{top?, …} (0–72 pt), backgroundContents?: \"transparent\"|\"white\" (a white artboard background, not an object), colorMode?: \"rgb\"|\"cmyk\" (a CMYK document starts with CMYK swatches and stores the colours applied to it as CMYK), rasterEffectsPpi?: 72|150|300 (1–2400), previewMode?: \"default\"|\"pixel\"|\"overprint\" (overprint turns Overprint Preview on, pixel Pixel Preview in the app; default leaves both), alignNewObjectsToPixelGrid?: bool (Advanced Options › Align New Objects to Pixel Grid: paths drawn in the document are pixel-aligned; default on for the Mobile and Web presets, else off; document.setup changes it later), profile?: a category of file.newPresets|null (the New Document profile the document starts from, see file.newProfiles; default: a built-in preset's category, kept by the saved and Recent presets made from it; null or no preset: the defaults), created?: Unix seconds|null (File Info's created date; default now, recorded in the journal so a replay matches), size?: a preset's size label (a preset file.newPresets lists can be passed back; ignored)} → {index, previewMode, profile?: the profile applied, warnings?: [text] (a color profile the profile's file carries that can't be used), profileError?: {profile, reason} (its file is a link or a folder, could not be read, was larger than 64 MiB or is not a native document, or the request may not read the profiles folder, a reason that leaves out the folder's path: the document has the defaults)}; the size is remembered in file.newPresets' Recent",
always,
super::newdoc::file_new
),
+2 -2
View File
@@ -36,7 +36,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Export Document",
[],
None,
"{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd|cmx|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin.<plug-in id>, which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; pdf/ai: of the layers the file draws, without editing data, with a warning, and ai refuses pdfCompatible: false; SVG has it as an SVG option), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as <stem>.html / <stem>.map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, transparencyDither?: none (default: pixels under half opacity become transparent)|diffusion|pattern|noise (with transparency: as document.exportForWeb), transparencyDitherAmount?: 100 (0–100: the diffusion transparency dither's strength), matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: every pixel kept exactly; false writes lossy WebP, a smaller file that loses some detail), quality?: 90 (webp with lossless: false: 0–100, higher keeps more detail in a larger file; more than 100 is refused), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts, variableData} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), …hpgl writes a plot of the artboard as pen moves for plotters and cutters (each visible path once along its line in plotter units; useArtboards: true one file per chosen artboard, false the bounds of the art it plots, without placed images, unpainted paths and art at 0% opacity), hpglVersion?: hpgl (default: IN, SP, PU, PD) | hpgl2 (also NP and PC pen colors, each pen's paths as one encoded polyline PE), curveTolerance?: 0.1 (points, 0.01 to 10), pens?: [\"#rrggbb\"…] (pen 1 first, up to 255; each path takes the nearest; default a pen per color in the order the art first draws in it, numbered alike in every file), origin?: bottomLeft (default) | center, sortPaths?: false (each pen's next path the nearest), insideFirst?: false (a path after the pen's paths that lie inside it), …cmx writes one file with a page for the artboard (useArtboards: true a page for each chosen artboard, false the bounds of the visible art; a layer for each Line truncated
"{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd|cmx|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin.<plug-in id>, which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; pdf/ai: of the layers the file draws, without editing data, with a warning, and ai refuses pdfCompatible: false; SVG has it as an SVG option), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as <stem>.html / <stem>.map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, transparencyDither?: none (default: pixels under half opacity become transparent)|diffusion|pattern|noise (with transparency: as document.exportForWeb), transparencyDitherAmount?: 100 (0–100: the diffusion transparency dither's strength), matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: every pixel kept exactly; false writes lossy WebP, a smaller file that loses some detail), quality?: 90 (webp with lossless: false: 0–100, higher keeps more detail in a larger file; more than 100 is refused), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, units, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts, variableData} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), …hpgl writes a plot of the artboard as pen moves for plotters and cutters (each visible path once along its line in plotter units; useArtboards: true one file per chosen artboard, false the bounds of the art it plots, without placed images, unpainted paths and art at 0% opacity), hpglVersion?: hpgl (default: IN, SP, PU, PD) | hpgl2 (also NP and PC pen colors, each pen's paths as one encoded polyline PE), curveTolerance?: 0.1 (points, 0.01 to 10), pens?: [\"#rrggbb\"…] (pen 1 first, up to 255; each path takes the nearest; default a pen per color in the order the art first draws in it, numbered alike in every file), origin?: bottomLeft (default) | center, sortPaths?: false (each pen's next path the nearest), insideFirst?: false (a path after the pen's paths that lie inside it), …cmx writes one file with a page for the artboard (useArtboards: true a page for each chosen artboard, false the bounds of the visible art; a layer f Line truncated
has_doc,
export::export
),
@@ -54,7 +54,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Export for Screens",
["File", "Export"],
None,
"{folder?, zip?: false (one .zip of every file, each deflated or stored, whichever is smaller: no folder → {name, dataBase64, bytes, files: [name…]}; with a folder it is written there → {path, bytes, files}), artboard?: index | artboards?: [index…] | range?: \"1-3\" (default all), assets?: [asset id…] (instead of artboards: each asset's art alone, cropped to its bounds and named after the asset; see assets.list), layers?: [layer id…] (instead of artboards: each layer's art alone, sublayers included, named after the layer), selection?: one|each (instead of artboards: the selected art as one file, or a file per selected object, named after it), fullDocument?: false (one file per format instead: a PDF of every artboard, other formats the bounds of all visible art, named after the document), includeBleed?: false (artboards grown by the document's bleed; a PDF page keeps the artboard as its TrimBox and puts its row's bleed around it once, the document's bleed when the row sets none and its preset gives none or 0), includeArtboardFill?: true (Include Artboard Fill: each artboard's background color behind its art; false leaves it out), pdfs?: multiple|single (Export PDFs As: with several artboards, single writes them as the pages of one PDF per PDF row, named after the document; refused with assets, layers or selection: each), exportPreset?: (a preset of document.exportPresets.list: its settings, under these params), subfolders?: false (each row's files in a sub-folder: its folder, else its size for raster (1x, 2x, 100w…) or its format (SVG, PDF)), folders?: none|rows (as subfolders)|format (a folder per extension: png, svg, pdf…)|item (a folder per artboard, asset, layer or object)|itemFormat (item/extension) (default: rows with subfolders or a preset, else none), name?: (a file name pattern instead of the item's name, with <filename> for the document, <name> for the artboard, asset, layer or object, <index> from 1, #### for the counter zero-padded to the run of #, <format>, <scale>, <suffix> (else the row's suffix ends the name), YYYYMMDD, YYYY-MM-DD, YYYY, <date>, <time>, <YYYY>, <MM>, <DD>, <hh>, <mm> and <ss>; a trailing .ext is dropped, as in `COMPANY-Logo-<filename>-####-YYYYMMDD`; different files it names alike get -2, -3…), counterStart?: 1, counterPer?: item (every file of an item has its number)|file, date?: YYYY-MM-DD (the date the pattern uses; default today, UTC), preset?: mobile (PNG 1x, 2x, 3x) | density (PNG 0.75x–4x in ldpi…xxxhdpi sub-folders) instead of formats (turns subfolders on), formats?: [{format: png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft, scale?: 1 | \"2x\" | \"100w\" | \"100h\" | \"72ppi\", width?: px | height?: px | ppi? (raster only; width, then height, then ppi win over scale), suffix?: (raster default: @2x, @100w, @100h, none at 1x; vector formats drop size suffixes), folder?: (its sub-folder), quality?: (jpg 0–100; webp 0–100 with lossless: false), …the format's options (antiAlias, background, preset (pdf)…)}], settings?: {png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft: {…options for every row of that format}} (rows' own options win), prefix?, antiAlias?: none|art|type (raster rows without their own), openLocation?: (remembered; the app shows the files after exporting)} one file per artboard and format (a PDF holds its artboard alone; artboards with the same name, in any case, get -2, -3…; an unnamed one is Artboard-N; a row whose file would take a name another row's file has, in any case, gets -2, -3… too, and identical rows write one file; row folders that differ only in case are one folder, spelled as the first row spells it) → {files: [path…]} (into the folder of exportPreset, outside the automation read roots: no ZIP path, and files relative to that folder); no folder → {files: [{name, dataBase64}]} (names include sub-folders: 2x/[email protected]); every reply has warnings: [the encoders' warnings for the files, each once: an image that couldn't be decoded, type written in the fallback font…]. eps, ai and vectorcraft rows write a document of the item alone (its one artboard). The params (but zip and assets) are remembered in the document (document.exportSettings; not an undo step). A key it doesn't take, a key no format takes in a format row or in settings, settings for a format it doesn't write, and an unknown key inside a PDF, EPS or SVG option's object, are refused; a key only another format takes in a row or in settings is not used, and warnings name it as given (formats[0].quality; a key in settings only when no row of that format reads it; not a key of an exportPreset). Under automation read roots, an svg or svgz row, and a row whose files carry the native document (vectorcraft, eps, ai but a version 7 file, a pdf with preserveEditing on that holds every artboard of the document it is written from), is refused, before the folder is made or any file is written, while t Line truncated
"{folder?, zip?: false (one .zip of every file, each deflated or stored, whichever is smaller: no folder → {name, dataBase64, bytes, files: [name…]}; with a folder it is written there → {path, bytes, files}), artboard?: index | artboards?: [index…] | range?: \"1-3\" (default all), assets?: [asset id…] (instead of artboards: each asset's art alone, cropped to its bounds and named after the asset; see assets.list), layers?: [layer id…] (instead of artboards: each layer's art alone, sublayers included, named after the layer), selection?: one|each (instead of artboards: the selected art as one file, or a file per selected object, named after it), fullDocument?: false (one file per format instead: a PDF of every artboard, other formats the bounds of all visible art, named after the document), includeBleed?: false (artboards grown by the document's bleed; a PDF page keeps the artboard as its TrimBox and puts its row's bleed around it once, the document's bleed when the row sets none and its preset gives none or 0; a native, .ai or EPS file of an artboard holds the grown artboard with a bleed of 0), includeArtboardFill?: true (Include Artboard Fill: each artboard's background color behind its art; false leaves it out), pdfs?: multiple|single (Export PDFs As: with several artboards, single writes them as the pages of one PDF per PDF row, named after the document; refused with assets, layers or selection: each), exportPreset?: (a preset of document.exportPresets.list: its settings, under these params), subfolders?: false (each row's files in a sub-folder: its folder, else its size for raster (1x, 2x, 100w…) or its format (SVG, PDF)), folders?: none|rows (as subfolders)|format (a folder per extension: png, svg, pdf…)|item (a folder per artboard, asset, layer or object)|itemFormat (item/extension) (default: rows with subfolders or a preset, else none), name?: (a file name pattern instead of the item's name, with <filename> for the document, <name> for the artboard, asset, layer or object, <index> from 1, #### for the counter zero-padded to the run of #, <format>, <scale>, <suffix> (else the row's suffix ends the name), YYYYMMDD, YYYY-MM-DD, YYYY, <date>, <time>, <YYYY>, <MM>, <DD>, <hh>, <mm> and <ss>; a trailing .ext is dropped, as in `COMPANY-Logo-<filename>-####-YYYYMMDD`; different files it names alike get -2, -3…), counterStart?: 1, counterPer?: item (every file of an item has its number)|file, date?: YYYY-MM-DD (the date the pattern uses; default today, UTC), preset?: mobile (PNG 1x, 2x, 3x) | density (PNG 0.75x–4x in ldpi…xxxhdpi sub-folders) instead of formats (turns subfolders on), formats?: [{format: png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft, scale?: 1 | \"2x\" | \"100w\" | \"100h\" | \"72ppi\", width?: px | height?: px | ppi? (raster only; width, then height, then ppi win over scale), suffix?: (raster default: @2x, @100w, @100h, none at 1x; vector formats drop size suffixes), folder?: (its sub-folder), quality?: (jpg 0–100; webp 0–100 with lossless: false), …the format's options (antiAlias, background, preset (pdf)…)}], settings?: {png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft: {…options for every row of that format}} (rows' own options win), prefix?, antiAlias?: none|art|type (raster rows without their own), openLocation?: (remembered; the app shows the files after exporting)} one file per artboard and format (a PDF holds its artboard alone; artboards with the same name, in any case, get -2, -3…; an unnamed one is Artboard-N; a row whose file would take a name another row's file has, in any case, gets -2, -3… too, and identical rows write one file; row folders that differ only in case are one folder, spelled as the first row spells it) → {files: [path…]} (into the folder of exportPreset, outside the automation read roots: no ZIP path, and files relative to that folder); no folder → {files: [{name, dataBase64}]} (names include sub-folders: 2x/[email protected]); every reply has warnings: [the encoders' warnings for the files, each once: an image that couldn't be decoded, type written in the fallback font…]. eps, ai and vectorcraft rows write a document of the item alone (its one artboard). The params (but zip and assets) are remembered in the document (document.exportSettings; not an undo step). A key it doesn't take, a key no format takes in a format row or in settings, settings for a format it doesn't write, and an unknown key inside a PDF, EPS or SVG option's object, are refused; a key only another format takes in a row or in settings is not used, and warnings name it as given (formats[0].quality; a key in settings only when no row of that format reads it; not a key of an exportPreset). Under automation read roots, an svg or svgz row, and a row whose files carry the native document (vectorcraft, eps, ai but a version 7 file, a pdf with preserveEditing on that holds every artboard of the document it is Line truncated
has_doc,
screens::export_for_screens
),
+16 -7
View File
@@ -1131,23 +1131,29 @@ fn names_scripts(item: &Item, r: &Row, single: Option<&[usize]>) -> bool {
/// The document the file of `item` that row `r` writes carries when it carries one
/// ([`names_scripts`]): Full Document's PDF of every artboard, the item's artboard alone for a
/// native, `.ai` or EPS row ([`board_document`]), else the item's document.
fn carried_document<'a>(item: &'a Item, r: &Row, single: Option<&[usize]>) -> std::borrow::Cow<'a, Document> {
/// native, `.ai` or EPS row ([`board_document`]), else the item's document. `grown`: Include Bleed
/// grew the artboards by the document's bleed.
fn carried_document<'a>(item: &'a Item, r: &Row, single: Option<&[usize]>, grown: bool) -> std::borrow::Cow<'a, Document> {
match (&item.every_artboard, r.format.id, single) {
(Some(all), "pdf", None) => std::borrow::Cow::Borrowed(&**all),
_ if r.whole_document() && item.artboard.is_some() => std::borrow::Cow::Owned(board_document(item)),
_ if r.whole_document() && item.artboard.is_some() => std::borrow::Cow::Owned(board_document(item, grown)),
_ => std::borrow::Cow::Borrowed(&*item.doc),
}
}
/// The document a native, `.ai` or EPS row writes for `item`'s artboard: that artboard alone, with
/// its background color and the art on it, as Save's separateArtboards writes it (#3868).
fn board_document(item: &Item) -> Document {
/// its background color and the art on it, as Save's separateArtboards writes it (#3868). When
/// Include Bleed grew the artboard (`grown`), the artboard already holds the bleed, so the document
/// is written with a bleed of 0: opened again, its pages are not grown by the bleed a second time.
fn board_document(item: &Item, grown: bool) -> Document {
let mut d = single_artboard(&item.doc, item.region, &item.name);
if let (Some(a), Some(from)) = (d.artboards.first_mut(), item.doc.artboards.get(item.artboard.unwrap_or(0))) {
a.color = from.color;
}
super::save::keep_art_on(&mut d, item.region);
if grown && item.every_artboard.is_none() {
d.setup.bleed = [0.0; 4];
}
d
}
@@ -1209,7 +1215,7 @@ pub(crate) fn export(s: &mut Session, p: &Value, asked: &Value) -> Result<Value>
let all = item.every_artboard.is_some() && r.format.id == "pdf" && single.is_none();
let board = item.artboard.filter(|_| !all && r.whole_document());
if looked.insert((Arc::as_ptr(&item.doc) as usize, all, board))
&& crate::cmd::links::names_hidden_file(&carried_document(item, r, single.as_deref()), base)
&& crate::cmd::links::names_hidden_file(&carried_document(item, r, single.as_deref(), ungrown.is_some()), base)
{
return Err(bad(C, super::access::IMAGE_OUTSIDE));
}
@@ -1402,7 +1408,10 @@ fn encode_and_write(export: ScreenExport, writer: &mut dyn FnMut(&str, &[u8]) ->
write(pdf_doc.unwrap_or(all), "pdf", &options)?
} else if r.whole_document() && item.artboard.is_some() {
let b = item.artboard.unwrap_or(0);
let d = board_docs.entry((Arc::as_ptr(&item.doc) as usize, b)).or_insert_with(|| Arc::new(board_document(item))).clone();
let d = board_docs
.entry((Arc::as_ptr(&item.doc) as usize, b))
.or_insert_with(|| Arc::new(board_document(item, pdf_doc.is_some())))
.clone();
let mut options = r.options_for(item.region, None)?;
// An EPS page is the artboard, not its art's bounds: an artboard without art still writes.
if r.format.id == "eps" {
+7 -1
View File
@@ -50,6 +50,12 @@ pub const OPTIONS: &[FormatOption] = &[
FormatOption { name: "decimals", ty: "integer", default: "3", description: "coordinate precision, 1–7 decimal places" },
FormatOption { name: "minify", ty: "boolean", default: "false", description: "no XML declaration, indentation or line breaks" },
FormatOption { name: "responsive", ty: "boolean", default: "false", description: "no width/height: the SVG scales to its container" },
FormatOption {
name: "units",
ty: "string",
default: "null",
description: "override the document unit for width and height: px (bare numbers, one per point) | pt | mm | cm | in; omit to follow the document unit, not null (the viewBox stays in points; not with responsive)",
},
FormatOption {
name: "preserveEditing",
ty: "boolean",
@@ -121,7 +127,7 @@ pub fn options_map(p: &Value) -> Result<Map<String, Value>, String> {
let mut m = Map::new();
let Some(o) = p.as_object() else { return Ok(m) };
for opt in OPTIONS.iter().filter(|opt| opt.name != "svg") {
if let Some(v) = o.get(opt.name).filter(|v| !v.is_null()) {
if let Some(v) = o.get(opt.name).filter(|v| opt.name == "units" || !v.is_null()) {
m.insert(opt.name.into(), v.clone());
}
}
@@ -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}));
@@ -1512,3 +1512,39 @@ fn each_piece_writes_its_own_native_document() {
assert!(name.contains(&board), "{name} holds the artboard {board}");
}
}
/// With Include Bleed, a native, `.ai` or EPS file of an artboard holds the artboard grown by the
/// bleed, and no bleed of its own: opened again, a PDF with the document's bleed has the same page
/// as the export's own PDF row, not one grown by the bleed twice. A Full Document file keeps the
/// document's bleed around its art's bounds, which Include Bleed doesn't grow.
#[test]
fn include_bleed_native_files_hold_the_bleed_once() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap();
s.execute("document.setup", &json!({"bleed": 9})).unwrap();
let r = export(&mut s, json!({"includeBleed": true, "artboard": 0, "formats": [{"format": "pdf"}]}));
let [(_, pdf)] = &files(&r)[..] else { panic!("one PDF: {r}") };
let [(media, bleed, ..)] = page_sizes(pdf)[..] else { panic!("one page") };
let reopened = |name: &str, bytes: &[u8]| -> (Session, Vec<PageSizes>) {
let mut t = Session::new();
t.execute("document.open", &json!({"name": name, "dataBase64": vectorcraft_format::base64_encode(bytes)})).unwrap();
let r = t.execute("document.exportPdf", &json!({"bleed": {"useDocument": true}, "preserveEditing": false})).unwrap();
let pages = page_sizes(&b64(&r));
(t, pages)
};
for format in ["vectorcraft", "ai", "eps"] {
let r = export(&mut s, json!({"includeBleed": true, "artboard": 0, "formats": [{"format": format}]}));
let [(name, bytes)] = &files(&r)[..] else { panic!("one {format} file: {r}") };
let (t, pages) = reopened(name, bytes);
let [(m, b, trim, _)] = pages[..] else { panic!("{format}: one page") };
assert_eq!((m, b), (media, bleed), "{format}: the page of the PDF row");
assert_eq!(trim, bleed, "{format}: the artboard holds the bleed");
assert_eq!(t.doc().unwrap().doc.setup.bleed, [0.0; 4], "{format}: no second bleed");
}
// Full Document: the art's bounds, with the document's bleed around them.
let r = export(&mut s, json!({"includeBleed": true, "fullDocument": true, "formats": [{"format": "vectorcraft"}]}));
let [(name, bytes)] = &files(&r)[..] else { panic!("one file: {r}") };
let (t, _) = reopened(name, bytes);
assert_eq!(t.doc().unwrap().doc.setup.bleed, [9.0; 4]);
}
+37
View File
@@ -115,6 +115,10 @@ fn junk_options_are_rejected() {
json!({"svg": "css"}),
json!({"images": "inline"}),
json!({"useArtboards": "yes"}),
json!({"units": "furlong"}),
json!({"units": 7}),
json!({"units": null}),
json!({"svg": {"units": null}}),
] {
let mut q = p.clone();
q["format"] = json!("svg");
@@ -124,6 +128,39 @@ fn junk_options_are_rejected() {
assert!(s.execute("document.export", &json!({"format": "png", "styling": "fancy"})).is_ok());
}
/// #4462: width and height carry the chosen unit (the document is 200 × 100 pt, the viewBox stays
/// in points), px is today's bare numbers, and Responsive leaves the size out whatever the unit.
#[test]
fn svg_export_writes_width_height_with_the_requested_unit() {
let mut s = session(1);
let plain = svg(&mut s, json!({}));
assert!(plain.contains(" width=\"200\" height=\"100\" viewBox=\"0 0 200 100\""), "{plain}");
assert_eq!(svg(&mut s, json!({"units": "px"})), plain, "px keeps bare point coordinates");
for unit in ["mm", "cm", "in", "pt"] {
for decimals in [1, 3] {
for p in [json!({"units": unit, "decimals": decimals}), json!({"svg": {"units": unit, "decimals": decimals}})] {
let out = svg(&mut s, p);
assert!(out.contains(&format!("{unit}\"")) && out.contains("viewBox=\"0 0 200 100\""), "{unit}:\n{out}");
let back = vectorcraft_svg::import(&out).unwrap();
let rect = back.artboards[0].rect;
assert!((rect.width() - 200.0).abs() < 0.001 && (rect.height() - 100.0).abs() < 0.001, "{unit}: {rect:?}\n{out}");
}
}
}
let out = svg(&mut s, json!({"units": "mm", "responsive": true}));
assert!(!out.contains("mm\"") && !out.contains("height=\"100\" viewBox") && out.contains("viewBox=\"0 0 200 100\""), "{out}");
assert!(svg(&mut s, json!({"units": "mm", "decimals": 1})).contains("x=\"10.1\""), "coordinate precision is unchanged");
// Omitted units retain main's document-unit save behavior, including serialized defaults.
s.execute("document.setUnits", &json!({"units": "millimeters"})).unwrap();
let defaults = serde_json::to_value(vectorcraft_svg::ExportOptions::default()).unwrap();
assert!(svg(&mut s, json!({"svg": defaults})).contains("mm\""));
for p in [json!({"units": "px"}), json!({"svg": {"units": "px"}})] {
assert_eq!(svg(&mut s, p), plain, "explicit pixels override physical document units");
}
assert_eq!(svg(&mut s, json!({"units": "mm", "svg": {"units": "px"}})), plain, "nested units override flat units");
assert_eq!(svg(&mut s, json!({"units": null, "svg": {"units": "px"}})), plain, "nested units override flat null");
}
#[test]
fn several_artboards_write_one_file_each() {
let mut s = session(3);
+2 -2
View File
@@ -135,7 +135,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Placement Options",
[],
None,
"{ids?: [image or placed document ids] (default: the selected ones), preserve?: transforms|bounds (default)|fileDimensions|fit|fill, align?: topLeft|top|topRight|left|center (default)|right|bottomLeft|bottom|bottomRight (where the new art sits; not for bounds), clip?: false (clip it to the old bounds where it is larger)} how a file read again (links.relink, links.update) takes each image's place: transforms keeps its scale (relative to each file's 100% size), rotation and position; bounds stretches it into the old bounds; fileDimensions puts it at 100%, unrotated; fit and fill scale it proportionally to fit inside or cover the old bounds. Without options → {placement} of the first image; else one undo step → {ids, placement}",
"{ids?: [image or placed document ids] (default: the selected ones), preserve?: transforms|bounds (default)|fileDimensions|fit|fill, align?: topLeft|top|topRight|left|center (default)|right|bottomLeft|bottom|bottomRight (where the new art sits; not for bounds), clip?: false (clip it to the old bounds where it is larger)} how a file read again (links.relink, links.update) takes each image's place: transforms keeps its scale (relative to each file's 100% size), rotation and position; bounds stretches it into the old bounds; fileDimensions puts it at 100%, unrotated; fit and fill scale it proportionally to fit inside or cover the old bounds. Without options → {ids, placement} (the images read, and the placement of the first); else one undo step → {ids, placement}",
has_doc,
placement_options
),
@@ -3230,7 +3230,7 @@ fn placement_options(s: &mut Session, p: &Value) -> Result<Value> {
let first = ids.first().and_then(|id| placement_of(&doc, *id)).unwrap_or_default();
drop(doc);
if preserve.is_none() && align.is_none() && clip.is_none() {
return Ok(json!({ "placement": placement_json(first) }));
return Ok(json!({ "ids": ids_json(&ids), "placement": placement_json(first) }));
}
let set = |o: &mut PlacementOptions| {
o.preserve = preserve.unwrap_or(o.preserve);
+28 -21
View File
@@ -299,7 +299,11 @@ impl DocSettings {
}
/// These settings with `p`'s changes (the params of `file.new`) → validated.
pub fn with_params(mut self, p: &Value, cmd: &str) -> Result<Self> {
pub fn with_params(self, p: &Value, cmd: &str) -> Result<Self> {
self.with_params_inner(p, cmd, false)
}
fn with_params_inner(mut self, p: &Value, cmd: &str, replaying: bool) -> Result<Self> {
if let Some(u) = p.get("units").filter(|v| !v.is_null()) {
let u = u.as_str().unwrap_or("");
self.units = Unit::named(u).ok_or_else(|| bad(cmd, format!("unknown units `{u}`")))?;
@@ -329,11 +333,11 @@ impl DocSettings {
Some(o) => return Err(bad(cmd, format!("orientation must be portrait or landscape, not `{o}`"))),
}
if let Some(n) = p.get("artboards").filter(|v| !v.is_null()) {
let n = n.as_f64().filter(|n| n.is_finite()).ok_or_else(|| bad(cmd, "artboards must be a number"))?;
self.artboards = n.round().clamp(1.0, MAX_ARTBOARDS as f64) as u32;
self.artboards = if replaying { n.as_f64().map(|n| n.round().clamp(1.0, f64::from(MAX_ARTBOARDS)) as u32) } else { count(n) }
.ok_or_else(|| bad(cmd, format!("artboards must be a whole number from 1 to {MAX_ARTBOARDS}")))?;
}
if let Some(l) = p.get("artboardLayout").filter(|v| !v.is_null()) {
self.layout_params(l, cmd)?;
self.layout_params(l, cmd, replaying)?;
}
if let Some(b) = p.get("bleed").filter(|v| !v.is_null()) {
self.bleed = super::docsetup::bleed_param(b, self.bleed, cmd)?;
@@ -371,7 +375,7 @@ impl DocSettings {
}
/// `artboardLayout: {layout?, columns?, rows?, spacing?, rightToLeft?}` or just a layout id.
fn layout_params(&mut self, l: &Value, cmd: &str) -> Result<()> {
fn layout_params(&mut self, l: &Value, cmd: &str, replaying: bool) -> Result<()> {
let bad_layout = || bad(cmd, "artboardLayout.layout must be gridByRow, gridByColumn, row or column");
if let Some(id) = l.as_str() {
self.layout = ArtboardLayout::parse(id).ok_or_else(bad_layout)?;
@@ -380,25 +384,22 @@ impl DocSettings {
}
return Ok(());
}
let o = l.as_object().ok_or_else(|| bad(cmd, "artboardLayout must be {layout?, columns?, spacing?, rightToLeft?}"))?;
let o = l.as_object().ok_or_else(|| bad(cmd, "artboardLayout must be {layout?, columns?, rows?, spacing?, rightToLeft?}"))?;
for (k, v) in o {
match k.as_str() {
"layout" => self.layout = v.as_str().and_then(ArtboardLayout::parse).ok_or_else(bad_layout)?,
"columns" => {
self.columns = v
.as_f64()
.filter(|c| c.is_finite() && *c >= 1.0)
.ok_or_else(|| bad(cmd, "artboardLayout.columns must be 1 or more"))?
.round()
.min(MAX_ARTBOARDS as f64) as u32
self.columns =
if replaying { v.as_f64().filter(|n| *n >= 1.0).map(|n| n.round().min(f64::from(MAX_ARTBOARDS)) as u32) } else { count(v) }
.ok_or_else(|| bad(cmd, format!("artboardLayout.columns must be a whole number from 1 to {MAX_ARTBOARDS}")))?
}
"rows" => {
self.rows = v
.as_f64()
.map(f64::round)
.filter(|r| (1.0..=MAX_ARTBOARDS as f64).contains(r))
.map(|r| r as u32)
.ok_or_else(|| bad(cmd, format!("artboardLayout.rows must be from 1 to {MAX_ARTBOARDS}")))?
self.rows = if replaying {
v.as_f64().map(f64::round).filter(|n| (1.0..=f64::from(MAX_ARTBOARDS)).contains(n)).map(|n| n as u32)
} else {
count(v)
}
.ok_or_else(|| bad(cmd, format!("artboardLayout.rows must be a whole number from 1 to {MAX_ARTBOARDS}")))?
}
"spacing" => {
self.spacing = v
@@ -407,7 +408,7 @@ impl DocSettings {
.ok_or_else(|| bad(cmd, format!("artboardLayout.spacing must be 0–{MAX_SPACING} pt")))?
}
"rightToLeft" => self.right_to_left = v.as_bool().ok_or_else(|| bad(cmd, "artboardLayout.rightToLeft must be true or false"))?,
_ => return Err(bad(cmd, format!("unknown artboardLayout key `{k}` (layout, columns, spacing, rightToLeft)"))),
_ => return Err(bad(cmd, format!("unknown artboardLayout key `{k}` (layout, columns, rows, spacing, rightToLeft)"))),
}
}
if o.contains_key("rows") && self.layout != ArtboardLayout::GridByColumn {
@@ -610,6 +611,12 @@ fn de_rows<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result<u32, D
Ok(u32::deserialize(d)?.min(MAX_ARTBOARDS))
}
/// A count `file.new` takes (artboards, columns, rows): a whole number, written `4` or `4.0`, from 1
/// to [`MAX_ARTBOARDS`]; anything else is `None`.
fn count(v: &Value) -> Option<u32> {
v.as_f64().filter(|n| n.fract() == 0.0 && (1.0..=f64::from(MAX_ARTBOARDS)).contains(n)).map(|n| n as u32)
}
/// A saved or Recent preset's artboard spacing, kept to 0 to [`MAX_SPACING`] points.
fn de_spacing<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result<f64, D::Error> {
Ok(f64::deserialize(d)?.clamp(0.0, MAX_SPACING))
@@ -871,7 +878,7 @@ pub(crate) fn file_new(s: &mut Session, p: &Value) -> Result<Value> {
// A preset keeps its name in Recent unless its size changed (turning it doesn't count).
let sorted = |d: &DocSettings| (d.width.min(d.height), d.width.max(d.height), d.units);
let size = str_param(p, "preset").map(|_| sorted(&base));
let mut settings = base.with_params(p, C)?;
let mut settings = base.with_params_inner(p, C, s.replaying())?;
if size != Some(sorted(&settings)) {
settings.name = "Custom".into();
}
@@ -956,7 +963,7 @@ fn save(s: &mut Session, p: &Value) -> Result<Value> {
Some(from) => find(s, from).ok_or_else(|| bad(C, format!("no preset called `{from}` (see file.newPresets)")))?,
None => s.default_settings(),
};
let mut preset = base.with_params(p, C)?;
let mut preset = base.with_params_inner(p, C, s.replaying())?;
preset.name = name.to_string();
let saved = &mut s.prefs.new_doc_presets;
match saved.iter_mut().find(|q| q.name.eq_ignore_ascii_case(name)) {
+5 -5
View File
@@ -388,6 +388,7 @@ const EXCLUSIVE_KEYS: &[(&str, &str, &str)] = &[
("addon.pathtools.cornerSet", "items", "ids"),
("addon.pathtools.cornerRemove", "items", "ids"),
("addon.pathtools.bridge", "radius", "gap"),
("addon.pathtools.commonTangents", "radius", "gap"),
("links.unembed", "id", "ids"),
("links.unembed", "path", "folder"),
];
@@ -956,11 +957,10 @@ fn option_trees() -> Value {
let mut trees = pdf_option_tree();
if let Some(tree) = trees.as_object_mut() {
tree.insert("flattener".into(), serde_json::to_value(super::flatten::FlattenOptions::default()).unwrap_or_default());
let mut svg = serde_json::to_value(vectorcraft_svg::ExportOptions::default()).unwrap_or_default();
if let Some(svg) = svg.as_object_mut() {
svg.extend(super::fileio::ARTBOARD_PARAMS.iter().chain(&["useArtboards"]).map(|k| (k.to_string(), Value::Null)));
}
tree.insert("svg".into(), svg);
// Serialized defaults omit optional overrides such as units; the registry lists every key.
let svg = super::fileio::FORMATS.iter().find(|f| f.id == "svg").into_iter().flat_map(|f| f.options);
let svg = svg.filter(|o| o.name != "svg").map(|o| (o.name.to_string(), Value::Null)).collect();
tree.insert("svg".into(), Value::Object(svg));
}
trees
}
+3 -2
View File
@@ -63,7 +63,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Divide",
["Window", "Pathfinder"],
None,
"{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids}",
"{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front). When open paths are among them, the command stops with an error and leaves the art unchanged if the paths are too many or too complex to map. This happens when the paths it maps, as it prepares them from the selection, have more than 65,536 segments, have more than 131,072 pieces once cut where they meet, or exceed the sweep's work budget, which counts pairs of segments with overlapping bounds. → {ids}",
has_selection,
|s, p| run_pf(s, p, PathfinderOp::Divide)
),
@@ -823,7 +823,8 @@ fn run_pf(s: &mut Session, p: &Value, op: PathfinderOp) -> Result<Value> {
if shapes.iter().any(|s| s.path.subpaths.iter().any(|sp| sp.anchors.iter().any(|a| !(a.p.x.is_finite() && a.p.y.is_finite())))) {
return Err(EngineError::Other("paths contain invalid coordinates".into()));
}
let mut results = po::pathfinder_with(op, &shapes, options.precision);
let mut results = po::try_pathfinder_with(op, &shapes, options.precision)
.map_err(|e| EngineError::Other(format!("{label}: {e} to cut with the open paths; select fewer paths")))?;
if options.remove_unpainted && matches!(op, PathfinderOp::Divide | PathfinderOp::Outline) {
// Pathfinder Options › Divide and Outline Will Remove Unpainted Artwork: the pieces
// of objects with no fill (or only hidden ones) go.
+37 -10
View File
@@ -12,7 +12,7 @@ use vectorcraft_pdf::{PrintLayers, PrintOptions, PrintPreview, PrintSettings};
use super::fileio::pdf::{merge, pdf_error};
use super::fileio::{extension, write_or_return};
use super::flatten::has_transparent_tile_images;
use super::{CommandSpec, EngineError, Result, Session, bad, bool_or, cmd, has_doc, str_param};
use super::{CommandSpec, EngineError, Result, Session, bad, bool_or, cmd, has_doc, str_param, u64_req};
const SETUP: &str = "print.setup";
@@ -41,7 +41,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Print",
[],
Some("Cmd+P"),
"{preset?: name (as print.setup's: its settings instead of the document's; the saved settings stay), settings?: {…settings of print.setup} (over the document's or the preset's), includeArtboardFill?: true (each artboard's background color prints behind its art; false leaves it out), path?, format?: pdf (default: a print-ready PDF) | postscript (the default for a .ps path: a PostScript file with DSC comments, %%Pages, a page per sheet with its paper size, marks, separations with their ink and halftone screen, the fixed flatness, negatives), level?: 3|2 (the PostScript language level), flattenerPreset?: \"medium\" (PostScript: the preset transparency is flattened with — high, low or a saved one, see flattener.presets.list), acknowledgeLoss?: bool (with path: write over the file the document was read from although reading it left things out), forPrinter?: bool (the PDF goes to a print queue: a page whose paper is turned to landscape is written upright, the art turned a quarter anticlockwise, as a printer driver turns a landscape job; macOS prints a landscape page as it is, cut off on upright paper; paper wide in Portrait and transverse pages stay as they are)} print the document, one page per sheet of paper (per tile, per ink, per copy; with copiesPerSheet, a sheet holds as many copies of an artboard as fit) → {pages, format, path, bytes, warnings}; no path → {dataBase64, bytes, pages, format, warnings}. Raster effects print at the document's raster effects resolution; a PDF leaves halftone screens and flatness to the output device",
"{preset?: name (as print.setup's: its settings instead of the document's; the saved settings stay), settings?: {…settings of print.setup} (over the document's or the preset's), includeArtboardFill?: true (each artboard's background color prints behind its art; false leaves it out), path?, format?: pdf (default: a print-ready PDF) | postscript (the default for a .ps path: a PostScript file with DSC comments, %%Pages, a page per sheet with its paper size, marks, separations with their ink and halftone screen, the fixed flatness, negatives), level?: 3|2 (the PostScript language level), flattenerPreset?: \"medium\" (PostScript: the preset transparency is flattened with — high, low or a saved one, see flattener.presets.list), acknowledgeLoss?: bool (with path: write over the file the document was read from although reading it left things out), maxPages?: n (a whole number: the job is composed only when it prints at most n pages, copies counted; with more, nothing is composed or written and the reply is {pages, format}), forPrinter?: bool (the PDF goes to a print queue: a page whose paper is turned to landscape is written upright, the art turned a quarter anticlockwise, as a printer driver turns a landscape job; macOS prints a landscape page as it is, cut off on upright paper; paper wide in Portrait and transverse pages stay as they are)} print the document, one page per sheet of paper (per tile, per ink, per copy; with copiesPerSheet, a sheet holds as many copies of an artboard as fit) → {pages, format, path, bytes, warnings}; no path → {dataBase64, bytes, pages, format, warnings}. Raster effects print at the document's raster effects resolution; a PDF leaves halftone screens and flatness to the output device",
has_doc,
print
),
@@ -222,6 +222,11 @@ fn print(s: &mut Session, p: &Value) -> Result<Value> {
super::fileio::check_not_lossy_overwrite(s.doc()?, path, p, PRINT)?;
}
let postscript = to_postscript(p)?;
let max_pages = match p.get("maxPages") {
None => None,
Some(_) => Some(u64_req(p, "maxPages", PRINT)?),
};
let too_many = |pages: usize| max_pages.is_some_and(|m| pages as u64 > m);
let doc = &s.doc()?.doc;
let mut set = preset_or_saved(PRINT, s, doc, p)?;
if postscript {
@@ -244,6 +249,27 @@ fn print(s: &mut Session, p: &Value) -> Result<Value> {
&& !bitmap
&& super::printadvanced::flattener(PRINT, &set, &s.prefs.flattener_presets)?
.is_some_and(|o| has_transparent_tile_images(&vectorcraft_pdf::printed_document(doc, &set), &o));
let level = match p.get("level").filter(|v| postscript && !v.is_null()) {
Some(v) => {
let t = super::fileio::dxf::text(v);
Level::from_id(&t).ok_or_else(|| bad(PRINT, format!("level `{t}`: 2 or 3")))?
}
None => Level::default(),
};
// A job past `maxPages` is turned away before Print as Bitmap or a flattener preset prepares it,
// once the options are checked, when its pages follow from the artboards alone (composite, no
// `skipBlank`, artboards not ignored); the pages are counted again on the prepared art.
super::printadvanced::flattener(PRINT, &set, &s.prefs.flattener_presets)?;
let by_artboards = !set.skip_blank
&& !matches!(set.artboards, vectorcraft_pdf::PrintArtboards::Ignore)
&& set.output.mode == vectorcraft_pdf::OutputMode::Composite;
if max_pages.is_some()
&& by_artboards
&& let Ok(pv) = vectorcraft_pdf::preview(doc, &set)
&& too_many(pv.pages)
{
return Ok(json!({ "pages": pv.pages, "format": if postscript { "postscript" } else { "pdf" } }));
}
// Print as Bitmap and the flattener preset (Advanced) render and flatten it first.
let prepared = super::printadvanced::prepare(PRINT, doc, &set, &s.prefs.flattener_presets, s.prefs.black_output == "rich")?;
let path = str_param(p, "path");
@@ -251,7 +277,12 @@ fn print(s: &mut Session, p: &Value) -> Result<Value> {
let which = set.print_layers;
if !postscript {
let printed = prepared.as_ref().unwrap_or(doc);
let typed = type_warnings(&full, which, &areas(&vectorcraft_pdf::preview(printed, &set).map_err(|e| pdf_error(PRINT, e))?));
let laid_out = vectorcraft_pdf::preview(printed, &set).map_err(|e| pdf_error(PRINT, e))?;
// `maxPages` is checked on the art as it prints, before the job is composed.
if too_many(laid_out.pages) {
return Ok(json!({ "pages": laid_out.pages, "format": "pdf" }));
}
let typed = type_warnings(&full, which, &areas(&laid_out));
let mut r =
vectorcraft_pdf::print(printed, &PrintOptions { settings: set, for_printer: bool_or(p, "forPrinter", false), ..Default::default() })
.map_err(|e| pdf_error(PRINT, e))?;
@@ -260,13 +291,6 @@ fn print(s: &mut Session, p: &Value) -> Result<Value> {
r.warnings.extend(r.setting_notes);
return write_or_return(path, &r.bytes, json!({ "pages": r.pages, "format": "pdf", "warnings": r.warnings }));
}
let level = match p.get("level").filter(|v| !v.is_null()) {
Some(v) => {
let t = super::fileio::dxf::text(v);
Level::from_id(&t).ok_or_else(|| bad(PRINT, format!("level `{t}`: 2 or 3")))?
}
None => Level::default(),
};
// What the job loses, then the notes on the options: a reply lists them in that order.
let (mut warnings, mut setting_notes) = (vec![], vec![]);
if !bitmap && (tile_images || doc.layers.iter().any(|l| l.shows_transparency())) {
@@ -283,6 +307,9 @@ fn print(s: &mut Session, p: &Value) -> Result<Value> {
};
let plan = vectorcraft_pdf::plan(prepared.as_ref().unwrap_or(doc), &PrintOptions { settings: set, postscript: true, ..Default::default() })
.map_err(|e| pdf_error(PRINT, e))?;
if too_many(plan.order.len()) {
return Ok(json!({ "pages": plan.order.len(), "format": "postscript" }));
}
let pages: Vec<PrintPage> = plan
.sheets
.iter()
+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)
+11
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;
@@ -383,6 +384,16 @@ pub struct Session {
pub(crate) script_style_trail: script::StyleTrail,
/// While a slice of a script runs in this session.
pub(crate) script_in_run: bool,
/// The one command a member of the script object model runs past
/// [`script::refused_to_scripts`] while it is set: `file.print` for `Document.print`, after the
/// member checked its options and its file.
pub(crate) script_unfenced: Option<&'static str>,
/// The printers the frontend lists for the next run, which takes them: `app.printerList` and
/// `Document.print` to a printer read them. `None`: scripts cannot print to a printer here.
pub script_printers: Option<script::printing::Printers>,
/// The jobs the last run that printed to a printer prepared, until the frontend takes them
/// ([`Session::take_script_prints`]).
pub(crate) script_prints: Vec<script::printing::PreparedPrint>,
/// The desktop app supplies each window by (document uid, runtime window identity) while a
/// script runs. Scripts read them as `Document.views`, and the app applies their zoom, center,
/// and screen mode. This list is empty without windows (headless).
+20 -3
View File
@@ -94,9 +94,10 @@ use vectorcraft_js::{
ArgInfo, Data, HostClass, HostError, HostFunction, HostItem, HostMember, MemberInfo, Realm, RunError, host_ref, host_ref_parts,
};
use super::{HISTORY_LOST, Host, Link, Savepoint, command, command_value, current, data_size};
use super::{HISTORY_LOST, Host, Link, Savepoint, command, command_kept, command_value, current, data_size};
use crate::{DocState, Document, NodeId, NodeKind, Session, WindowView};
mod print;
mod save_open;
mod tags;
mod text;
@@ -209,6 +210,8 @@ pub(super) struct State {
saving: Cell<bool>,
/// `app.userInteractionLevel` ([`save_open`]).
save_options: save_open::State,
/// The print option objects ([`print`]).
printing: print::State,
text: text::TextState,
presets: RefCell<Vec<Vec<(String, Data)>>>,
preset_bytes: Cell<u64>,
@@ -228,6 +231,17 @@ impl State {
self.saving.get()
}
/// Gives the run the printers the frontend listed (`None`: none can be printed to here), and
/// whether jobs an earlier run prepared still wait.
pub(super) fn start_printing(&self, printers: Option<super::printing::Printers>, waiting: bool) {
self.printing.start(printers, waiting);
}
/// The jobs the run prepared for a printer, which the run no longer holds.
pub(super) fn take_prints(&self) -> Vec<super::printing::PreparedPrint> {
self.printing.take_jobs()
}
/// The id of the tool `app.selectTool` chose last in the run, which becomes the current tool
/// when the run ends without an error.
pub(super) fn chosen_tool(&self) -> Option<&'static str> {
@@ -2968,7 +2982,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.iter().chain(save_open::ENUMS) {
for (name, members) in ENUMS.iter().chain(save_open::ENUMS).chain(print::ENUMS) {
let items = members.iter().map(|m| (m.to_string(), HostItem::Value(text(format!("{name}.{m}"))))).collect();
realm.define_host_object(name, items)?;
}
@@ -3007,6 +3021,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(print::application_members(l));
application.extend(super::actions::app_members(l));
let preset = {
let l = link.clone();
@@ -3086,8 +3101,9 @@ fn classes(link: &Link) -> Vec<HostClass> {
document.extend(defaults::document_members(l));
document.extend(text::styles::doc_members(l));
document.extend(["layers", "artboards", "groupItems", "swatches", "symbols", "activeLayer"].into_iter().map(|m| later(l, "Document", m)));
document.extend(save_open::document_members(l));
document.extend(variables::document_members(l));
document.extend(save_open::document_members(l));
document.extend(print::document_members(l));
document.push(("tags".into(), get(l, tags::doc_tags), MemberInfo { collection: true, ..typed("Tags") }));
classes.push(class("Document", None, document, None));
classes.push(class(
@@ -3198,6 +3214,7 @@ fn classes(link: &Link) -> Vec<HostClass> {
classes.extend(text::classes(l));
classes.extend(variables::classes(l));
classes.extend(save_open::classes(l));
classes.extend(print::classes(l));
classes.push(class(
"Layer",
None,
File diff suppressed because it is too large. Load diff
+4 -4
View File
@@ -717,18 +717,18 @@ fn typename(d: &Data) -> Option<&str> {
// ---- Files ----
/// The path of the `File` argument `d`, or a `TypeError` naming the method.
fn file_path<'a>(d: &'a Data, method: &str) -> std::result::Result<&'a str, HostError> {
pub(super) fn file_path<'a>(d: &'a Data, method: &str) -> std::result::Result<&'a str, HostError> {
vectorcraft_js::file_ref_path(d).ok_or_else(|| HostError::Type(format!("{method} needs a File")))
}
/// The error a refused path throws: the `File` error and the path.
fn refused(message: &str, path: &str) -> HostError {
pub(super) fn refused(message: &str, path: &str) -> HostError {
HostError::Error(format!("{message}: {path}"))
}
/// Runs `f` with the commands' reads and writes held to the script's own grants
/// ([`super::super::files::Disk::exact`]).
fn exactly(h: &Host, f: impl FnOnce() -> Answer) -> Answer {
pub(super) fn exactly(h: &Host, f: impl FnOnce() -> Answer) -> Answer {
h.disk.borrow_mut().exact = true;
let r = f();
h.disk.borrow_mut().exact = false;
@@ -747,7 +747,7 @@ fn warned(h: &Host, method: &str, id: &str, p: &Value) -> Answer {
}
/// The path to give a command for the real path `real`, or an error when it is not valid UTF-8.
fn plain(real: std::path::PathBuf) -> std::result::Result<String, HostError> {
pub(super) fn plain(real: std::path::PathBuf) -> std::result::Result<String, HostError> {
crate::cmd::findfiles::plain(real).into_os_string().into_string().map_err(|_| HostError::Error("Script file path is not valid UTF-8".into()))
}
+49 -1
View File
@@ -47,6 +47,10 @@
//! run. An engine keeps no document and no run: its host functions reach the run through a link
//! that holds the run's host only while the run goes on. An error, a limit or a stop puts the
//! documents back and keeps the engine's globals; an internal error drops the engine.
//!
//! `Document.print` to a printer prepares its job in memory; the session holds the jobs of a run
//! only after the run's changes are kept, for the frontend to send once the person approves them
//! ([`printing`]).
pub mod actions;
pub mod console;
@@ -54,6 +58,7 @@ pub mod dialogs;
pub mod dollar;
pub mod dom;
pub mod include;
pub mod printing;
pub mod scriptui;
pub use dialogs::{DialogAnswer, DialogKind, ScriptDialog};
@@ -1405,6 +1410,17 @@ fn command(host: &Host, id: &str, params: &Value) -> std::result::Result<Data, H
/// [`command`], with the command's result as it gave it as well as the script's copy of it.
fn command_value(host: &Host, id: &str, params: &Value) -> std::result::Result<(Data, Value), HostError> {
command_crossing(host, id, params, true).map(|(data, value)| (data.unwrap_or(Data::Undefined), value))
}
/// [`command`] for a member that keeps the command's result itself: the result does not cross to
/// the script, so it is not held to the limits of a crossing. → the result as the command gave it.
fn command_kept(host: &Host, id: &str, params: &Value) -> std::result::Result<Value, HostError> {
command_crossing(host, id, params, false).map(|(_, value)| value)
}
/// [`command_value`], with the script's copy of the result made only when `cross` is true.
fn command_crossing(host: &Host, id: &str, params: &Value, cross: bool) -> std::result::Result<(Option<Data>, Value), HostError> {
// Point changes that wait in the object model are written before any command runs.
dom::flush(host)?;
let session = host.session.clone();
@@ -1430,10 +1446,13 @@ fn command_value(host: &Host, id: &str, params: &Value) -> std::result::Result<(
};
let mark = host.growth_mark();
let crossed = host.charge_growth(objects, added).and_then(|()| {
if !cross {
return Ok(None);
}
let data = to_data(&value, &result_limits(), 0, &mut (0, 0))
.map_err(|place| HostError::Range(format!("vc.run: the result{place} is too large for a script")))?;
host.charge_call(data_size(&data))?;
Ok(data)
Ok(Some(data))
});
// A command whose result does not reach the script is put back, like one that failed, and so is
// the growth it was charged.
@@ -1985,6 +2004,22 @@ impl Session {
self.script_report.as_ref()
}
/// Whether jobs a run prepared for a printer wait to be sent or dropped ([`printing`]).
pub fn script_prints_waiting(&self) -> bool {
!self.script_prints.is_empty()
}
/// The jobs that wait, as [`Self::take_script_prints`] would give them.
pub fn script_prints(&self) -> &[printing::PreparedPrint] {
&self.script_prints
}
/// The jobs the last run that printed to a printer prepared, which the session no longer holds:
/// the frontend sends them or drops them ([`printing`]).
pub fn take_script_prints(&mut self) -> Vec<printing::PreparedPrint> {
std::mem::take(&mut self.script_prints)
}
/// The Script Console: the lines of this session's runs, oldest first.
pub fn script_console(&self) -> &console::Console {
&self.script_console
@@ -2344,6 +2379,9 @@ impl Session {
),
linked: std::cell::OnceCell::new(),
});
// The printers the frontend listed are this run's alone, and a run may not print while
// jobs an earlier run prepared still wait for the person.
host.dom.start_printing(self.script_printers.take(), !self.script_prints.is_empty());
*link.borrow_mut() = Some(host.clone());
let args = match to_data(&Value::Object(request.args), &DataLimits::default(), 0, &mut (0, 0)) {
Ok(args) => args,
@@ -2641,6 +2679,12 @@ impl Session {
"hostCalls": host.calls.get(),
});
host.more_written(&mut report);
// The jobs it prepared for a printer wait for the frontend now that its changes are kept.
let prints = host.dom.take_prints();
if !prints.is_empty() {
report["prints"] = json!(prints.len());
self.script_prints = prints;
}
let rejections = rejections_report(host, &job.realm);
if let (false, Some(o)) = (rejections.is_empty(), report.as_object_mut()) {
o.insert("unhandledRejections".into(), Value::Array(rejections));
@@ -2894,6 +2938,8 @@ fn run_slice(s: &mut Session, job: &mut Job) -> std::result::Result<std::result:
}
std::mem::swap(s, &mut *cell.borrow_mut());
s.script_in_run = false;
// A panic in a member that opened the fence for one command skips its own reset.
s.script_unfenced = None;
job.world.swap(s);
s.depth = depth;
s.sync_front_profiles();
@@ -2960,6 +3006,8 @@ thread_local! {
pub(crate) static TEST_RESULT_BYTES: Cell<Option<usize>> = const { Cell::new(None) };
/// Tests: makes the next slice panic.
pub(crate) static PANIC_IN_SLICE: Cell<bool> = const { Cell::new(false) };
/// Tests: makes the next command a member runs past the script fence panic before it runs.
pub(crate) static PANIC_WHILE_UNFENCED: Cell<bool> = const { Cell::new(false) };
/// Tests: the objects a run may add in place of [`GROWTH_OBJECTS`].
pub(crate) static TEST_GROWTH: Cell<Option<u64>> = const { Cell::new(None) };
/// Tests: the bytes a run may keep in place of [`GROWTH_BYTES`].
+101
View File
@@ -0,0 +1,101 @@
//! Printing to a printer from a script: the printers a frontend lists for a run ([`Printers`]),
//! which `app.printerList` and `PrintOptions.printerName` read, and the jobs `Document.print`
//! prepares ([`PreparedPrint`]).
//!
//! A run that prints to a printer sends nothing while it runs: each job is composed in memory and
//! kept with the run. When the run fails or is stopped, its jobs are dropped with its changes. When
//! it ends and its changes are kept, the session holds its jobs ([`crate::Session::take_script_prints`])
//! for the frontend, which sends them only when the person at the computer approves them.
//!
//! A printer name is only a key into the list the frontend gave: it never becomes a path, a URL or
//! a command line.
//!
//! The limits are VectorCraft's own: [`MAX_PRINTERS`], [`MAX_PRINTER_NAME_BYTES`], [`MAX_JOBS`],
//! [`MAX_SHEETS`] and [`MAX_JOB_BYTES`].
/// The most printers a run lists.
pub const MAX_PRINTERS: usize = 256;
/// The longest printer name a run lists, in bytes.
pub const MAX_PRINTER_NAME_BYTES: usize = 512;
/// The most printer jobs one run prepares.
pub const MAX_JOBS: usize = 4;
/// The most sheets of paper the jobs of one run hold together, every copy counted.
pub const MAX_SHEETS: u64 = 100;
/// The most bytes the jobs of one run hold together.
pub const MAX_JOB_BYTES: usize = 32 << 20;
/// The printers a frontend lists for a run, by name, with the system's default printer.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Printers {
names: Vec<String>,
default: Option<usize>,
/// The printer turns no landscape page to fit its paper: jobs are written upright
/// (`file.print`'s `forPrinter`).
pub for_printer: bool,
}
impl Printers {
/// The printers of `list` (name, whether it is the default), in its order. A name that is
/// empty, longer than [`MAX_PRINTER_NAME_BYTES`] or holds a control character is left out, and
/// so is a name that repeats an earlier one, though its default mark is kept. Every printer
/// after the first [`MAX_PRINTERS`] is left out, except the default printer, which takes the
/// last place when it comes later.
pub fn new(list: impl IntoIterator<Item = (String, bool)>, for_printer: bool) -> Self {
let mut names: Vec<String> = Vec::new();
let mut default = None;
for (name, is_default) in list {
let full = names.len() >= MAX_PRINTERS;
if full && default.is_some() {
break;
}
if name.is_empty() || name.len() > MAX_PRINTER_NAME_BYTES || name.chars().any(char::is_control) {
continue;
}
if let Some(i) = names.iter().position(|n| *n == name) {
if is_default && default.is_none() {
default = Some(i);
}
continue;
}
if full {
if is_default && let Some(last) = names.last_mut() {
*last = name;
default = Some(MAX_PRINTERS - 1);
}
continue;
}
if is_default && default.is_none() {
default = Some(names.len());
}
names.push(name);
}
Self { names, default, for_printer }
}
/// The printers' names.
pub fn names(&self) -> &[String] {
&self.names
}
/// The system's default printer, when the list holds it.
pub fn default_name(&self) -> Option<&str> {
self.default.map(|i| self.names[i].as_str())
}
/// Whether the list holds a printer named exactly `name`.
pub fn has(&self, name: &str) -> bool {
self.names.iter().any(|n| n == name)
}
}
/// A job a run prepared for a printer: a print-ready PDF, every copy in it.
#[derive(Clone, Debug, PartialEq)]
pub struct PreparedPrint {
/// The printer, by the name the run's list gave it.
pub printer: String,
/// The title of the document it prints, the job's name in the print queue.
pub title: String,
pub pdf: Vec<u8>,
/// The sheets of paper it prints, every copy counted.
pub sheets: u64,
}
+3
View File
@@ -192,6 +192,9 @@ impl Session {
script_high_water: Default::default(),
script_style_trail: Default::default(),
script_in_run: false,
script_unfenced: None,
script_printers: None,
script_prints: Vec::new(),
window_views: vec![],
script_copy_first: cfg!(target_arch = "wasm32"),
}
+1 -1
View File
@@ -104,7 +104,7 @@ impl Session {
return Err(EngineError::PluginBusy);
}
// A step of a batch a script runs is held to the same rule as the script's own commands.
if self.script_in_run && crate::script::refused_to_scripts(id) {
if self.script_in_run && crate::script::refused_to_scripts(id) && self.script_unfenced != Some(id) {
return Err(EngineError::Other(crate::script::refused_text(id)));
}
// An edit the active tool is computing on another thread (a Shape Builder merge) is
+1
View File
@@ -190,6 +190,7 @@ mod script_folder;
mod script_include;
mod script_io;
mod script_modules;
mod script_print;
mod script_run;
mod script_save_open;
mod script_scriptui;
+24 -4
View File
@@ -1160,9 +1160,10 @@ fn a_blend_mode_over_art_of_several_colors_has_no_one_answer() {
assert!((ratio(&r) - 21.0).abs() < 1e-3, "white minus white is black: {r}");
}
/// A Difference square over a white square in a 50 % group that isolates its blending, over the
/// edge between black and white art: the square blends only with the white inside the group, so
/// A Difference square over a 50 % white square in a 50 % group that isolates its blending, over
/// the edge between black and white art: the square blends only with the white inside the group, so
/// the art of two colors outside it, which the group draws over in Normal mode, leaves one answer.
/// Without isolation the blend also reaches that art, and there is no one answer.
#[test]
fn a_blend_mode_inside_an_isolating_group_answers_over_art_of_several_colors() {
let mut s = session();
@@ -1177,14 +1178,33 @@ fn a_blend_mode_inside_an_isolating_group_answers_over_art_of_several_colors() {
let back = id(s.execute("shape.rectangle", &json!({"x": 60, "y": 60, "width": 80, "height": 80})).unwrap());
s.execute("paint.setFill", &json!({"color": "#ffffff"})).unwrap();
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
// Translucent, so that a blend that is not isolated also reaches the art behind the group.
s.execute("transparency.set", &json!({"opacity": 50})).unwrap();
let square = id(s.execute("shape.rectangle", &json!({"x": 70, "y": 70, "width": 60, "height": 60})).unwrap());
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
s.execute("paint.setFill", &json!({"color": "#ffffff"})).unwrap();
s.execute("transparency.set", &json!({"blend": "difference"})).unwrap();
s.execute("object.group", &json!({"ids": [back, square]})).unwrap();
let group = id(s.execute("object.group", &json!({"ids": [back, square]})).unwrap());
s.execute("transparency.set", &json!({"opacity": 50, "isolate": true})).unwrap();
s.execute("select.set", &json!({"ids": [square]})).unwrap();
s.execute("color.contrast", &json!({})).unwrap();
let r = s.execute("color.contrast", &json!({})).unwrap();
let isolated = ratio(&r);
assert!(isolated > 1.0, "{r}");
assert!(r["against"].as_str().is_some_and(|h| vectorcraft_color::Color::from_hex(h).is_some()), "{r}");
// Without isolation the square also blends with the black and white art, so there is no one answer.
let set_isolate = |s: &mut Session, on: bool| {
s.execute("select.set", &json!({"ids": [group]})).unwrap();
s.execute("transparency.set", &json!({"isolate": on})).unwrap();
s.execute("select.set", &json!({"ids": [square]})).unwrap();
};
set_isolate(&mut s, false);
let e = s.execute("color.contrast", &json!({})).unwrap_err().to_string();
assert!(e.contains("is not one color where it is read"), "{e}");
set_isolate(&mut s, true);
// The Difference mode is applied: in Normal mode the same square gives another answer.
s.execute("transparency.set", &json!({"blend": "normal"})).unwrap();
let normal = ratio(&s.execute("color.contrast", &json!({})).unwrap());
assert!((isolated - normal).abs() > 0.1, "difference {isolated} against normal {normal}");
}
/// With a fill of None, what a pick would be measured against is still read: the Color Wheel's
+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);
+4 -1
View File
@@ -578,7 +578,10 @@ fn placement_options_read_set_and_round_trip() {
let mut s = session();
let id = place(&mut s, &pic);
run(&mut s, "select.set", json!({"ids": [id.0]}));
assert_eq!(run(&mut s, "links.placementOptions", json!({})), json!({"placement": {"preserve": "bounds", "align": "center", "clip": false}}));
assert_eq!(
run(&mut s, "links.placementOptions", json!({})),
json!({"ids": [id.0], "placement": {"preserve": "bounds", "align": "center", "clip": false}})
);
let r = run(&mut s, "links.placementOptions", json!({"preserve": "fill", "align": "topRight", "clip": true}));
assert_eq!(r, json!({"ids": [id.0], "placement": {"preserve": "fill", "align": "topRight", "clip": true}}));
assert!(s.execute("links.placementOptions", &json!({"preserve": "stretch"})).is_err());
+73
View File
@@ -173,6 +173,79 @@ fn ppi_overprint_preview_and_bad_params() {
}
}
/// Artboard counts, columns and rows are whole numbers in range: a fraction or a count outside
/// 1 to 1000 is an error, not rounded or clamped to one.
#[test]
fn counts_that_are_not_whole_or_out_of_range_are_errors() {
for p in [
json!({"artboards": 2.4}),
json!({"artboards": 0}),
json!({"artboards": -0.5}),
json!({"artboards": 1001}),
json!({"artboardLayout": {"columns": 2.4}}),
json!({"artboardLayout": {"columns": 1001}}),
json!({"artboardLayout": {"layout": "gridByColumn", "rows": 2.4}}),
json!({"artboardLayout": {"layout": "gridByColumn", "rows": 0.6}}),
json!({"artboardLayout": {"layout": "gridByColumn", "rows": 1000.4}}),
] {
let mut s = Session::new();
assert!(s.execute("file.new", &p).is_err(), "{p}");
assert!(s.active().is_none(), "{p}: no document on an error");
}
let s = new_doc(json!({"artboards": 6.0, "artboardLayout": {"layout": "gridByColumn", "rows": 2.0}}));
assert_eq!(s.doc().unwrap().doc.artboards.len(), 6, "a whole number written 6.0 is a count");
}
#[test]
fn replaying_a_journal_rounds_an_older_artboard_count() {
let mut recorded = new_doc(json!({"artboards": 2}));
recorded.journal.last_mut().unwrap().1["artboards"] = json!(2.4);
let mut s = Session::new();
for (id, p) in &recorded.journal {
s.replay(id, p).unwrap();
}
assert_eq!(boards(&s), boards(&recorded));
assert_eq!(boards(&s).len(), 2);
assert!(s.execute("file.new", &json!({"artboards": 2.4})).is_err());
}
#[test]
fn replayed_counts_keep_their_rounding_and_range_rules() {
for (key, value, expected) in [
("artboards", 0.0, 1),
("artboards", 1001.0, 1000),
("columns", 2.4, 2),
("columns", 1001.0, 1000),
("rows", 2.4, 2),
("rows", 0.6, 1),
("rows", 1000.4, 1000),
] {
let mut p = json!({"width": 10, "height": 10, "artboards": 4,
"artboardLayout": {"layout": "gridByColumn", "spacing": 0}});
if key == "artboards" {
p[key] = json!(value);
} else {
p["artboardLayout"][key] = json!(value);
}
let mut s = Session::new();
s.replay("file.new", &p).unwrap();
assert!(s.execute("file.new", &p).is_err(), "{p}");
if key == "artboards" {
p[key] = json!(expected);
} else {
p["artboardLayout"][key] = json!(expected);
}
assert_eq!(boards(&s), boards(&new_doc(p)));
}
for layout in [json!({"columns": 0.6}), json!({"rows": 0.4}), json!({"rows": 1000.6})] {
let mut p = json!({"artboardLayout": layout});
p["artboardLayout"]["layout"] = json!("gridByColumn");
let mut s = Session::new();
assert!(s.replay("file.new", &p).is_err(), "{p}");
assert!(s.active().is_none(), "{p}");
}
}
#[test]
fn categories_list_generated_presets_with_neutral_names() {
let mut s = Session::new();
+4 -2
View File
@@ -445,11 +445,13 @@ fn each_copys_shadow_on_type_expands_as_the_canvas_draws_it() {
let shadow = json!({"x": 20, "y": 0, "blur": 0, "opacity": 100, "mode": "normal", "color": "#00ff00"});
run(&mut s, "effect.apply", json!({"effect": "stylize.dropShadow", "params": shadow}));
run(&mut s, "effect.apply", json!({"effect": "distort.transform", "params": {"scaleH": 200, "scaleV": 200, "moveV": 80, "copies": 1}}));
let before = render(&s);
if !(0..100u32).any(|y| (0..200u32).any(|x| before.pixel(x, y) == [255, 0, 0, 255])) {
let style = vectorcraft_doc::text::CharStyle::default();
if vectorcraft_text::FontDb::global().face(&style.font_family, &style.font_style).is_none() {
eprintln!("skipped: built without a font that draws the type");
return;
}
let before = render(&s);
assert!((0..100u32).any(|y| (0..200u32).any(|x| before.pixel(x, y) == [255, 0, 0, 255])), "the type draws in red");
// The rightmost red pixel of the copy, below the type, and 38 pt right of it the copy's shadow.
let red =
(100..200u32).flat_map(|y| (0..200u32).map(move |x| (x, y))).filter(|&(x, y)| before.pixel(x, y) == [255, 0, 0, 255]).max_by_key(|p| p.0);
+3 -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
+5 -1
View File
@@ -1144,7 +1144,7 @@ fn file_new_takes_the_rows_of_a_grid_by_column() {
let (plain, spaced) = (plain.with_params(&to_row, "file.new").unwrap(), spaced.with_params(&to_row, "file.new").unwrap());
assert_eq!(plain.grid_columns(), spaced.grid_columns());
let e = s.execute("file.new", &json!({"artboardLayout": {"layout": "gridByColumn", "rows": 0}})).unwrap_err().to_string();
assert!(e.contains("rows must be from 1 to 1000"), "{e}");
assert!(e.contains("rows must be a whole number from 1 to 1000"), "{e}");
for layout in ["gridByRow", "row", "column"] {
let e = s.execute("file.new", &json!({"artboardLayout": {"layout": layout, "rows": 2}})).unwrap_err().to_string();
assert!(e.contains("rows needs the gridByColumn layout"), "{layout}: {e}");
@@ -1477,6 +1477,10 @@ fn a_document_preset_is_an_instance_of_its_class() {
let mut s = Session::new();
let out = log(&mut s, "var p = new DocumentPreset(); vc.log(p instanceof DocumentPreset); vc.log(p.typename); vc.log(p.width);");
assert_eq!(out, vec![json!(true), json!("DocumentPreset"), json!(612)]);
// A named engine keeps the preset, but in a later run its type name throws, as its settings do.
run(&mut s, "#targetengine keep\nvar held = new DocumentPreset();").unwrap();
let e = failure(&mut s, "#targetengine keep\nheld.typename;");
assert!(e.contains("this is not a DocumentPreset"), "{e}");
}
/// A preset kept from an earlier run throws from `typename` and `toString()` as it does from its
+748
View File
@@ -0,0 +1,748 @@
//! Printing from a script: `Document.print` with `PrintOptions` and its option classes,
//! `app.printPresetsList`, `app.PPDFileList`, and the checks every option and the file go through.
use std::path::{Path, PathBuf};
use serde_json::{Value, json};
use crate::script::printing::{MAX_PRINTER_NAME_BYTES, MAX_PRINTERS, PreparedPrint, Printers};
use crate::*;
const DENIED: &str = "Script file access denied";
/// A test's folder, removed when the test ends, a failed assertion included.
struct Workspace(PathBuf);
impl std::ops::Deref for Workspace {
type Target = Path;
fn deref(&self) -> &Path {
&self.0
}
}
impl AsRef<Path> for Workspace {
fn as_ref(&self) -> &Path {
&self.0
}
}
impl Drop for Workspace {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
/// A fresh folder for test `name`, by its real path, with `main` for the script.
fn folder(name: &str) -> Workspace {
let base = std::env::temp_dir().join(format!("vc-script-print-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&base);
std::fs::create_dir_all(base.join("main")).unwrap();
std::fs::create_dir_all(base.join("outside")).unwrap();
Workspace(std::fs::canonicalize(&base).unwrap())
}
/// A session whose scripts keep their data folders in `base/settings/Script Data`, with a
/// 300 × 200 document of two artboards holding a rectangle.
fn session(base: &Path) -> Session {
let mut s = Session::new();
s.attach_script_data(base.join("settings/Script Data"));
s.execute("file.new", &json!({"width": 300, "height": 200, "artboards": 2})).unwrap();
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 100, "height": 50})).unwrap();
s
}
/// Runs `main/main.jsx` in `base` with the text `text` in `s`.
fn run(s: &mut Session, base: &Path, text: &str) -> Result<Value> {
let main = base.join("main/main.jsx");
std::fs::write(&main, text.as_bytes()).unwrap();
s.execute("script.run", &json!({"path": main.to_string_lossy()}))
}
fn logged(s: &mut Session, base: &Path, text: &str) -> Value {
run(s, base, text).unwrap_or_else(|e| panic!("{text}: {e}"))["log"].clone()
}
fn failure(s: &mut Session, base: &Path, text: &str) -> String {
run(s, base, text).map(|r| panic!("{text} ran: {r}")).unwrap_err().to_string()
}
/// The script's data folder, where it may write.
fn data_folder(s: &mut Session, base: &Path) -> PathBuf {
PathBuf::from(logged(s, base, "vc.log(Folder.userData.fsName);")[0].as_str().unwrap())
}
fn quoted(p: &Path) -> String {
serde_json::to_string(&p.to_string_lossy()).unwrap()
}
fn pages(path: &Path) -> Vec<(f64, f64)> {
let info = vectorcraft_pdf::info(&std::fs::read(path).unwrap(), None).unwrap();
info.pages.iter().map(|p| (p.width.round(), p.height.round())).collect()
}
#[test]
fn print_writes_the_file_with_the_assigned_options_over_the_saved_settings() {
let base = folder("happy");
let mut s = session(&base);
s.execute("print.setup", &json!({"settings": {"collate": true, "marks": {"trim": true}}})).unwrap();
let saved = s.execute("print.setup", &json!({})).unwrap()["settings"].clone();
let undo = s.active().unwrap().history.undo.len();
let dir = data_folder(&mut s, &base);
let d = quoted(&dir);
let out = logged(
&mut s,
&base,
&format!(
"Folder.userData; var dir = {d}, doc = app.activeDocument;\n\
var o = new PrintOptions(), j = new PrintJobOptions();\n\
vc.log([o.typename, j.typename, j.copies, j.collate, j.printAllArtboards, j.designation, o.coordinateOptions.typename]);\n\
o.jobOptions = j; j.copies = 2; j.file = new File(dir + '/a.pdf');\n\
j.copies = 3; vc.log([o.jobOptions.copies, j.collate]);\n\
doc.print(o);\n\
var back = o.jobOptions.file; j.file = back; vc.log([back instanceof File, back.name]);\n\
j.printAllArtboards = false; j.artboardRange = '2'; j.copies = 1; j.file = new File(dir + '/b.pdf');\n\
o.paperOptions.name = 'a4'; o.coordinateOptions.fitToPage = true; o.coordinateOptions.orientation = PrintOrientation.PORTRAIT;\n\
o.printerName = ''; o.fontOptions.downloadFonts = PrintFontDownloadMode.DOWNLOADSUBSET;\n\
doc.print(o);\n\
j.file = new File(dir + '/c.ps'); doc.print(o);\n\
o.postScriptOptions.postScriptLevel = PrinterPostScriptLevelEnum.PSLEVEL2; j.file = new File(dir + '/level2.prn');\n\
doc.print(o);\n\
vc.log([app.printPresetsList[0], app.PPDFileList.length]);"
),
);
let expected =
json!(["PrintOptions", "PrintJobOptions", 1, false, true, "PrintArtworkDesignation.VISIBLEPRINTABLELAYERS", "PrintCoordinateOptions"]);
assert_eq!(out[0], expected, "a new option object reads as its help page's defaults");
assert_eq!(out[1], json!([3, false]), "a change after the assignment is read through the PrintOptions");
assert_eq!(out[2], json!([true, "a.pdf"]), "jobOptions.file reads back as a File");
assert_eq!(out[3], json!(["[Default]", 0]));
assert_eq!(pages(&dir.join("a.pdf")).len(), 6, "two artboards, three copies");
assert_eq!(pages(&dir.join("b.pdf")), vec![(595.0, 842.0)], "artboard 2 only, on upright A4");
let ps = std::fs::read_to_string(dir.join("c.ps")).unwrap();
assert!(ps.starts_with("%!PS") && !ps.contains("%%LanguageLevel: 2"), "a .ps name alone: {}", &ps[..ps.len().min(200)]);
let ps = std::fs::read_to_string(dir.join("level2.prn")).unwrap();
assert!(ps.starts_with("%!PS") && ps.contains("%%LanguageLevel: 2"), "a level alone: {}", &ps[..ps.len().min(200)]);
assert_eq!(s.execute("print.setup", &json!({})).unwrap()["settings"], saved, "printing leaves the saved settings as they are");
assert_eq!(s.active().unwrap().history.undo.len(), undo, "and adds no undo step");
// The commands stay closed to vc.run, before and after a print.
for case in [
"vc.run('file.print', {});",
"var o = new PrintOptions(); o.jobOptions.file = new File(Folder.userData.fsName + '/d.pdf'); app.activeDocument.print(o); vc.run('file.print', {});",
"vc.run('print.setup', {settings: {copies: 5}});",
] {
let e = failure(&mut s, &base, case);
assert!(e.contains("a script cannot run"), "{case}: {e}");
}
assert_eq!(s.execute("print.setup", &json!({})).unwrap()["settings"], saved);
let _ = std::fs::remove_dir_all(base);
}
/// Without the printers a frontend lists for scripts (a run outside the app, the web), printing to
/// a printer and `app.printerList` throw, and nothing is prepared.
#[test]
fn print_without_a_file_does_not_print() {
let base = folder("no-file");
let mut s = session(&base);
for case in [
"app.activeDocument.print();",
"app.activeDocument.print(new PrintOptions());",
"var o = new PrintOptions(); o.jobOptions.copies = 2; app.activeDocument.print(o);",
"var o = new PrintOptions(); o.printerName = 'Office'; app.activeDocument.print(o);",
] {
let e = failure(&mut s, &base, case);
assert!(e.contains("Printing to a printer is not available here"), "{case}: {e}");
}
let e = failure(&mut s, &base, "app.printerList;");
assert!(e.contains("Application.printerList is not available here"), "{e}");
assert!(!s.script_prints_waiting());
let _ = std::fs::remove_dir_all(base);
}
/// The printers a frontend lists, `Office` the default, with a name a shell or a file system would
/// read as more than a name.
const ODD_NAME: &str = "Lab; rm -rf / & \\\\srv\\q $(x) ../p";
fn printers() -> Printers {
Printers::new([("Office".to_string(), true), (ODD_NAME.to_string(), false)], false)
}
/// The PDF pages a prepared job holds.
fn job_pages(job: &PreparedPrint) -> usize {
vectorcraft_pdf::info(&job.pdf, None).unwrap().pages.len()
}
/// `app.printerList` gives a `Printer` for each printer the frontend listed, at most 256 of them,
/// without names that are empty, too long, hold a control character or repeat; the list is the
/// run's own, needs an open document, and its objects go stale after the run.
#[test]
fn printer_list_is_the_bounded_list_the_frontend_gave() {
let base = folder("printer-list");
let mut s = session(&base);
let mut list: Vec<(String, bool)> = (0..300).map(|i| (format!("Printer {i}"), i == 1)).collect();
list.insert(0, ("x".repeat(MAX_PRINTER_NAME_BYTES + 1), true));
list.insert(1, ("Bad\nName".into(), false));
list.insert(2, (String::new(), false));
list.insert(3, ("Printer 5".into(), false));
let snapshot = Printers::new(list, false);
assert_eq!(snapshot.names().len(), MAX_PRINTERS);
assert_eq!(snapshot.default_name(), Some("Printer 1"));
// A default listed after the first 256 takes the last place, and a repeated name keeps a later
// default mark without a second entry.
let late = Printers::new((0..300).map(|i| (format!("Q{i}"), i == 280)), false);
let names = late.names();
assert_eq!((names.len(), late.default_name(), names[254].as_str(), names[255].as_str()), (MAX_PRINTERS, Some("Q280"), "Q254", "Q280"));
let repeat = Printers::new([("A".to_string(), false), ("B".to_string(), false), ("A".to_string(), true)], false);
assert_eq!((repeat.names(), repeat.default_name()), (&["A".to_string(), "B".to_string()][..], Some("A")));
s.script_printers = Some(snapshot);
let out = logged(
&mut s,
&base,
"#targetengine keep\nvar l = app.printerList; held = l[0];\n\
vc.log([l.length, l[0].name, l[0].typename, l[1].name, l[255].name]);\n\
try { l[0].name = 'Other'; } catch (e) {} vc.log(l[0].name);\n\
try { l[0].printerInfo; } catch (e) { vc.log(e.message); }",
);
assert_eq!(out[0], json!([256, "Printer 5", "Printer", "Printer 0", "Printer 255"]));
assert_eq!(out[1], json!("Printer 5"), "name is read-only");
assert_eq!(out[2], json!("Printer.printerInfo is not available yet"));
// The next run has no list unless the frontend gives one again.
let e = failure(&mut s, &base, "app.printerList;");
assert!(e.contains("Application.printerList is not available here"), "{e}");
s.script_printers = Some(printers());
let e = failure(&mut s, &base, "#targetengine keep\nheld.name;");
assert!(e.contains("Stale printer"), "{e}");
s.script_printers = Some(printers());
assert_eq!(logged(&mut s, &base, "vc.log(app.printerList[1].name);")[0], json!(ODD_NAME));
// With no document open there is no list.
let mut empty = Session::new();
empty.attach_script_data(base.join("settings/Script Data"));
empty.script_printers = Some(printers());
let e = failure(&mut empty, &base, "app.printerList;");
assert!(e.contains("Application.printerList needs an open document"), "{e}");
let _ = std::fs::remove_dir_all(base);
}
/// `print` without a file prepares a print-ready PDF for the printer it names, or the default one,
/// and sends nothing: the session holds the jobs once the run's changes are kept, for the frontend
/// to take. A name is matched exactly, whatever characters it holds.
#[test]
fn print_to_a_printer_holds_the_job_until_the_run_ends() {
let base = folder("prepared");
let mut s = session(&base);
s.script_printers = Some(printers());
let name = serde_json::to_string(ODD_NAME).unwrap();
let report = run(
&mut s,
&base,
&format!(
"var o = new PrintOptions(); o.printerName = {name}; o.jobOptions.copies = 2; o.jobOptions.collate = true;\n\
app.activeDocument.print(o);\n\
vc.run('shape.rectangle', {{x: 150, y: 10, width: 20, height: 20}});\n\
app.activeDocument.print();"
),
)
.unwrap();
assert_eq!(report["prints"], 2, "{report}");
assert!(s.script_prints_waiting());
let title = s.active().unwrap().title();
let jobs = s.take_script_prints();
assert!(!s.script_prints_waiting());
assert_eq!(jobs.len(), 2);
assert_eq!((jobs[0].printer.as_str(), jobs[0].sheets, job_pages(&jobs[0])), (ODD_NAME, 4, 4), "two artboards, two copies");
assert_eq!((jobs[1].printer.as_str(), jobs[1].sheets, job_pages(&jobs[1])), ("Office", 2, 2), "the default printer");
assert!(jobs.iter().all(|j| j.title == title && j.pdf.starts_with(b"%PDF")));
// Each job holds the document as it was when print was called: one copy of the second job has
// the rectangle the script added after the first job, and the first job's two copies do not.
let paths = |job: &PreparedPrint| {
let mut n = 0;
vectorcraft_pdf::import(&job.pdf).unwrap().walk(|c| n += usize::from(matches!(c.kind, vectorcraft_doc::NodeKind::Path { .. })));
n
};
assert_eq!(paths(&jobs[0]) % 2, 0, "two equal copies");
assert_eq!(paths(&jobs[0]) / 2 + 1, paths(&jobs[1]), "the second job has the added rectangle");
assert!(s.take_script_prints().is_empty(), "a job is taken once");
let _ = std::fs::remove_dir_all(base);
}
/// A run that throws, runs out of fuel or ends at a failed command keeps no job.
#[test]
fn a_run_that_fails_keeps_no_print_job() {
let base = folder("rollback");
let mut s = session(&base);
let objects = s.active().unwrap().doc.layers[0].children().map_or(0, Vec::len);
for case in [
"app.activeDocument.print(); throw new Error('late');",
"app.activeDocument.print(); vc.run('no.such.command', {});",
"app.activeDocument.print(); app.activeDocument.print(); app.activeDocument.print(); app.activeDocument.print(); app.activeDocument.print();",
] {
s.script_printers = Some(printers());
failure(&mut s, &base, case);
assert!(!s.script_prints_waiting(), "{case}");
}
s.script_printers = Some(printers());
let stopped = s.execute("script.run", &json!({"source": "app.activeDocument.print(); while (true) {}", "name": "t.js", "maxFuel": 2_000_000}));
assert!(stopped.is_err());
assert!(s.take_script_prints().is_empty());
assert_eq!(s.active().unwrap().doc.layers[0].children().map_or(0, Vec::len), objects);
let _ = std::fs::remove_dir_all(base);
}
/// A name that is not exactly a listed printer's, a list with no default, PostScript, more jobs or
/// sheets than a run may prepare and jobs an earlier run left waiting all throw, and nothing is
/// prepared; a file wins over a printer name.
#[test]
fn print_to_a_printer_refuses_what_it_cannot_send() {
let base = folder("refuse");
let mut s = session(&base);
let dir = data_folder(&mut s, &base);
let cases = [
("o.printerName = 'office';", "PrintOptions.printerName names no installed printer: office"),
("o.printerName = 'Offic';", "names no installed printer: Offic"),
("o.printerName = ' Office';", "names no installed printer: Office"),
("o.printerName = 'Office\\n';", "names no installed printer"),
("o.postScriptOptions.postScriptLevel = PrinterPostScriptLevelEnum.PSLEVEL2;", "PostScript prints only to a file"),
("o.jobOptions.copies = 51;", "at most 100 sheets in a run; this job has 102"),
("for (var i = 0; i < 4; i++) app.activeDocument.print(o);", "at most 4 jobs to a printer in a run"),
("o.printPreset = 'Nope';", "printPreset names no print preset"),
];
for (case, part) in cases {
s.script_printers = Some(printers());
let e = failure(&mut s, &base, &format!("var o = new PrintOptions(); {case} app.activeDocument.print(o);"));
assert!(e.contains(part), "{case}: {e}");
assert!(!s.script_prints_waiting(), "{case}");
}
// A job past the sheet limit is refused before it is composed.
s.script_printers = Some(printers());
failure(&mut s, &base, "var o = new PrintOptions(); o.jobOptions.copies = 999; app.activeDocument.print(o);");
let report = s.script_report().unwrap();
let ran: Vec<&str> = report["slowestCommands"].as_array().unwrap().iter().filter_map(|c| c["id"].as_str()).collect();
assert_eq!(ran, ["file.print"], "{report}");
s.script_printers = Some(Printers::new([("Office".to_string(), false)], false));
let e = failure(&mut s, &base, "app.activeDocument.print();");
assert!(e.contains("There is no default printer: set PrintOptions.printerName"), "{e}");
// Jobs an earlier run left waiting: the next run cannot print to a printer until they are taken.
s.script_printers = Some(printers());
logged(&mut s, &base, "app.activeDocument.print();");
s.script_printers = Some(printers());
let e = failure(&mut s, &base, "app.activeDocument.print();");
assert!(e.contains("A print job from an earlier script still waits for approval"), "{e}");
assert_eq!(s.take_script_prints().len(), 1, "the earlier job is kept");
s.script_printers = Some(printers());
logged(&mut s, &base, "app.activeDocument.print();");
assert_eq!(s.take_script_prints().len(), 1);
// A file wins over the printer name.
s.script_printers = Some(printers());
let file = quoted(&dir.join("f.pdf"));
logged(
&mut s,
&base,
&format!(
"Folder.userData; var o = new PrintOptions(); o.printerName = 'Nowhere'; o.jobOptions.file = new File({file}); app.activeDocument.print(o);"
),
);
assert!(dir.join("f.pdf").exists());
assert!(!s.script_prints_waiting());
let _ = std::fs::remove_dir_all(base);
}
/// The pages of a job for a printer are counted from the art as it prints, artboard backgrounds
/// included, as `file.print` lays it out: an artboard that holds only its background prints with
/// `skipBlank`, and counts toward the sheet limit.
#[test]
fn print_to_a_printer_counts_the_pages_of_the_art_as_it_prints() {
let base = folder("backgrounds");
let mut s = session(&base);
s.execute("artboard.setProps", &json!({"index": 1, "color": "#ff0000"})).unwrap();
s.execute("print.setup", &json!({"settings": {"skipBlank": true, "artboards": "range", "range": "2"}})).unwrap();
s.script_printers = Some(printers());
logged(&mut s, &base, "app.activeDocument.print();");
let jobs = s.take_script_prints();
assert_eq!(jobs.iter().map(|j| (j.sheets, job_pages(j))).collect::<Vec<_>>(), [(1, 1)], "the background prints");
s.execute("print.setup", &json!({"settings": {"artboards": "all"}})).unwrap();
s.script_printers = Some(printers());
let e = failure(&mut s, &base, "var o = new PrintOptions(); o.jobOptions.copies = 51; app.activeDocument.print(o);");
assert!(e.contains("this job has 102"), "both artboards print: {e}");
assert!(!s.script_prints_waiting());
let _ = std::fs::remove_dir_all(base);
}
/// `file.print`'s `maxPages` composes nothing for a longer job, and only after the other params are
/// checked.
#[test]
fn file_print_max_pages_composes_only_what_fits() {
let base = folder("max-pages");
let mut s = session(&base);
let r = s.execute("file.print", &json!({"maxPages": 5, "settings": {"copies": 3}})).unwrap();
assert_eq!((&r["pages"], r.get("dataBase64").is_none()), (&json!(6), true), "{r}");
let r = s.execute("file.print", &json!({"maxPages": 6, "settings": {"copies": 3}})).unwrap();
assert_eq!((&r["pages"], r["dataBase64"].is_string()), (&json!(6), true));
for bad in [
json!({"maxPages": 0, "format": "postscript", "level": 1}),
json!({"maxPages": 0, "settings": {"advanced": {"flattenerPreset": "nope"}}}),
json!({"maxPages": -1}),
json!({"maxPages": "2"}),
json!({"maxPages": null}),
] {
assert!(s.execute("file.print", &bad).is_err(), "{bad}");
}
let _ = std::fs::remove_dir_all(base);
}
/// Bad values throw when they are assigned, and nothing prints.
#[test]
fn print_options_refuse_bad_values() {
let base = folder("bad");
let mut s = session(&base);
let cases = [
("j.copies = 0;", "RangeError", "copies must be a whole number from 1 to 999"),
("j.copies = NaN;", "TypeError", "copies"),
("j.copies = 1e12;", "RangeError", "copies must be a whole number"),
("j.copies = 1.5;", "RangeError", "copies must be a whole number"),
("j.copies = '2';", "TypeError", "copies must be a number"),
("j.collate = 1;", "TypeError", "collate must be true or false"),
("c.horizontalScale = NaN;", "TypeError", "horizontalScale"),
("c.horizontalScale = Infinity;", "TypeError", "horizontalScale"),
("c.verticalScale = 20000;", "RangeError", "verticalScale must be from 1 to 10000"),
("c.verticalScale = 0;", "RangeError", "verticalScale must be from 1 to 10000"),
("m.trimMarksWeight = -1;", "RangeError", "trimMarksWeight must be from 0"),
("c.orientation = 'PrintOrientation.SIDEWAYS';", "TypeError", "orientation must be a PrintOrientation value"),
("c.orientation = 'PrintTiling.TILEFULLPAGES';", "TypeError", "orientation must be a PrintOrientation value"),
("j.file = 'C:/out.pdf';", "TypeError", "file must be a File"),
("j.file = {};", "TypeError", "file must be a File"),
("o.jobOptions = new PrintCoordinateOptions();", "TypeError", "jobOptions must be a PrintJobOptions"),
("o.jobOptions = {copies: 2};", "TypeError", "jobOptions must be a PrintJobOptions"),
("o.printPreset = new Array(5000).join('x');", "RangeError", "printPreset is too long"),
("app.activeDocument.print({jobOptions: j});", "TypeError", "print's options must be a PrintOptions object"),
("app.activeDocument.print(j);", "TypeError", "print's options must be a PrintOptions object"),
];
let prefix = "var o = new PrintOptions(), j = o.jobOptions, c = o.coordinateOptions, m = o.pageMarksOptions;";
for (case, kind, part) in cases {
let e = failure(&mut s, &base, &format!("{prefix} {case}"));
assert!(e.contains(kind) && e.contains(part), "{case}: {e}");
}
let _ = std::fs::remove_dir_all(base);
}
/// Options that `file.print` cannot honor throw instead of being dropped.
#[test]
fn options_that_are_not_available_throw() {
let base = folder("later");
let mut s = session(&base);
let dir = data_folder(&mut s, &base);
let file = format!("j.file = new File({});", quoted(&dir.join("x.pdf")));
let cases = [
("o.PPDName = 'Generic';", "PrintOptions.PPDName is not available yet"),
("o.PPDName = '/etc/cups/ppd/office.ppd';", "PrintOptions.PPDName is not available yet"),
("j.name = 'Job';", "PrintJobOptions.name is not available yet"),
("j.printArea = PrintingBounds.ARTWORKBOUNDS;", "PrintingBounds.ARTWORKBOUNDS is not available yet"),
("o.colorSeparationOptions.colorSeparationMode = PrintColorSeparationMode.INRIPSEPARATION;", "INRIPSEPARATION is not available yet"),
("o.colorManagementOptions.colorProfileMode = PrintColorProfile.PRINTERPROFILE;", "PRINTERPROFILE is not available yet"),
("o.colorSeparationOptions.inkList = [];", "PrintColorSeparationOptions.inkList is not available yet"),
("o.fontOptions.downloadFonts = PrintFontDownloadMode.DOWNLOADCOMPLETE;", "PrintFontOptions.downloadFonts is not available yet"),
("o.flattenerOptions.rasterizationResolution = 600;", "PrintFlattenerOptions.rasterizationResolution is not available yet"),
("o.flattenerOptions.rasterizationResolution = NaN;", "PrintFlattenerOptions.rasterizationResolution"),
("o.pageMarksOptions.bleedOffsetRect = [0, 0, 0, 0];", "PrintPageMarksOptions.bleedOffsetRect is not available yet"),
("o.paperOptions.offset = 10;", "PrintPaperOptions.offset is not available yet"),
("o.postScriptOptions.postScriptLevel = PrinterPostScriptLevelEnum.PSLEVEL1;", "PSLEVEL1 is not available yet"),
("o.postScriptOptions.binaryPrinting = true;", "PrintPostScriptOptions.binaryPrinting is not available yet"),
(
&format!("{file} o.coordinateOptions.horizontalScale = 2000; app.activeDocument.print(o);"),
"horizontalScale above 1000 is not available yet",
),
];
let prefix = "Folder.userData; var o = new PrintOptions(), j = o.jobOptions;";
for (case, part) in cases {
let e = failure(&mut s, &base, &format!("{prefix} {case}"));
assert!(e.contains(part), "{case}: {e}");
}
assert!(!dir.join("x.pdf").exists(), "nothing printed");
// With Fit to Page on, the scale factors are not used, so a factor above 1000 does not stop the job.
let out = logged(
&mut s,
&base,
&format!(
"{prefix} {file} var c = o.coordinateOptions; c.horizontalScale = 2000; c.verticalScale = 2000; c.fitToPage = true;\
app.activeDocument.print(o); vc.log(true);"
),
);
assert_eq!(out, json!([true]));
assert!(dir.join("x.pdf").exists(), "the fitted job printed");
let _ = std::fs::remove_dir_all(base);
}
/// A panic while `print` has the fence open for `file.print` closes it again for the next run.
#[test]
fn a_panic_while_printing_leaves_the_fence_closed() {
let base = folder("panic-unfenced");
let mut s = session(&base);
let print = "var o = new PrintOptions(); o.jobOptions.file = new File(Folder.userData.fsName + '/p.pdf'); app.activeDocument.print(o);";
crate::script::PANIC_WHILE_UNFENCED.with(|p| p.set(true));
let r = run(&mut s, &base, print);
crate::script::PANIC_WHILE_UNFENCED.with(|p| p.set(false));
let e = r.map(|r| panic!("the print ran: {r}")).unwrap_err().to_string();
assert!(e.contains("a command past the fence failed"), "the run ends at the panic: {e}");
let e = failure(&mut s, &base, "vc.run('file.print', {});");
assert!(e.contains("a script cannot run"), "{e}");
}
#[test]
fn print_writes_only_where_the_script_may() {
let base = folder("refused");
let mut s = session(&base);
let dir = data_folder(&mut s, &base);
let grants = base.join("settings/Script Grants.json");
std::fs::write(&grants, "{}").unwrap();
for target in [base.join("outside/x.pdf"), grants.clone(), dir.clone()] {
let case =
format!("Folder.userData; var o = new PrintOptions(); o.jobOptions.file = new File({}); app.activeDocument.print(o);", quoted(&target));
let e = failure(&mut s, &base, &case);
assert!(e.contains("Script file"), "{case}: {e}");
if target != dir {
assert!(e.contains(DENIED), "{case}: {e}");
}
}
assert!(!base.join("outside/x.pdf").exists());
assert_eq!(std::fs::read_to_string(&grants).unwrap(), "{}");
let _ = std::fs::remove_dir_all(base);
}
/// A print to a file a `File` object holds open for writing throws, so the object's bytes written at
/// the end of the run do not replace the printed file.
#[test]
fn print_does_not_write_a_file_open_for_writing() {
let base = folder("openhandle");
let mut s = session(&base);
let dir = data_folder(&mut s, &base);
let p = quoted(&dir.join("x.pdf"));
let log = logged(
&mut s,
&base,
&format!(
"Folder.userData; var w = new File({p}); w.open('w'); w.write('pending');\nvar o = new PrintOptions(); o.jobOptions.file = new File({p});\ntry {{ app.activeDocument.print(o); vc.log('ran'); }} catch (e) {{ vc.log(e.message); }}"
),
);
assert!(log[0].as_str().unwrap().contains(crate::script::files::OPEN_FOR_WRITING), "{log}");
assert_eq!(std::fs::read_to_string(dir.join("x.pdf")).unwrap(), "pending", "the File's own bytes");
let _ = std::fs::remove_dir_all(base);
}
/// One assigned scale factor leaves the other at the document's saved value.
#[test]
fn one_assigned_scale_factor_keeps_the_saved_other() {
let base = folder("scale");
let mut s = session(&base);
let common = json!({"media": "letter", "autoRotate": false, "orientation": "portrait", "artboards": "range", "range": "1"});
let mut saved = common.clone();
saved["scale"] = json!({"width": 100, "height": 500, "linked": false});
s.execute("print.setup", &json!({"settings": saved})).unwrap();
let dir = data_folder(&mut s, &base);
let mut expected = common;
expected["scaling"] = json!("tileFull");
expected["scale"] = json!({"width": 400, "height": 500, "linked": false});
let want = s.execute("file.print", &json!({"settings": expected, "path": dir.join("want.pdf").to_string_lossy()})).unwrap();
logged(
&mut s,
&base,
&format!(
"Folder.userData; var o = new PrintOptions(); o.jobOptions.file = new File({});\n\
o.coordinateOptions.horizontalScale = 400; o.coordinateOptions.tiling = PrintTiling.TILEFULLPAGES;\n\
app.activeDocument.print(o);",
quoted(&dir.join("got.pdf"))
),
);
let got = pages(&dir.join("got.pdf"));
assert_eq!(got.len() as u64, want["pages"].as_u64().unwrap(), "the saved vertical scale of 500% is kept");
assert!(got.len() >= 4, "1200 by 1000 pt of art tiles over at least four letter pages: {got:?}");
let _ = std::fs::remove_dir_all(base);
}
/// An assigned `artboardRange` replaces a saved range, an assigned `printArea` prints by artboard over
/// saved settings that ignore the artboards, and two scale factors that differ by any amount print
/// unlinked.
#[test]
fn assigned_job_and_scale_options_apply_over_the_saved_settings() {
let base = folder("over-saved");
let mut s = session(&base);
let dir = data_folder(&mut s, &base);
let print = |s: &mut Session, name: &str, body: &str| {
let file = quoted(&dir.join(name));
logged(
s,
&base,
&format!("Folder.userData; var o = new PrintOptions(); o.jobOptions.file = new File({file}); {body} app.activeDocument.print(o);"),
);
pages(&dir.join(name)).len()
};
s.execute("print.setup", &json!({"settings": {"artboards": "range", "range": "1"}})).unwrap();
assert_eq!(print(&mut s, "saved.pdf", ""), 1, "the saved range");
assert_eq!(print(&mut s, "range.pdf", "o.jobOptions.artboardRange = '1-2';"), 2, "the assigned range replaces the saved one");
s.execute("print.setup", &json!({"settings": {"artboards": "ignore"}})).unwrap();
assert_eq!(print(&mut s, "ignore.pdf", ""), 1, "all the art as one page");
assert_eq!(print(&mut s, "area.pdf", "o.jobOptions.printArea = PrintingBounds.ARTBOARDBOUNDS;"), 2, "each artboard prints");
assert_eq!(print(&mut s, "range-ignored.pdf", "o.jobOptions.artboardRange = '2';"), 1, "a range alone keeps ignoring the artboards");
let area_range = "o.jobOptions.printArea = PrintingBounds.ARTBOARDBOUNDS; o.jobOptions.artboardRange = '2';";
assert_eq!(print(&mut s, "area-range.pdf", area_range), 1, "printArea with a range prints the range");
let scaled = "o.coordinateOptions.horizontalScale = 100; o.coordinateOptions.verticalScale = 100.0000000005;";
assert!(print(&mut s, "scale.pdf", scaled) >= 1, "factors that differ by a tiny amount print unlinked");
assert_eq!(s.execute("print.setup", &json!({})).unwrap()["settings"]["artboards"], json!("ignore"), "the saved settings stay");
let _ = std::fs::remove_dir_all(base);
}
/// The format follows the name `jobOptions.file` gives, not the extension of the file a link in the
/// granted folder leads to.
#[cfg(unix)]
#[test]
fn the_format_follows_the_name_the_script_gives() {
let base = folder("format-name");
let mut s = session(&base);
let dir = data_folder(&mut s, &base);
std::fs::write(dir.join("proof.pdf"), "old").unwrap();
std::os::unix::fs::symlink(dir.join("proof.pdf"), dir.join("proof.ps")).unwrap();
logged(
&mut s,
&base,
&format!(
"Folder.userData; var o = new PrintOptions(); o.jobOptions.file = new File({}); app.activeDocument.print(o);",
quoted(&dir.join("proof.ps"))
),
);
let written = std::fs::read(dir.join("proof.pdf")).unwrap();
assert!(written.starts_with(b"%!PS"), "PostScript for a .ps name: {:?}", String::from_utf8_lossy(&written[..written.len().min(40)]));
let _ = std::fs::remove_dir_all(base);
}
/// Artboard ranges the document does not hold and preset names that are not presets, such as
/// paths, throw before anything is written.
#[test]
fn print_refuses_ranges_and_preset_names_it_cannot_honor() {
let base = folder("names");
let mut s = session(&base);
let dir = data_folder(&mut s, &base);
let file = format!("j.file = new File({});", quoted(&dir.join("x.pdf")));
let cases = [
("j.printAllArtboards = false; j.artboardRange = '3';", "RangeError", "artboardRange: range `3`"),
("j.printAllArtboards = false; j.artboardRange = '0-1';", "RangeError", "artboardRange"),
("j.printAllArtboards = false; j.artboardRange = '../../outside';", "RangeError", "artboardRange"),
("j.printAllArtboards = false; j.artboardRange = '2-1';", "RangeError", "artboardRange"),
("j.artboardRange = '3';", "RangeError", "artboardRange: range `3`"),
("o.printPreset = 'Office';", "Error", "printPreset names no print preset: Office"),
(&format!("o.printPreset = {};", quoted(&base.join("settings/Script Grants.json"))), "Error", "printPreset names no print preset"),
("o.printPreset = '../../preset';", "Error", "printPreset names no print preset"),
("o.flattenerPreset = '/etc/passwd';", "Error", "flattenerPreset names no flattener preset"),
(&format!("o.flattenerPreset = {};", quoted(&base.join("outside/f.xml"))), "Error", "flattenerPreset names no flattener preset"),
];
let prefix = format!("Folder.userData; var o = new PrintOptions(), j = o.jobOptions; {file}");
for (case, kind, part) in cases {
let e = failure(&mut s, &base, &format!("{prefix} {case} app.activeDocument.print(o);"));
assert!(e.contains(kind) && e.contains(part), "{case}: {e}");
}
assert!(!dir.join("x.pdf").exists(), "nothing printed");
// The names the lists give print, in any case.
logged(&mut s, &base, &format!("{prefix} o.printPreset = '[default]'; o.flattenerPreset = 'high resolution'; app.activeDocument.print(o);"));
assert!(dir.join("x.pdf").exists());
let _ = std::fs::remove_dir_all(base);
}
/// A color profile, a paper or a preset name that is empty, path-shaped, holds a control character
/// or is not on its list throws before anything is written; a listed name in any case prints.
#[test]
fn print_refuses_profile_paper_and_blank_preset_names() {
let base = folder("profile-paper");
let mut s = session(&base);
let dir = data_folder(&mut s, &base);
let file = format!("j.file = new File({});", quoted(&dir.join("x.pdf")));
let profile = "PrintColorManagementOptions.name names no color profile";
let paper = "PrintPaperOptions.name names no paper";
let cases = [
("c.name = '../sRGB IEC61966-2.1';", profile),
("c.name = 'C:/Windows/System32/spool/drivers/color/sRGB IEC61966-2.1';", profile),
("c.name = '\\\\\\\\server\\\\share\\\\cmyk.icc';", profile),
("c.name = 'No Such Profile';", profile),
("c.colorProfileMode = PrintColorProfile.SOURCEPROFILE; c.name = '../cmyk.icc';", profile),
("c.name = ' ';", "PrintColorManagementOptions.name must name a color profile"),
("p.name = '../letter';", paper),
("p.name = 'let\\u0007ter';", paper),
("p.name = '\\tA4\\n';", paper),
("o.printPreset = '[Default]\\n';", "PrintOptions.printPreset names no print preset"),
("p.name = 'Office Tray 2';", paper),
("p.name = '';", "PrintPaperOptions.name must name a paper"),
("p.name = 'a4'; p.width = 300;", "PrintPaperOptions.width and height apply only to custom paper, not a4"),
("o.flattenerPreset = ' ';", "PrintOptions.flattenerPreset must name a flattener preset"),
("o.flattenerPreset = '';", "PrintOptions.flattenerPreset must name a flattener preset"),
("o.printPreset = ' ';", "PrintOptions.printPreset must name a print preset"),
];
let prefix = format!("Folder.userData; var o = new PrintOptions(), j = o.jobOptions, c = o.colorManagementOptions, p = o.paperOptions; {file}");
for (case, part) in cases {
let e = failure(&mut s, &base, &format!("{prefix} {case} app.activeDocument.print(o);"));
assert!(e.contains(part), "{case}: {e}");
}
assert!(!dir.join("x.pdf").exists(), "nothing printed");
// Listed names print in any case and with spaces around them.
logged(
&mut s,
&base,
&format!(
"{prefix} c.colorProfileMode = PrintColorProfile.CUSTOMPROFILE; c.name = 'srgb iec61966-2.1'; p.name = ' A4 ';\n\
o.printPreset = ' [Default] '; o.flattenerPreset = ' High Resolution '; app.activeDocument.print(o);"
),
);
let sizes = pages(&dir.join("x.pdf"));
assert!(!sizes.is_empty() && sizes.iter().all(|&(w, h)| [(595.0, 842.0), (842.0, 595.0)].contains(&(w, h))), "A4: {sizes:?}");
// A custom paper takes the assigned size.
let custom = format!(
"Folder.userData; var o = new PrintOptions(), p = o.paperOptions; o.jobOptions.file = new File({});\n\
p.name = 'Custom'; p.width = 360; p.height = 504; o.coordinateOptions.orientation = PrintOrientation.PORTRAIT;\n\
app.activeDocument.print(o);",
quoted(&dir.join("custom.pdf"))
);
logged(&mut s, &base, &custom);
let sizes = pages(&dir.join("custom.pdf"));
assert!(!sizes.is_empty() && sizes.iter().all(|&size| size == (360.0, 504.0)), "custom: {sizes:?}");
let _ = std::fs::remove_dir_all(base);
}
/// Each warning `file.print` gives goes to the Script Console.
#[test]
fn print_writes_its_warnings_to_the_script_console() {
let base = folder("warnings");
let mut s = session(&base);
let dir = data_folder(&mut s, &base);
let settings = json!({"color": {"profile": "sRGB IEC61966-2.1"}});
let want =
s.execute("file.print", &json!({"format": "postscript", "settings": settings, "path": dir.join("want.ps").to_string_lossy()})).unwrap();
let warnings: Vec<String> = want["warnings"].as_array().unwrap().iter().map(|w| format!("Document.print: {}", w.as_str().unwrap())).collect();
assert!(warnings.iter().any(|w| w.contains("printer profile")), "{want}");
let report = run(
&mut s,
&base,
&format!(
"Folder.userData; var o = new PrintOptions(); o.jobOptions.file = new File({});\n\
o.colorManagementOptions.name = 'sRGB IEC61966-2.1'; o.postScriptOptions.postScriptLevel = PrinterPostScriptLevelEnum.PSLEVEL3;\n\
app.activeDocument.print(o);",
quoted(&dir.join("got.ps"))
),
)
.unwrap();
assert_eq!(report["console"]["lines"], json!(warnings));
let _ = std::fs::remove_dir_all(base);
}
#[test]
fn option_objects_are_bounded_and_go_stale_after_their_run() {
let base = folder("bounds");
let mut s = session(&base);
let e = failure(&mut s, &base, "for (var i = 0; i < 1000; i++) new PrintJobOptions();");
assert!(e.contains("RangeError") && e.contains("at most 256 print option objects"), "{e}");
let e = failure(&mut s, &base, "var o = new PrintOptions(); for (var i = 0; i < 1000; i++) o.jobOptions = new PrintJobOptions();");
assert!(e.contains("at most 256"), "{e}");
// A named engine keeps its globals, but an option object from an earlier run is stale.
run(&mut s, &base, "#targetengine keep\nvar held = new PrintOptions();").unwrap();
let e = failure(&mut s, &base, "#targetengine keep\nnew PrintOptions(); held.printPreset;");
assert!(e.contains("Stale print options"), "{e}");
let e = failure(&mut s, &base, "#targetengine keep\napp.activeDocument.print(held);");
assert!(e.contains("Stale print options"), "{e}");
let e = failure(&mut s, &base, "#targetengine keep\nvar o = new PrintOptions(); o.jobOptions = held.jobOptions;");
assert!(e.contains("Stale print options"), "{e}");
let _ = std::fs::remove_dir_all(base);
}
@@ -644,6 +644,24 @@ fn a_link_out_of_the_granted_folder_is_refused() {
let _ = std::fs::remove_dir_all(base);
}
/// Without options, `saveAs` takes the format from the path the script names, not from the file a
/// link at that path leads to.
#[cfg(unix)]
#[test]
fn save_as_takes_the_format_of_the_named_path_through_a_link() {
let base = folder("link-format");
let mut s = session(&base);
let dir = data_folder(&mut s, &base);
std::fs::write(dir.join("target.pdf"), "old").unwrap();
std::os::unix::fs::symlink(dir.join("target.pdf"), dir.join("drawing.svg")).unwrap();
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
logged(&mut s, &base, &format!("Folder.userData; app.activeDocument.saveAs(new File({}));", quoted(&dir.join("drawing.svg"))));
let written = std::fs::read(dir.join("target.pdf")).unwrap();
assert!(!written.starts_with(b"%PDF"), "the named .svg path writes SVG, not PDF");
assert!(String::from_utf8_lossy(&written).contains("<svg"), "an SVG file");
let _ = std::fs::remove_dir_all(base);
}
/// Bad arguments throw before anything is written or opened.
#[test]
fn bad_arguments_are_refused_with_an_error() {
+29 -8
View File
@@ -729,7 +729,9 @@ fn a_temporary_file_starts_private() {
}
/// A replaced sidecar that had no access ACL takes none from its folder's default ACL, whose named
/// users the sidecar's group bits would let in. (Skipped where `setfacl` or ACLs are missing.)
/// users the sidecar's group bits would let in. The default ACL is set through its extended
/// attribute, so the test runs where the `acl` tools are not installed. (Skipped on a file system
/// without ACLs.)
#[cfg(target_os = "linux")]
#[test]
fn a_replaced_sidecar_takes_no_inherited_acl() {
@@ -741,11 +743,28 @@ fn a_replaced_sidecar_takes_no_inherited_acl() {
&format!("var p = Folder.userData.fsName + '/a.xmp'; var f = new File(p); f.open('w'); f.write({PACKET:?}); f.close(); vc.log(p);"),
);
let path = PathBuf::from(log[0].as_str().unwrap());
let set = std::process::Command::new("setfacl").args(["-d", "-m", "u:nobody:rw"]).arg(path.parent().unwrap()).status();
if !set.is_ok_and(|s| s.success()) {
let _ = std::fs::remove_dir_all(base);
return;
let parent = path.parent().unwrap();
// `u::rw-,u:nobody:rw-,g::r--,m::rw-,o::r--` as the kernel's attribute: version 2, then tag,
// permissions and id per entry.
let mut acl = 2u32.to_le_bytes().to_vec();
for (tag, perm, id) in [(0x01u16, 6u16, u32::MAX), (0x02, 6, 65534), (0x04, 4, u32::MAX), (0x10, 6, u32::MAX), (0x20, 4, u32::MAX)] {
acl.extend(tag.to_le_bytes());
acl.extend(perm.to_le_bytes());
acl.extend(id.to_le_bytes());
}
match rustix::fs::setxattr(parent, "system.posix_acl_default", &acl, rustix::fs::XattrFlags::empty()) {
Ok(()) => {}
Err(e) if e == rustix::io::Errno::NOTSUP => {
let _ = std::fs::remove_dir_all(base);
return;
}
Err(e) => panic!("setting the default ACL: {e}"),
}
let mut buf = vec![0u8; 4096];
let probe = parent.join("probe");
std::fs::write(&probe, b"").unwrap();
assert!(rustix::fs::getxattr(&probe, "system.posix_acl_access", &mut buf[..]).is_ok(), "a new file takes the default ACL");
std::fs::remove_file(&probe).unwrap();
logged(
&mut s,
&base,
@@ -753,9 +772,11 @@ fn a_replaced_sidecar_takes_no_inherited_acl() {
var m = x.getXMP(); m.setProperty(XMPConst.NS_DC, 'format', 'changed'); x.putXMP(m); x.closeFile();",
);
assert!(std::fs::read_to_string(&path).unwrap().contains("<dc:format>changed</dc:format>"));
let acl = std::process::Command::new("getfacl").args(["--omit-header", "--absolute-names"]).arg(&path).output().unwrap();
let acl = String::from_utf8_lossy(&acl.stdout);
assert!(!acl.contains("nobody"), "the replacement takes no ACL entry the sidecar lacked: {acl}");
assert_eq!(
rustix::fs::getxattr(&path, "system.posix_acl_access", &mut buf[..]),
Err(rustix::io::Errno::NODATA),
"the replacement takes no ACL entry the sidecar lacked"
);
let _ = std::fs::remove_dir_all(base);
}
+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}");
}
+24 -1
View File
@@ -929,7 +929,20 @@ fn mutate_text(src: &str, cut: usize, edits: &[(usize, char)]) -> String {
fn svg_type_shifted_two_billion_points_exports_to_pdf() {
let svg = r#"<svg xmlns="http://www.w3.org/2000/svg"><text baseline-shift="-2147483649">f</text></svg>"#;
let d = vectorcraft_svg::import(svg).unwrap();
assert!(vectorcraft_engine::export_pdf(&d, &vectorcraft_pdf::PdfOptions::default()).is_ok());
// The type opens with its shift, so the export below meets a glyph that far out.
let mut shifts = Vec::new();
d.walk(|n| {
if let vectorcraft_doc::NodeKind::Text(t) = &n.kind {
shifts.extend(t.runs.iter().map(|r| r.style.baseline_shift));
}
});
assert!(shifts.iter().any(|&s| s.abs() > 2e9), "baseline shifts read: {shifts:?}");
let pdf = vectorcraft_engine::export_pdf(&d, &vectorcraft_pdf::PdfOptions::default()).unwrap();
// The PDF leaves the type out: reading it back finds no type.
let back = vectorcraft_pdf::import(&pdf).unwrap();
let mut text = 0;
back.walk(|n| text += usize::from(matches!(n.kind, vectorcraft_doc::NodeKind::Text(_))));
assert_eq!(text, 0, "type left out of the page");
}
proptest! {
@@ -8630,6 +8643,16 @@ fn a_long_thin_shape_with_a_shadow_renders_and_exports() {
let stream = canvas_stream(vec![with_effects(rectangle(10, (0.0, 0.0), (3_276_800.0, 50.0)), vec![shadow()])]);
let bytes = affinity_sample_file(&stream, None);
let doc = vectorcraft_engine::cmd::fileio::load("long.af", &bytes).unwrap().doc;
// The shape opens whole, with its shadow, so the exports below draw the shadow that far out.
let mut shadowed = Vec::new();
doc.walk(|n| {
if n.appearance.effects.iter().any(|e| e.id == "stylize.dropShadow") {
shadowed.push(n.id);
}
});
assert_eq!(shadowed.len(), 1, "one shape with a drop shadow");
let width = doc.bounds_of(&shadowed, false).map(|r| r.width());
assert!(width.is_some_and(|w| w > 3_000_000.0), "the shape is {width:?} pt wide");
survive("long shape", || Some(doc)).unwrap();
}
@@ -37,6 +37,7 @@ const OUTSIDE: &[(&str, &str, &str)] = &[
("Folder.prototype.remove", "var d = new Folder(p); d.remove();", "filesWritten"),
("Folder.prototype.rename", "var d = new Folder(p); d.rename(q);", "filesWritten"),
("Folder.prototype.execute", "var d = new Folder(p); d.execute();", "filesOpened"),
("Document.prototype.print", "var o = new PrintOptions(); o.jobOptions.file = new File(p); app.activeDocument.print(o);", "filesWritten"),
("Document.prototype.exportVariables", "app.activeDocument.exportVariables(f);", "filesWritten"),
("ExternalObject", "var lib = new ExternalObject(n);", "nativeCode"),
("Document.prototype.saveAs", "app.activeDocument.saveAs(f);", "filesWritten"),
@@ -96,8 +97,9 @@ const INSIDE: &[(&str, &str)] = &[
(
"Application.prototype.",
"activeDocument activeDocument= beep beep= constructor coordinateSystem coordinateSystem= documents doScript \
executeMenuCommand getIsFileOpen loadAction loadAction= open redo redraw selection selection= selectTool textFonts \
toString typename undo unloadAction unloadAction= userInteractionLevel userInteractionLevel=",
executeMenuCommand getIsFileOpen loadAction loadAction= open PPDFileList printPresetsList printerList redo redraw \
selection selection= selectTool textFonts toString typename undo unloadAction unloadAction= userInteractionLevel \
userInteractionLevel=",
),
("DocumentPreset.", "prototype"),
(
@@ -241,6 +243,88 @@ const INSIDE: &[(&str, &str)] = &[
("PDFOverprint.", "DISCARDPDFOVERPRINT PRESERVEPDFOVERPRINT"),
("SaveOptions.", "DONOTSAVECHANGES PROMPTTOSAVECHANGES"),
("UserInteractionLevel.", "DISPLAYALERTS DONTDISPLAYALERTS"),
// The print option classes and the enumerations of printing.
(
"",
"FontSubstitutionPolicy PageMarksTypes PostScriptImageCompressionType PrintArtworkDesignation PrintColorIntent \
PrintColorManagementOptions PrintColorProfile PrintColorSeparationMode PrintColorSeparationOptions \
PrintCoordinateOptions PrintFlattenerOptions PrintFontDownloadMode PrintFontOptions PrintJobOptions PrintOptions \
PrintOrientation PrintPageMarksOptions PrintPaperOptions PrintPosition PrintPostScriptOptions PrintTiling \
Printer PrinterPostScriptLevelEnum PrintingBounds",
),
("Printer.", "prototype"),
("Printer.prototype.", "constructor name printerInfo printerInfo= typename"),
("PrintOptions.", "prototype"),
(
"PrintOptions.prototype.",
"PPDName PPDName= colorManagementOptions colorManagementOptions= colorSeparationOptions colorSeparationOptions= \
constructor coordinateOptions coordinateOptions= flattenerOptions flattenerOptions= flattenerPreset \
flattenerPreset= fontOptions fontOptions= jobOptions jobOptions= pageMarksOptions pageMarksOptions= paperOptions \
paperOptions= postScriptOptions postScriptOptions= printPreset printPreset= printerName printerName= typename",
),
("PrintJobOptions.", "prototype"),
(
"PrintJobOptions.prototype.",
"artboardRange artboardRange= bitmapResolution bitmapResolution= collate collate= constructor copies copies= \
designation designation= file file= name name= printAllArtboards printAllArtboards= printArea printArea= \
printAsBitmap printAsBitmap= reversePages reversePages= typename",
),
("PrintColorManagementOptions.", "prototype"),
("PrintColorManagementOptions.prototype.", "colorProfileMode colorProfileMode= constructor intent intent= name name= typename"),
("PrintColorSeparationOptions.", "prototype"),
(
"PrintColorSeparationOptions.prototype.",
"colorSeparationMode colorSeparationMode= constructor convertSpotColors convertSpotColors= inkList inkList= \
overPrintBlack overPrintBlack= typename",
),
("PrintCoordinateOptions.", "prototype"),
(
"PrintCoordinateOptions.prototype.",
"constructor emulsion emulsion= fitToPage fitToPage= horizontalScale horizontalScale= orientation orientation= \
position position= tiling tiling= typename verticalScale verticalScale=",
),
("PrintFlattenerOptions.", "prototype"),
(
"PrintFlattenerOptions.prototype.",
"clipComplexRegions clipComplexRegions= constructor convertStrokesToOutlines convertStrokesToOutlines= \
convertTextToOutlines convertTextToOutlines= flatteningBalance flatteningBalance= gradientResolution \
gradientResolution= overprint overprint= rasterizationResolution rasterizationResolution= typename",
),
("PrintFontOptions.", "prototype"),
("PrintFontOptions.prototype.", "constructor downloadFonts downloadFonts= fontSubstitution fontSubstitution= typename"),
("PrintPageMarksOptions.", "prototype"),
(
"PrintPageMarksOptions.prototype.",
"bleedOffsetRect bleedOffsetRect= colorBars colorBars= constructor marksOffsetRect marksOffsetRect= pageInfoMarks \
pageInfoMarks= pageMarksType pageMarksType= registrationMarks registrationMarks= trimMarks trimMarks= \
trimMarksWeight trimMarksWeight= typename",
),
("PrintPaperOptions.", "prototype"),
("PrintPaperOptions.prototype.", "constructor height height= name name= offset offset= transverse transverse= typename width width="),
("PrintPostScriptOptions.", "prototype"),
(
"PrintPostScriptOptions.prototype.",
"binaryPrinting binaryPrinting= compatibleShading compatibleShading= constructor forceContinuousTone \
forceContinuousTone= imageCompression imageCompression= negativePrinting negativePrinting= postScriptLevel \
postScriptLevel= shadingResolution shadingResolution= typename",
),
("FontSubstitutionPolicy.", "SUBSTITUTEDEVICE SUBSTITUTEOBLIQUE SUBSTITUTETINT"),
("PageMarksTypes.", "Japanese Roman"),
("PostScriptImageCompressionType.", "IMAGECOMPRESSIONNONE JPEG RLE"),
("PrintArtworkDesignation.", "ALLLAYERS VISIBLELAYERS VISIBLEPRINTABLELAYERS"),
("PrintColorIntent.", "ABSOLUTECOLORIMETRIC PERCEPTUALINTENT RELATIVECOLORIMETRIC SATURATIONINTENT"),
("PrintColorProfile.", "CUSTOMPROFILE OLDSTYLEPROFILE PRINTERPROFILE SOURCEPROFILE"),
("PrintColorSeparationMode.", "COMPOSITE HOSTBASEDSEPARATION INRIPSEPARATION"),
("PrintFontDownloadMode.", "DOWNLOADCOMPLETE DOWNLOADNONE DOWNLOADSUBSET"),
("PrintOrientation.", "AUTOROTATE LANDSCAPE PORTRAIT REVERSELANDSCAPE REVERSEPORTRAIT"),
(
"PrintPosition.",
"TRANSLATEBOTTOM TRANSLATEBOTTOMLEFT TRANSLATEBOTTOMRIGHT TRANSLATECENTER TRANSLATELEFT TRANSLATERIGHT TRANSLATETOP \
TRANSLATETOPLEFT TRANSLATETOPRIGHT",
),
("PrintTiling.", "TILEFULLPAGES TILEIMAGEABLEAREAS TILESINGLEFULLPAGE"),
("PrinterPostScriptLevelEnum.", "PSLEVEL1 PSLEVEL2 PSLEVEL3"),
("PrintingBounds.", "ARTBOARDBOUNDS ARTWORKBOUNDS"),
(
"",
"CharacterAttributes CharacterStyle CharacterStyleAttributes CharacterStyles Characters Justification \
+2
View File
@@ -873,6 +873,7 @@ mod tests {
}
r.entry(&[V::Num(0.0), name("E")], Affine::IDENTITY);
let mesh = r.one_mesh().unwrap();
assert_eq!(mesh.points.len(), 9, "{mesh:?}");
assert!(mesh.points.iter().all(|q| q.p.x.is_finite() && q.p.y.is_finite() && q.handles.iter().all(|h| h.x.is_finite() && h.y.is_finite())));
}
@@ -962,6 +963,7 @@ mod tests {
assert!(!reader.unread, "{with_opacity} {data_first}");
let mesh = reader.one_mesh().unwrap();
let want = if with_opacity { 0.25 } else { 1.0 };
assert_eq!(mesh.points.len(), 4, "{with_opacity} {data_first}: {mesh:?}");
assert!(mesh.points.iter().all(|p| p.opacity == want), "{with_opacity} {data_first}: {mesh:?}");
}
}
+7 -3
View File
@@ -248,6 +248,9 @@ pub struct Structure {
/// The objects by their XML id (`AI10_ArtUID`), a text object by its slot's id: `None` for an
/// id two objects have.
pub xml_ids: HashMap<String, Option<NodeId>>,
/// The group of a styled text object and its look, by the text object's slot id. The group,
/// not the type in it, is hidden or locked where the text object was.
pub text_looks: HashMap<NodeId, NodeId>,
/// The objects the variable library binds to its variables, by their XML ids: the importer
/// binds those it keeps.
pub bindings: Vec<BindingRef>,
@@ -664,8 +667,9 @@ struct Reader<'a> {
ruler_guides: HashMap<NodeId, (Point, Point)>,
/// Legacy compound member groups, even when followed by the generic `9 () XW` marker.
compound_groups: HashSet<NodeId>,
/// Groups of a text object and its look (see [`Self::style_marker`]), which aren't a look.
text_looks: HashSet<NodeId>,
/// Groups of a text object and its look (see [`Self::style_marker`]), which aren't a look, each
/// with the text object's slot id.
text_looks: HashMap<NodeId, NodeId>,
/// Objects followed by samples of the pen (`(…) Xt n XD`), which aren't read: such an object
/// whose style has a Calligraphic brush that varies with the pen keeps its drawn look (see
/// [`Self::style_marker`]).
@@ -911,7 +915,7 @@ impl<'a> Reader<'a> {
looks: HashSet::new(),
ruler_guides: HashMap::new(),
compound_groups: HashSet::new(),
text_looks: HashSet::new(),
text_looks: HashMap::new(),
pen_samples: HashSet::new(),
group_ended: false,
mesh_ended: false,
@@ -1485,6 +1485,7 @@ impl<'a> Reader<'a> {
canvas_scale: self.canvas_scale,
symbols_own_size: self.symbols_own_size,
xml_ids: self.xml_ids,
text_looks: self.text_looks.into_iter().map(|(group, slot)| (slot, group)).collect(),
bindings,
bindings_skipped,
warnings,
+10 -4
View File
@@ -378,7 +378,7 @@ impl<'a> Reader<'a> {
}
}
"Xw" => self.gs.hidden = Self::nums(&vals).last() == Some(&1.0),
"A" => self.gs.locked = Self::nums(&vals).last() == Some(&1.0),
"A" => self.gs.locked = Self::nums(&vals).last().is_some_and(|&v| v != 0.0),
"XW" => self.state_marker(&vals, hidden),
// Gradients.
"Bd" => self.gradient_def = GradientDef::begin(&vals, &mut self.names),
@@ -822,7 +822,7 @@ impl<'a> Reader<'a> {
// The look is a group of paths, or one image where an effect (a blur, a shadow) rasterizes it.
if !self.hidden_ids.contains(&object.id)
|| self.hidden_ids.contains(&look.id) != hidden
|| self.text_looks.contains(&look.id)
|| self.text_looks.contains_key(&look.id)
|| !matches!(look.kind, NodeKind::Group { clip: false, .. } | NodeKind::Image(_))
{
return;
@@ -978,10 +978,15 @@ impl<'a> Reader<'a> {
let Some(mut look) = f.children.pop() else { return };
let state = (look.opacity, look.blend, look.isolate, look.knockout, look.knockout_shape);
(look.opacity, look.blend, look.isolate, look.knockout, look.knockout_shape) = (1.0, BlendMode::Normal, false, Knockout::Neutral, false);
let (visible, locked, slot) = (object.visible, object.locked, object.id);
(object.opacity, object.blend, object.isolate, object.knockout_shape) = (1.0, BlendMode::Normal, false, false);
object.visible = true;
object.locked = false;
let mut group = Node::group(self.doc.alloc_id(), vec![Arc::new(look), Arc::new(object)]);
(group.opacity, group.blend, group.isolate, group.knockout, group.knockout_shape) = state;
self.text_looks.insert(group.id);
group.visible = visible;
group.locked = locked;
self.text_looks.insert(group.id, slot);
if let Some(f) = self.frames.last_mut() {
f.children.push(group);
}
@@ -2212,7 +2217,8 @@ mod tests {
let ap = styled(&image, &look, &st, &paints).expect("an image takes one Warp");
let ids: Vec<&str> = ap.effects.iter().map(|e| e.id.as_str()).collect();
assert_eq!(ids, ["warp.arc"]);
assert!(ap.items.iter().all(|i| i.paint().is_none()), "{ap:?}");
// The image's own look: none of the look's fills and strokes.
assert!(ap.items.is_empty(), "{ap:?}");
// Not on a path, nor on an image with an opacity mask.
assert!(styled(&square(3, Paint::None), &look, &st, &paints).is_none());
let mut masked = image.clone();
+30
View File
@@ -291,6 +291,7 @@ fn object_tags_without_an_object_before_them_tag_nothing() {
let doc = read7(&layer7("L", &body)).doc;
let mut all = art(&doc);
all.extend(all.iter().flat_map(|n| n.children().cloned().unwrap_or_default()).collect::<Vec<_>>());
assert!(!all.is_empty(), "{body}: no art");
assert!(all.iter().all(|n| n.extras().attrs.is_none()), "{body}");
}
for bad in ["(x) (y) XT\n", "/id 3 XT\n", "XT\n"] {
@@ -12411,6 +12412,35 @@ fn type_with_an_art_brush_keeps_its_drawn_look() {
assert_eq!(brushed, 0, "{:?}", r.warnings);
}
/// A hidden styled text wrapper group inherits hidden state while its inner text and look retain
/// intrinsic visibility, so showing the group makes the inner artwork visible.
#[test]
fn hidden_styled_text_look_wrapper_group_showing_reveals_inner_text() {
let own: String = "/AI11Text :\n0 /FreeUndo ,\n0 /FrameIndex ,\n7 /StoryIndex ,\n;\n".lines().map(|l| format!("%_{l}\n")).collect();
let object = format!(
"0 Ae\nu\n/AI11Text :\n1 /FreeUndo ,\n0 /FrameIndex ,\n0 /StoryIndex ,\n;\n{RED}{}f\nU\n0 0.5 0 0 0 Xy\n0 0 Xd\n6 () XW\n1 Xw\n1 A\n{own}1 (Inked) XW\n0 Xw\n0 A\n",
rect_path(20.0, 18.0, 100.0, 62.0)
);
let def = format!("{}{}", lopsided_art("Ribbon art"), plugin_object(ART_BRUSH, "Ribbon", RIBBON));
let r = read_ok(&format!("{def}{}{}", art_style("Ribbon", 1.0, &STRETCHED, ""), layer(&object)));
let a = art(&r.doc);
assert_eq!(a.len(), 1, "wrapper group created: {a:#?}");
let group = &a[0];
assert!(!group.visible, "wrapper group must inherit hidden state");
assert!(group.locked, "wrapper group must inherit locked state");
let children = group.children().expect("must be a group of look and text");
assert_eq!(children.len(), 2);
for child in children {
assert!(child.visible, "inner child must retain intrinsic visibility");
assert!(!child.locked, "inner child must not be locked");
}
let mut shown = (**group).clone();
shown.visible = true;
for child in shown.children().unwrap() {
assert!(child.visible, "inner child remains visible when parent group is shown");
}
}
/// Each copy a Scatter brush places is its section's art turned over before the copy's rotation:
/// the side of the section with y up goes down the page with the rotation at 0° to the page, and
/// to the right of the path's direction when the rotation follows the path. A rotation turns the
+1 -1
View File
@@ -43,7 +43,7 @@ use super::ate::{Story, Texts};
mod build;
pub(super) mod compare;
mod layers;
pub(super) mod layers;
mod plan;
mod slots;
+19 -8
View File
@@ -4,8 +4,8 @@ use super::compare::{
};
use super::plan::{made_only, make_slots, plan, readable_all};
use super::slots::{
ART_LEFT_OUT, Content, DREW_DIFFERENTLY, Filled, MAX_PAIRS, MAX_SLOTS, MAX_TEXT, OUTLINE_REACH, SlotInfo, TEXT_LEFT_OUT, TYPE_LEFT_OUT,
collect_slots, extent, few, fill_slots, letters, text_objects, words,
ART_LEFT_OUT, Content, DREW_DIFFERENTLY, Filled, MAX_PAIRS, MAX_PLACE_PAIRS, MAX_SLOTS, MAX_TEXT, OUTLINE_REACH, SlotInfo, TEXT_LEFT_OUT,
TYPE_LEFT_OUT, collect_slots, extent, few, fill_slots, letters, text_objects, words,
};
use super::{
Affine, Arc, BTreeSet, Document, Node, NodeId, NodeKind, PathData, Rect, Scaling, Story, Structure, Texts, Unit, VariableKind, Vec2, ai,
@@ -350,6 +350,7 @@ pub(super) fn build_weighing(
canvas_scale,
symbols_own_size,
xml_ids,
text_looks,
bindings,
bindings_skipped,
warped_type,
@@ -653,7 +654,7 @@ pub(super) fn build_weighing(
None => unmark(&mut doc.layers, true, true, &mut vec![]),
}
doc.limit_depth_noting(&mut notes);
bind_variables(&mut doc, &bindings, bindings_skipped, &xml_ids, &filled, &mut notes);
bind_variables(&mut doc, &bindings, bindings_skipped, &xml_ids, &filled, &text_looks, &mut notes);
if placed_documents(&mut doc, &placed_pages, &placed_eps) && !notes.iter().any(|n| n == ai::LINKED_PREVIEWS) {
notes.push(ai::LINKED_PREVIEWS.to_string());
}
@@ -731,7 +732,9 @@ fn to_placed_documents(
/// Bind the objects of `doc` to the variables of its library that `bindings` binds them to, each
/// object named by its XML id (`ids`: the object read with that id, or what `filled` made of a text
/// object's slot: for a visibility variable every object that took the slot's place, for a text
/// variable the one text object among them). An object is bound when it is of the variable's kind:
/// variable the one text object among them). A visibility variable binds a styled text object's
/// group with its look (`text_looks`, by slot) in place of the type: the group is what is hidden or
/// shown. An object is bound when it is of the variable's kind:
/// type for a text variable, a linked image for an image variable, any object for a visibility
/// variable. Locked and hidden objects, objects in locked or hidden layers and groups, and objects
/// on locked artboards keep their bindings. Graph variables and
@@ -743,6 +746,7 @@ fn bind_variables(
skipped: usize,
ids: &std::collections::HashMap<String, Option<NodeId>>,
filled: &std::collections::HashMap<NodeId, Filled>,
text_looks: &std::collections::HashMap<NodeId, NodeId>,
notes: &mut Vec<String>,
) {
let mut skipped = skipped;
@@ -753,7 +757,12 @@ fn bind_variables(
let mut bound = vec![];
for b in bindings {
let kind = doc.variables.variable(&b.variable).map(|v| v.kind);
let targets = match (b.target.as_ref().and_then(|t| ids.get(t).copied().flatten()), kind) {
let target = b.target.as_ref().and_then(|t| ids.get(t).copied().flatten());
let target = match kind {
Some(VariableKind::Visibility) => target.map(|id| text_looks.get(&id).copied().unwrap_or(id)),
_ => target,
};
let targets = match (target, kind) {
(Some(id), Some(kind)) => match filled.get(&id) {
Some(f) if kind == VariableKind::Visibility => f.objects.clone(),
Some(f) => match f.text.as_slice() {
@@ -1514,9 +1523,11 @@ fn slot_content(
}
// The page's type is matched with every text object whose type isn't made, and weighed against
// where every made one draws: that has its limits (the slots of type that looks draw are within
// them, see `build_from`).
// them, see `build_from`). A file whose text document makes all but a few text objects is
// matched only with those few (#9176).
let open = infos.iter().zip(&made).filter(|(i, m)| i.look.is_none() && m.is_none()).count();
if open > MAX_SLOTS || infos.len().saturating_mul(pages[0].len()) > MAX_PAIRS {
let shown = pages[0].len();
if open > MAX_SLOTS || open.saturating_mul(shown) > MAX_PAIRS || infos.len().saturating_mul(shown) > MAX_PLACE_PAIRS {
return Err("it has too many text objects".into());
}
let mut content = plan(infos, stories, made, template, to_doc, pages, notes);
@@ -2817,7 +2828,7 @@ mod candidate_tests {
bind("v_graph", "path"),
];
let mut notes = vec![];
bind_variables(&mut doc, &refs, 3, &ids, &filled, &mut notes);
bind_variables(&mut doc, &refs, 3, &ids, &filled, &Default::default(), &mut notes);
let sorted = |mut v: Vec<NodeId>| {
v.sort();
v
+83 -3
View File
@@ -172,13 +172,19 @@ pub fn layered_ai_from(
}
// The PDF part, its pages placed and named as the editing data's artboards are, when the
// layers can't be used (`why`).
let from_pdf_part = |mut visible: Document, mut warnings: Vec<String>, why: &str| {
let from_pdf_part = |mut visible: Document, mut warnings: Vec<String>, why: &str, layers_read: bool| {
let mut read = ai::Names::new(names);
let mut board_names = ai::Names::new(names);
let (boards, active) = ai::artboards(&data, &mut board_names);
if place_pages(&boards, active, &mut visible, unit) {
read.absorb(board_names);
}
// The editing data's locks, read again only here (and only when its layers could be read):
// the layers read below are spent on the editable document, which most files open as.
if let Some(layers) = layers_read.then(|| ai::read_over_page(&data, false, names).ok()).flatten() {
let private_layers: Vec<LockTree> = layers.doc.layers.iter().map(|l| LockTree::from_node(l)).collect();
apply_private_layer_locks(&mut visible.layers, &private_layers);
}
let have = visible.patterns.len();
let own_palette = use_palette(&data, &mut visible, &mut read);
use_brushes(&data, &mut visible, have, &mut warnings, &mut read);
@@ -199,7 +205,9 @@ pub fn layered_ai_from(
// The envelopes of type the page doesn't hold against layers that don't draw as it, and how many
// envelopes of type the layers had.
let (mut free, mut count) = (None, 0);
let built = structure.unwrap_or_else(|| read().map(Box::new)).and_then(|structure| {
let structure = structure.unwrap_or_else(|| read().map(Box::new));
let layers_read = structure.is_ok();
let built = structure.and_then(|structure| {
count = structure.warped_type.envelope_count();
build_weighing(*structure, &data, Some(&visible), Page::Artboard, outlined, trust, unit, &mut free, &mut text)
});
@@ -230,7 +238,7 @@ pub fn layered_ai_from(
all.extend(notes.into_iter().filter(|n| !all.contains(n)).collect::<Vec<_>>());
(done, all, true)
}
Err(why) => from_pdf_part(visible, warnings, &why),
Err(why) => from_pdf_part(visible, warnings, &why, layers_read),
}
}
@@ -245,6 +253,78 @@ fn holds_type_envelope(nodes: &[Arc<Node>]) -> bool {
})
}
/// Lightweight lock metadata snapshot of a node hierarchy, preserving names and lock states
/// without holding `Arc<Node>` references to the artwork tree.
#[derive(Clone, Debug, Default)]
pub(crate) struct LockTree {
pub name: Option<String>,
pub locked: bool,
pub children: Vec<LockTree>,
}
impl LockTree {
pub fn from_node(node: &Node) -> Self {
Self {
name: node.name.clone(),
locked: node.locked,
children: node.children().map(|kids| kids.iter().map(|k| Self::from_node(k)).collect()).unwrap_or_default(),
}
}
}
/// Match unique names between visible nodes and private lock trees.
fn unique_name_pairs<T: std::ops::Deref<Target = Node>>(vis_nodes: &[T], priv_nodes: &[LockTree]) -> Vec<(usize, usize)> {
let mut priv_names: std::collections::HashMap<&str, (usize, usize)> = std::collections::HashMap::new();
for (i, p) in priv_nodes.iter().enumerate() {
if let Some(name) = p.name.as_deref() {
let entry = priv_names.entry(name).or_insert((0, i));
entry.0 += 1;
}
}
let mut vis_names: std::collections::HashMap<&str, usize> = std::collections::HashMap::new();
for v in vis_nodes.iter() {
if let Some(name) = v.name.as_deref() {
*vis_names.entry(name).or_insert(0) += 1;
}
}
let mut pairs = Vec::new();
for (v_idx, vis) in vis_nodes.iter().enumerate() {
if let Some(name) = vis.name.as_deref()
&& vis_names.get(name).copied() == Some(1)
&& let Some(&(1, p_idx)) = priv_names.get(name)
{
pairs.push((v_idx, p_idx));
}
}
pairs
}
/// Apply lock states from private data layers to visible PDF layers.
pub(crate) fn apply_private_layer_locks(visible_layers: &mut [Arc<Node>], private_layers: &[LockTree]) {
// Only layers that are evidently the same one (a name unique on both sides) take its locks: one
// layer each is no evidence, since a PDF part without layers comes in on a layer named for its
// page, and the editing data it was set aside for may not be the art on it.
for (v_idx, p_idx) in unique_name_pairs(visible_layers, private_layers) {
apply_node_locks(Arc::make_mut(&mut visible_layers[v_idx]), &private_layers[p_idx]);
}
}
fn apply_node_locks(vis: &mut Node, priv_: &LockTree) {
if priv_.locked {
vis.locked = true;
}
let Some(vis_kids) = vis.children_mut() else { return };
if vis_kids.is_empty() || priv_.children.is_empty() {
return;
}
for (v_idx, p_idx) in unique_name_pairs(vis_kids.as_slice(), &priv_.children) {
apply_node_locks(Arc::make_mut(&mut vis_kids[v_idx]), &priv_.children[p_idx]);
}
}
/// The `.ai` whose editing copy is `private` (as [`layered_ai`] takes it) from its layers alone,
/// without its PDF part, whose pages (each its trim box in points, width and height) are `pages`
/// and are in units of `unit` points (its first page's `UserUnit`): the document and the notes of
+162 -23
View File
@@ -154,8 +154,19 @@ pub(super) fn made_only(
if looks && infos.len().saturating_mul(shown.len()) <= MAX_PAIRS {
let spelled: Vec<String> =
content.iter().map(|c| if let Content::Made(node, ..) = c { spelling(&plain_text(node)) } else { String::new() }).collect();
let made_type = |o: &[Arc<Node>]| covered(o, &content, |_| true) && has_made_words(o, &content, &spelled);
// Past the word searches, type where made type draws is taken to be that type.
let (mut checks, mut unchecked) = (WordChecks::new(), false);
let mut made_type = |o: &[Arc<Node>]| {
covered(o, &content, |_| true)
&& has_made_words(o, &content, &spelled, &mut checks).unwrap_or_else(|| {
unchecked = true;
true
})
};
let mut spare: Vec<Vec<Arc<Node>>> = shown.iter().filter(|o| !made_type(o)).cloned().collect();
if unchecked {
note_unchecked(warn);
}
fill_look_slots(infos, &mut content, &mut spare);
for c in &content {
if let Content::Page(parts) = c {
@@ -173,7 +184,7 @@ pub(super) fn made_only(
match see_page_type(&mut content, untaken) {
Some(0) => {}
Some(_) => warn.push(PAGE_TYPE_LEFT_OUT.into()),
None => warn.push(PAGE_TYPE_UNCHECKED.into()),
None => note_unchecked(warn),
}
drop_look_slots(infos, &mut content);
fill_hidden(infos, stories, &mut content, hidden);
@@ -274,17 +285,64 @@ fn fill_look_slots(infos: &[SlotInfo], content: &mut [Content], spare: &mut Vec<
drop_look_slots(infos, content);
}
/// How many more times a word of the page's type may be looked for in a text object's type. The
/// page's type is weighed against where every text object lies up to `MAX_PLACE_PAIRS` pairs, a box
/// against a box, but each text object a piece of it lies on can be searched for each of its words:
/// those searches are held to `MAX_PAIRS` of their own.
struct WordChecks(usize);
impl WordChecks {
fn new() -> Self {
WordChecks(MAX_PAIRS)
}
/// One more search, if any are left.
fn spend(&mut self) -> Option<()> {
self.0 = self.0.checked_sub(1)?;
Some(())
}
/// Are no searches left?
fn spent(&self) -> bool {
self.0 == 0
}
}
/// Has made type that shows and draws where the page's text object `object` lies every word of it
/// ([`spelling`], each slot's in `spelled`), in any order?
fn has_made_words(object: &[Arc<Node>], content: &[Content], spelled: &[String]) -> bool {
let Some(r) = extent(object) else { return true };
/// ([`spelling`], each slot's in `spelled`), in any order? `None` once `checks` runs out before
/// that is known.
fn has_made_words(object: &[Arc<Node>], content: &[Content], spelled: &[String], checks: &mut WordChecks) -> Option<bool> {
let Some(r) = extent(object) else { return Some(true) };
if checks.spent() {
return None;
}
let near: Vec<&String> = content
.iter()
.zip(spelled)
.filter(|(c, _)| matches!(c, Content::Made(_, Some(region), _) if !region.intersect(r).is_zero_area()))
.map(|(_, s)| s)
.collect();
object_words(object).iter().all(|w| near.iter().any(|s| s.contains(w.as_str())))
for w in object_words(object) {
let mut found = false;
for s in &near {
checks.spend()?;
if s.contains(w.as_str()) {
found = true;
break;
}
}
if !found {
return Some(false);
}
}
Some(true)
}
/// Note once in `warn` that some of the page's type wasn't checked against the text objects.
fn note_unchecked(warn: &mut Vec<String>) {
if !warn.iter().any(|w| w == PAGE_TYPE_UNCHECKED) {
warn.push(PAGE_TYPE_UNCHECKED.into());
}
}
/// The text slots for type that a look draws and that have nothing have no type of their own to hold
@@ -438,9 +496,16 @@ pub(super) fn plan(
let made_stories: std::collections::BTreeSet<u32> = infos.iter().zip(&made).filter(|(_, m)| m.is_some()).filter_map(|(i, _)| i.story).collect();
let open: Vec<bool> = infos.iter().zip(&made).map(|(i, m)| m.is_none() && i.story.is_none_or(|s| !made_stories.contains(&s))).collect();
let owner = match_page_objects(infos, &lines, &open, shown);
// Where the made type that doesn't show lies, by slot.
let hidden_at: Vec<(usize, Rect)> =
infos.iter().zip(&made).enumerate().filter_map(|(k, (info, m))| Some((k, m.as_ref().filter(|_| !info.shown)?.1?))).collect();
// Where the made type that doesn't show lies, and the letters of its lines (it has lines).
let hidden_at: Vec<(Rect, Vec<String>)> = infos
.iter()
.zip(&made)
.enumerate()
.filter_map(|(k, (info, m))| {
let place = m.as_ref().filter(|_| !info.shown)?.1?;
Some((place, lines.get(k)?.as_ref()?.iter().map(|(text, _)| letters(text)).collect()))
})
.collect();
// Type the text document makes, shown or not: the page's pieces of it aren't needed. Its box
// stays that of type without a layout here: with text objects whose type isn't made stacked on
// made type that has their words (the copies of an outlined heading), the page's pieces in the
@@ -448,17 +513,34 @@ pub(super) fn plan(
let mut content = made_content(infos, made, false);
// Is `object` the type of a text object that doesn't show, as the page draws it: in its frame,
// with its words? (A copied object's lines are where its original's are, so they don't say.)
let hidden_type = |object: &[Arc<Node>]| {
let Some(r) = extent(object) else { return false };
// `None` once `checks` runs out before that is known.
let hidden_type = |object: &[Arc<Node>], checks: &mut WordChecks| -> Option<bool> {
let Some(r) = extent(object) else { return Some(false) };
let texts: Vec<Vec<String>> =
object.iter().filter_map(|n| if let NodeKind::Text(t) = &n.kind { Some(words(&t.plain_text())) } else { None }).collect();
hidden_at.iter().any(|(k, place)| {
place.intersect(r).area() >= 0.5 * r.area().max(1e-9)
&& lines.get(*k).and_then(Option::as_ref).is_some_and(|l| {
!texts.is_empty()
&& texts.iter().all(|ws| !ws.is_empty() && ws.iter().all(|w| l.iter().any(|(text, _)| letters(text).contains(w.as_str()))))
})
})
if texts.is_empty() || texts.iter().any(Vec::is_empty) {
return Some(false);
}
for (place, l) in &hidden_at {
if place.intersect(r).area() < 0.5 * r.area().max(1e-9) {
continue;
}
let mut all = true;
'words: for w in texts.iter().flatten() {
for text in l {
checks.spend()?;
if text.contains(w.as_str()) {
continue 'words;
}
}
all = false;
break;
}
if all {
return Some(true);
}
}
Some(false)
};
// The letters and digits of each slot's made type that shows, in any script, in lower case.
let spelled: Vec<String> = content
@@ -472,6 +554,12 @@ pub(super) fn plan(
})
.collect();
let mut spare: Vec<Vec<Arc<Node>>> = vec![];
// The word searches below are held to their own budget: past it, type where made type that shows
// draws is taken to be that type (made type is there either way), and type where only made type
// that doesn't show lies is spare type, as any type no text object takes: it goes into a slot
// or with another text object's type, else it is left out with a note (taken as the hidden
// type, it would be dropped unnoted).
let (mut checks, mut unchecked) = (WordChecks::new(), false);
for (j, object) in shown.iter().enumerate() {
match owner.get(j).copied().flatten() {
Some(k) => match content.get_mut(k) {
@@ -479,13 +567,28 @@ pub(super) fn plan(
Some(c) => *c = Content::Page(object.clone()),
None => {}
},
// What lies where made type draws, with its words, is that type as the page draws it (in
// another font, maybe, and in any script).
None if covered(object, &content, |_| true) && has_made_words(object, &content, &spelled) => {}
None if hidden_type(object) => {}
None => spare.push(object.clone()),
None => {
// What lies where made type draws, with its words, is that type as the page draws it
// (in another font, maybe, and in any script).
let theirs = covered(object, &content, |_| true)
&& has_made_words(object, &content, &spelled, &mut checks).unwrap_or_else(|| {
unchecked = true;
true
});
let hidden = !theirs
&& hidden_type(object, &mut checks).unwrap_or_else(|| {
unchecked = true;
false
});
if !theirs && !hidden {
spare.push(object.clone());
}
}
}
}
if unchecked {
note_unchecked(warn);
}
// The page's type that no made type takes is the spare type below.
let _ = see_page_type(&mut content, shown);
for (k, c) in content.iter_mut().enumerate() {
@@ -600,3 +703,39 @@ fn fill_hidden(infos: &[SlotInfo], stories: &[Option<Arc<Story>>], content: &mut
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use vectorcraft_doc::{CharStyle, TextObject};
fn text(id: u64, s: &str) -> Node {
let style = CharStyle { size: 12.0, ..CharStyle::default() };
Node::new(NodeId(id), NodeKind::Text(Box::new(TextObject::point(Point::new(100.0, 100.0), s, style))))
}
/// The page's type is searched for in every made text object that draws where it lies, word by
/// word: those searches stop when their budget runs out, saying they didn't finish, however many
/// made text objects lie there. A word is searched for only until a text object has it.
#[test]
fn word_searches_of_the_page_s_type_stop_when_their_budget_runs_out() {
let everywhere = Rect::new(-1e4, -1e4, 1e4, 1e4);
let slots = 50;
let content: Vec<Content> = (0..slots).map(|k| Content::Made(Box::new(text(k, "Other type")), Some(everywhere), false)).collect();
let spelled: Vec<String> =
content.iter().map(|c| if let Content::Made(n, ..) = c { spelling(&plain_text(n)) } else { String::new() }).collect();
// A word no made type has is searched for in each of them.
let missing = vec![Arc::new(text(1000, "Alpha beta"))];
let one_word_everywhere = slots as usize;
let mut short = WordChecks(one_word_everywhere - 1);
assert_eq!(has_made_words(&missing, &content, &spelled, &mut short), None, "past the budget the answer isn't known");
assert!(short.spent());
let mut enough = WordChecks(one_word_everywhere);
assert_eq!(has_made_words(&missing, &content, &spelled, &mut enough), Some(false));
// Words that the first made type has are found there, without searching the others.
let present = vec![Arc::new(text(1001, "other TYPE"))];
let mut few = WordChecks(one_word_everywhere);
assert_eq!(has_made_words(&present, &content, &spelled, &mut few), Some(true));
assert!(one_word_everywhere - few.0 < one_word_everywhere / 2, "{} searches", one_word_everywhere - few.0);
}
}
+111 -6
View File
@@ -50,6 +50,11 @@ pub(crate) const MAX_TEXT: usize = 16 << 20;
/// kept as outlines and a node of the page's type.
pub(super) const MAX_PAIRS: usize = 4_000_000;
/// Most pairs of a text object whose type is made and a piece of the page's type weighed only by
/// where each lies (a box against a box, far cheaper than matching the page's type with a text
/// object's words, which [`MAX_PAIRS`] limits).
pub(super) const MAX_PLACE_PAIRS: usize = 4 * MAX_PAIRS;
/// `names` for a note: the first few, and how many more.
pub(super) fn few(names: BTreeSet<String>) -> String {
const SHOWN: usize = 5;
@@ -307,12 +312,6 @@ pub(super) fn fill_slots(
.iter()
.map(|p| {
let mut p = reid(doc, p);
if !visible {
Arc::make_mut(&mut p).visible = false;
}
if locked {
Arc::make_mut(&mut p).locked = true;
}
if let Some(name) = name.filter(|_| matches!(p.kind, NodeKind::Text(_))) {
Arc::make_mut(&mut p).name = Some(name.clone());
}
@@ -321,6 +320,7 @@ pub(super) fn fill_slots(
.collect();
let mut text = vec![];
text_ids(&parts, &mut text);
let mut wrapped = false;
// When the page draws each of them with no transparency, the slot's, or the slot's
// combined with that of the objects around it, the slot's takes its place: on the one
// part, or on a group of several when the slot has transparency. Otherwise every part
@@ -342,9 +342,12 @@ pub(super) fn fill_slots(
(p.opacity, p.blend, p.isolate, p.knockout, p.knockout_shape) = (state.0, state.1, state.2, state.3, shape);
} else if transparent {
let mut group = Node::group(doc.alloc_id(), std::mem::take(&mut parts));
group.visible = visible;
group.locked = locked;
(group.opacity, group.blend, group.isolate, group.knockout, group.knockout_shape) =
(state.0, state.1, state.2, state.3, shape);
parts.push(Arc::new(group));
wrapped = true;
}
}
// A wrap object stays one: the page's parts of it in a group, when there are several.
@@ -352,12 +355,25 @@ pub(super) fn fill_slots(
if parts.len() > 1 {
let mut group = Node::group(doc.alloc_id(), std::mem::take(&mut parts));
group.visible = visible;
group.locked = locked;
parts.push(Arc::new(group));
wrapped = true;
}
for p in &mut parts {
Arc::make_mut(p).extras_mut().wrap = wrap;
}
}
if !wrapped {
for p in &mut parts {
let p = Arc::make_mut(p);
if !visible {
p.visible = false;
}
if locked {
p.locked = true;
}
}
}
// One text object with the slot's appearance and transparency keeps its graphic style.
if let ([p], Some(a)) = (parts.as_mut_slice(), styled.as_ref())
&& linked.is_some()
@@ -751,4 +767,93 @@ mod tests {
let inner = nodes[0].children().unwrap()[0].id;
assert_eq!(filled.get(&slot), Some(&Filled { text: vec![inner], objects: vec![nodes[0].id, nodes[1].id] }));
}
/// A transparent slot wrapper group inherits hidden state while its inner children retain
/// their original visibility (both visible and intrinsically hidden), so showing the group
/// reveals only the intrinsically visible artwork.
#[test]
fn transparent_slot_wrapper_group_showing_reveals_inner_art() {
let mut doc = Document::new(100.0, 100.0);
let mut slot = Node::group(doc.alloc_id(), vec![]);
slot.name = Some("\u{0}text0:0".into());
slot.visible = false;
slot.locked = true;
slot.opacity = 0.5; // see_through(n) == true -> transparent == true
let part = |doc: &mut Document, x: f64, visible: bool| {
let t = vectorcraft_doc::TextObject::point(Point::new(x, 50.0), "Part", Default::default());
let mut node = Node::new(doc.alloc_id(), NodeKind::Text(Box::new(t)));
node.visible = visible;
Arc::new(node)
};
// Page run contains both a visible child and an intrinsically hidden child:
let parts = vec![part(&mut doc, 10.0, true), part(&mut doc, 60.0, false)];
let mut nodes = vec![Arc::new(slot)];
let mut content = vec![Content::Page(parts)].into_iter();
let (mut empty, mut made, mut filled) = (0, vec![], std::collections::HashMap::new());
fill_slots(&mut doc, &mut nodes, &mut content, &Default::default(), &mut empty, &mut made, &mut vec![], &mut filled);
assert_eq!(nodes.len(), 1);
let group = &nodes[0];
assert!(!group.visible, "wrapper group must inherit hidden state (visible = false)");
assert!(group.locked, "wrapper group must inherit locked state");
let children = group.children().expect("must be a group of parts");
assert_eq!(children.len(), 2);
assert!(children[0].visible, "intrinsically visible child retains visible = true");
assert!(!children[0].locked, "inner child must not be locked");
assert!(!children[1].visible, "intrinsically hidden child retains visible = false");
assert!(!children[1].locked, "inner child must not be locked");
// Showing the group updates only the group node's visible field:
let mut shown = (**group).clone();
shown.visible = true;
assert!(shown.visible);
let shown_children = shown.children().unwrap();
assert!(shown_children[0].visible, "intrinsically visible child is visible when parent group is shown");
assert!(!shown_children[1].visible, "intrinsically hidden child remains hidden when parent group is shown");
}
/// A wrap slot wrapper group inherits hidden and locked states without overwriting children's
/// original visibility flags when a page run contains both visible and intrinsically hidden children.
#[test]
fn wrap_slot_wrapper_group_preserves_child_visibility_and_showing_reveals_art() {
let mut doc = Document::new(100.0, 100.0);
let mut slot = Node::group(doc.alloc_id(), vec![]);
slot.name = Some("\u{0}text0:0".into());
slot.visible = false;
slot.locked = true;
let wrap = vectorcraft_doc::TextWrap { offset: 3.0, invert: true };
slot.extras_mut().wrap = Some(wrap);
let part = |doc: &mut Document, x: f64, visible: bool| {
let t = vectorcraft_doc::TextObject::point(Point::new(x, 50.0), "Part", Default::default());
let mut node = Node::new(doc.alloc_id(), NodeKind::Text(Box::new(t)));
node.visible = visible;
Arc::new(node)
};
let parts = vec![part(&mut doc, 10.0, true), part(&mut doc, 60.0, false)];
let mut nodes = vec![Arc::new(slot)];
let mut content = vec![Content::Page(parts)].into_iter();
let (mut empty, mut made, mut filled) = (0, vec![], std::collections::HashMap::new());
fill_slots(&mut doc, &mut nodes, &mut content, &Default::default(), &mut empty, &mut made, &mut vec![], &mut filled);
assert_eq!(nodes.len(), 1);
let group = &nodes[0];
assert!(!group.visible, "wrap wrapper group must inherit hidden state");
assert!(group.locked, "wrap wrapper group must inherit locked state");
let children = group.children().expect("must be a group of parts");
assert_eq!(children.len(), 2);
assert!(children[0].visible, "intrinsically visible child retains visible = true");
assert!(!children[0].locked, "inner child must not be locked");
assert!(!children[1].visible, "intrinsically hidden child retains visible = false");
assert!(!children[1].locked, "inner child must not be locked");
let mut shown = (**group).clone();
shown.visible = true;
let shown_children = shown.children().unwrap();
assert!(shown_children[0].visible, "intrinsically visible child is visible when parent group is shown");
assert!(!shown_children[1].visible, "intrinsically hidden child remains hidden when parent group is shown");
}
}
+1
View File
@@ -241,6 +241,7 @@ fn cmyk_jpegs_keep_their_ink_amounts() {
/ImageMatrix [2 0 0 -2 0 2] /DataSource currentfile /ASCIIHexDecode filter /DCTDecode filter >> image\n{data}>"
));
let got = inks(&r).data;
assert_eq!(got.len(), want.len(), "{decode}: {got:?}");
assert!(got.iter().zip(&want).all(|(a, b)| a.abs_diff(*b) <= 3), "{decode}: {got:?}");
}
}
+388
View File
@@ -2240,6 +2240,38 @@ fn ai_variable_bindings_bind_the_objects_they_name() {
assert!(!r.warnings.iter().any(|w| w.contains("variable library")), "{:?}", r.warnings);
}
/// Hidden, locked type whose style comes in as a group of its drawn look and the type (the look has
/// its own transparency) is hidden and locked on that group. A visibility variable bound to the
/// type binds the group, so showing it shows the type; a text variable still binds the type.
#[test]
fn a_visibility_variable_on_hidden_styled_type_binds_the_group_that_hides_it() {
use vectorcraft_testkit::ai::{XmlValue, named, variable_library_data, xml_element, xml_node};
let declare = |name: &str, t: &str| {
let uid = "/XMLUIDREF : (type_x5F_1) ;";
let attributes = [("trait", XmlValue::Str(t)), ("varName", XmlValue::Unicode(name)), ("docRef", XmlValue::Raw(uid))];
xml_node(1, "variable", XmlValue::Str(""), &attributes, &[])
};
let declared = vec![declare("v_shown", "visibility"), declare("v_text", "textcontent")];
let set = xml_element("variableSet", &[("locked", "none")], &[xml_element("variables", &[], &declared)]);
let library = variable_library_data(&xml_element("variableSets", &[], &[set]));
let doc = text_document(&[("Bang\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0)]);
let drawing = "0 0 1 0 k\n54 56 m\n100 56 L\n100 80 L\n54 80 L\nf";
// The look at half opacity; the type hidden (`1 Xw`) and locked (`1 A`), with its XML id.
let look = format!("0 Ae\nu\n/AI11Text :\n1 /FreeUndo ,\n0 /FrameIndex ,\n0 /StoryIndex ,\n;\n{drawing}\nU\n0 0.5 0 0 0 Xy\n0 0 Xd\n6 () XW\n");
let own: String = text_object(0).lines().map(|l| format!("%_{l}\n")).collect();
let styled = format!("{look}1 Xw\n1 A\n{own}{}1 (Unlisted) XW\n0 Xw\n0 A\n", named("type_x5F_1"));
let art = native_with_text(&(library + &layer("Art", true, &styled)), &doc);
let (d, notes) = crate::ai_alone(&private(&art)).unwrap();
let a = d.layers[0].children().unwrap();
let [group] = a.as_slice() else { panic!("one group of the look and the type: {a:#?} {notes:?}") };
assert!(matches!(group.kind, NodeKind::Group { .. }) && !group.visible && group.locked, "{group:#?}");
let type_id = group.children().unwrap().iter().find(|n| matches!(n.kind, NodeKind::Text(_))).map(|n| n.id);
assert!(type_id.is_some(), "{group:#?}");
let vars = &d.variables;
assert_eq!(vars.objects_of("v_shown"), [group.id], "the hidden group, not the type in it: {notes:?}");
assert_eq!(vars.objects_of("v_text").first().copied(), type_id, "{notes:?}");
}
/// An EPS whose editing data can't be used, a palette with no layers among others, comes in as its
/// page with the swatches and color groups of that palette in place of the defaults.
#[test]
@@ -8238,6 +8270,7 @@ fn type_with_a_distort_effect_comes_in_as_type_with_it_live() {
// An angle that isn't a number: the drawing as paths, and no effect on the type.
let (texts, paths) = open("Adobe Twirl", "NaN /Real (angle) ,\n");
assert_eq!(paths, 1, "{texts:?}");
assert_eq!(texts.len(), 1, "{texts:?}");
assert!(texts.iter().all(|(_, effects)| effects.is_empty()), "{texts:?}");
}
@@ -8664,6 +8697,361 @@ fn trusted_editing_data_keeps_an_artboard_taller_than_its_pdf_page() {
assert!(!read, "the uncapped dimension must still match: {w:?}");
}
/// A locked layer as the format writes it.
fn locked_layer(name: &str, body: &str) -> String {
format!("%AI5_BeginLayer\n1 1 0 1 0 0 1 0 79 128 255 0 50 0 Lb\n({name}) Ln\n{body}\nLB\n%AI5_EndLayer--\n")
}
#[test]
fn ai_locked_layers_and_groups_preserve_locks() {
let art_locked_group = format!("1 A\nu\n{}\nU\n0 A", square(10, 10));
let plain_layer = layer("Unlocked Layer", true, &square(0, 0));
let locked_l = locked_layer("Locked Layer", &art_locked_group);
let n = native(&format!("{plain_layer}{locked_l}"));
let file = private(&n);
let (doc, notes, read) = crate::layered_ai(&file, pdf_part(10.0, 86.0), vec![], false, true, 1.0);
assert!(read, "{notes:?}");
let unlocked = doc.layers.iter().find(|l| l.name.as_deref() == Some("Unlocked Layer")).unwrap();
let locked = doc.layers.iter().find(|l| l.name.as_deref() == Some("Locked Layer")).unwrap();
assert!(!unlocked.locked, "Unlocked Layer is not locked");
assert!(locked.locked, "Locked Layer retains locked == true");
let group = locked.children().and_then(|c| c.iter().find(|n| matches!(n.kind, NodeKind::Group { .. })));
assert!(group.is_some_and(|g| g.locked), "group with 1 A retains locked == true");
}
#[test]
fn ai_fallback_to_pdf_part_preserves_private_stream_layer_and_group_locks() {
use std::sync::Arc;
let art_locked_group = format!("1 A\nu\n{}\nU\n%_/ArtDictionary :\n%_(Locked Subgroup) /String (AIArtName) ,\n%_;\n0 A", square(10, 10));
let locked_l = locked_layer("Map Layer", &art_locked_group);
let n = native(&locked_l);
let file = private(&n);
let mut pdf = Document::new(100.0, 100.0);
pdf.layers.clear();
let mut vis_layer = Node::layer(pdf.alloc_id(), "Map Layer", LayerColor::Preset(0));
vis_layer.locked = false;
let mut vis_group = Node::group(pdf.alloc_id(), vec![]);
vis_group.name = Some("Locked Subgroup".to_string());
vis_group.locked = false;
if let NodeKind::Layer { children, .. } = &mut vis_layer.kind {
children.push(Arc::new(vis_group));
}
pdf.layers.push(Arc::new(vis_layer));
let layers = crate::AiLayers::decode(&file);
let (doc, _notes, read) = crate::layered_ai_from(layers, pdf, vec![], false, false, 1.0, crate::NameEncoding::default());
assert!(!read, "falls back to PDF part");
let map_layer = doc.layers.iter().find(|l| l.name.as_deref() == Some("Map Layer")).unwrap();
assert!(map_layer.locked, "Map Layer preserved locked == true from private stream metadata");
let subgroup = map_layer.children().and_then(|c| c.iter().find(|n| n.name.as_deref() == Some("Locked Subgroup"))).unwrap();
assert!(subgroup.locked, "Locked Subgroup preserved locked == true from private stream metadata");
}
#[test]
fn ai_duplicate_group_names_under_different_layers_preserve_individual_lock_states() {
use std::sync::Arc;
let art_locked_group = format!("1 A\nu\n{}\nU\n%_/ArtDictionary :\n%_(SharedGroup) /String (AIArtName) ,\n%_;\n0 A", square(10, 10));
let art_unlocked_group = format!("0 A\nu\n{}\nU\n%_/ArtDictionary :\n%_(SharedGroup) /String (AIArtName) ,\n%_;\n0 A", square(10, 10));
let layer_a = layer("Layer A", true, &art_locked_group);
let layer_b = layer("Layer B", true, &art_unlocked_group);
let n = native(&format!("{layer_a}{layer_b}"));
let file = private(&n);
let mut pdf = Document::new(100.0, 100.0);
pdf.layers.clear();
let mut vis_a = Node::layer(pdf.alloc_id(), "Layer A", LayerColor::Preset(0));
let mut vis_grp_a = Node::group(pdf.alloc_id(), vec![]);
vis_grp_a.name = Some("SharedGroup".to_string());
vis_grp_a.locked = false;
if let NodeKind::Layer { children, .. } = &mut vis_a.kind {
children.push(Arc::new(vis_grp_a));
}
let mut vis_b = Node::layer(pdf.alloc_id(), "Layer B", LayerColor::Preset(1));
let mut vis_grp_b = Node::group(pdf.alloc_id(), vec![]);
vis_grp_b.name = Some("SharedGroup".to_string());
vis_grp_b.locked = false;
if let NodeKind::Layer { children, .. } = &mut vis_b.kind {
children.push(Arc::new(vis_grp_b));
}
pdf.layers.push(Arc::new(vis_a));
pdf.layers.push(Arc::new(vis_b));
let layers = crate::AiLayers::decode(&file);
let (doc, _notes, read) = crate::layered_ai_from(layers, pdf, vec![], false, false, 1.0, crate::NameEncoding::default());
assert!(!read, "falls back to PDF part");
let l_a = doc.layers.iter().find(|l| l.name.as_deref() == Some("Layer A")).unwrap();
let l_b = doc.layers.iter().find(|l| l.name.as_deref() == Some("Layer B")).unwrap();
let grp_a = l_a.children().and_then(|c| c.iter().find(|n| n.name.as_deref() == Some("SharedGroup"))).unwrap();
let grp_b = l_b.children().and_then(|c| c.iter().find(|n| n.name.as_deref() == Some("SharedGroup"))).unwrap();
assert!(grp_a.locked, "Layer A's SharedGroup is locked");
assert!(!grp_b.locked, "Layer B's SharedGroup remains unlocked");
}
#[test]
fn ai_reordered_mixed_named_and_unnamed_children_preserve_locks() {
use std::sync::Arc;
let mut doc = Document::new(100.0, 100.0);
let mut priv_layer = Node::layer(doc.alloc_id(), "Map", LayerColor::Preset(0));
let mut priv_unnamed = Node::group(doc.alloc_id(), vec![]);
priv_unnamed.locked = false;
let mut priv_roads = Node::group(doc.alloc_id(), vec![]);
priv_roads.name = Some("Roads".to_string());
priv_roads.locked = true;
if let NodeKind::Layer { children, .. } = &mut priv_layer.kind {
children.push(Arc::new(priv_unnamed));
children.push(Arc::new(priv_roads));
}
let mut vis_layer = Node::layer(doc.alloc_id(), "Map", LayerColor::Preset(0));
let mut vis_roads = Node::group(doc.alloc_id(), vec![]);
vis_roads.name = Some("Roads".to_string());
vis_roads.locked = false;
let mut vis_unnamed = Node::group(doc.alloc_id(), vec![]);
vis_unnamed.locked = false;
if let NodeKind::Layer { children, .. } = &mut vis_layer.kind {
children.push(Arc::new(vis_roads));
children.push(Arc::new(vis_unnamed));
}
let mut visible_layers = vec![Arc::new(vis_layer)];
let private_layers = vec![super::native::layers::LockTree::from_node(&priv_layer)];
super::native::layers::apply_private_layer_locks(&mut visible_layers, &private_layers);
let roads = visible_layers[0].children().unwrap()[0].clone();
let unnamed = visible_layers[0].children().unwrap()[1].clone();
assert_eq!(roads.name.as_deref(), Some("Roads"));
assert!(roads.locked, "Roads matched by unique name and preserved locked == true");
assert!(!unnamed.locked, "unnamed child matched to unlocked private child");
}
#[test]
fn ai_reordered_three_children_roads_triangle_circle_preserve_locks() {
use std::sync::Arc;
let mut doc = Document::new(100.0, 100.0);
// Private children: [Roads (unlocked), locked triangle (unnamed), unlocked circle (unnamed)]
let mut priv_layer = Node::layer(doc.alloc_id(), "Layer", LayerColor::Preset(0));
let mut priv_roads = Node::group(doc.alloc_id(), vec![]);
priv_roads.name = Some("Roads".to_string());
priv_roads.locked = false;
let mut priv_triangle = Node::group(doc.alloc_id(), vec![]);
priv_triangle.locked = true;
let mut priv_circle = Node::group(doc.alloc_id(), vec![]);
priv_circle.locked = false;
if let NodeKind::Layer { children, .. } = &mut priv_layer.kind {
children.push(Arc::new(priv_roads));
children.push(Arc::new(priv_triangle));
children.push(Arc::new(priv_circle));
}
// Visible children: [triangle (unnamed), circle (unnamed), Roads]
let mut vis_layer = Node::layer(doc.alloc_id(), "Layer", LayerColor::Preset(0));
let mut vis_triangle = Node::group(doc.alloc_id(), vec![]);
vis_triangle.locked = false;
let mut vis_circle = Node::group(doc.alloc_id(), vec![]);
vis_circle.locked = false;
let mut vis_roads = Node::group(doc.alloc_id(), vec![]);
vis_roads.name = Some("Roads".to_string());
vis_roads.locked = false;
if let NodeKind::Layer { children, .. } = &mut vis_layer.kind {
children.push(Arc::new(vis_triangle));
children.push(Arc::new(vis_circle));
children.push(Arc::new(vis_roads));
}
let mut visible_layers = vec![Arc::new(vis_layer)];
let private_layers = vec![super::native::layers::LockTree::from_node(&priv_layer)];
super::native::layers::apply_private_layer_locks(&mut visible_layers, &private_layers);
let vis_tri = visible_layers[0].children().unwrap()[0].clone();
let vis_circ = visible_layers[0].children().unwrap()[1].clone();
let vis_rd = visible_layers[0].children().unwrap()[2].clone();
assert!(!vis_tri.locked, "unnamed triangle does not pair blindly with private triangle");
assert!(!vis_circ.locked, "unnamed circle remains unlocked");
assert!(!vis_rd.locked, "Roads matched to unlocked private Roads by unique name");
}
/// The PDF part's one layer, named for its page because the PDF part has no layers, isn't the
/// editing data's one layer: nothing says the art on it is that layer's, so the layer's lock and
/// those of what it holds stay out of it.
#[test]
fn ai_fallback_with_generated_page_name_does_not_take_private_layer_lock() {
use std::sync::Arc;
let mut doc = Document::new(100.0, 100.0);
let mut priv_layer = Node::layer(doc.alloc_id(), "Map", LayerColor::Preset(0));
priv_layer.locked = true;
let mut priv_roads = Node::group(doc.alloc_id(), vec![]);
priv_roads.name = Some("Roads".to_string());
priv_roads.locked = true;
if let NodeKind::Layer { children, .. } = &mut priv_layer.kind {
children.push(Arc::new(priv_roads));
}
let mut vis_layer = Node::layer(doc.alloc_id(), "Page 1", LayerColor::Preset(0));
let mut vis_roads = Node::group(doc.alloc_id(), vec![]);
vis_roads.name = Some("Roads".to_string());
if let NodeKind::Layer { children, .. } = &mut vis_layer.kind {
children.push(Arc::new(vis_roads));
}
let mut visible_layers = vec![Arc::new(vis_layer)];
let private_layers = vec![super::native::layers::LockTree::from_node(&priv_layer)];
super::native::layers::apply_private_layer_locks(&mut visible_layers, &private_layers);
assert!(!visible_layers[0].locked, "the page's layer doesn't take the editing data's layer lock");
assert!(!visible_layers[0].children().unwrap()[0].locked, "nor does what it holds");
}
/// An editing copy that doesn't fit the PDF part (a stale copy of another page size) is set aside,
/// and the PDF part without layers comes in on one layer named for its page: the editing copy's
/// locked layer doesn't lock that art, which nothing ties to it.
#[test]
fn a_stale_editing_copy_does_not_lock_the_pdf_parts_page_layer() {
let art = native(&locked_layer("Map", &square(10, 10)));
let mut page = Document::new(300.0, 300.0);
std::sync::Arc::make_mut(&mut page.layers[0]).name = Some("Page 1".into());
let (d, w, read) = crate::layered_ai(&private(&art), page, vec![], false, false, 1.0);
assert!(!read, "the editing copy of another page size is set aside: {w:?}");
assert_eq!(names(&d), ["Page 1"], "{w:?}");
assert!(!d.layers[0].locked, "the page's layer isn't locked: {w:?}");
}
#[test]
fn ai_unnamed_visible_child_does_not_pair_with_private_node() {
use std::sync::Arc;
let mut doc = Document::new(100.0, 100.0);
let mut priv_layer = Node::layer(doc.alloc_id(), "Layer", LayerColor::Preset(0));
let mut priv_unnamed = Node::group(doc.alloc_id(), vec![]);
priv_unnamed.locked = false;
let mut priv_roads = Node::group(doc.alloc_id(), vec![]);
priv_roads.name = Some("Roads".to_string());
priv_roads.locked = true;
if let NodeKind::Layer { children, .. } = &mut priv_layer.kind {
children.push(Arc::new(priv_unnamed));
children.push(Arc::new(priv_roads));
}
let mut vis_layer = Node::layer(doc.alloc_id(), "Layer", LayerColor::Preset(0));
let mut vis_first = Node::group(doc.alloc_id(), vec![]);
vis_first.locked = false;
let mut vis_second = Node::group(doc.alloc_id(), vec![]);
vis_second.locked = false;
if let NodeKind::Layer { children, .. } = &mut vis_layer.kind {
children.push(Arc::new(vis_first));
children.push(Arc::new(vis_second));
}
let mut visible_layers = vec![Arc::new(vis_layer)];
let private_layers = vec![super::native::layers::LockTree::from_node(&priv_layer)];
super::native::layers::apply_private_layer_locks(&mut visible_layers, &private_layers);
let first = visible_layers[0].children().unwrap()[0].clone();
let second = visible_layers[0].children().unwrap()[1].clone();
assert!(!first.locked, "first unnamed visible group is unlocked");
assert!(!second.locked, "second unnamed visible group does not pair positionally with locked Roads group");
}
#[test]
fn ai_multi_page_unlayered_pdf_does_not_blindly_pair_with_private_layers() {
use std::sync::Arc;
let mut doc = Document::new(100.0, 100.0);
let mut priv_1 = Node::layer(doc.alloc_id(), "Layer 1", LayerColor::Preset(0));
priv_1.locked = true;
let mut priv_2 = Node::layer(doc.alloc_id(), "Layer 2", LayerColor::Preset(0));
priv_2.locked = false;
let vis_1 = Node::layer(doc.alloc_id(), "Page 1", LayerColor::Preset(0));
let vis_2 = Node::layer(doc.alloc_id(), "Page 2", LayerColor::Preset(0));
let mut visible_layers = vec![Arc::new(vis_1), Arc::new(vis_2)];
let private_layers = vec![super::native::layers::LockTree::from_node(&priv_1), super::native::layers::LockTree::from_node(&priv_2)];
super::native::layers::apply_private_layer_locks(&mut visible_layers, &private_layers);
assert!(!visible_layers[0].locked, "Page 1 does not pair with private Layer 1");
assert!(!visible_layers[1].locked, "Page 2 does not pair with private Layer 2");
}
#[test]
fn ai_duplicate_visible_name_does_not_lock_multiple_from_single_private_node() {
use std::sync::Arc;
let mut doc = Document::new(100.0, 100.0);
let mut priv_layer = Node::layer(doc.alloc_id(), "Layer", LayerColor::Preset(0));
let mut priv_roads = Node::group(doc.alloc_id(), vec![]);
priv_roads.name = Some("Roads".to_string());
priv_roads.locked = true;
let mut priv_buildings = Node::group(doc.alloc_id(), vec![]);
priv_buildings.name = Some("Buildings".to_string());
priv_buildings.locked = false;
if let NodeKind::Layer { children, .. } = &mut priv_layer.kind {
children.push(Arc::new(priv_roads));
children.push(Arc::new(priv_buildings));
}
let mut vis_layer = Node::layer(doc.alloc_id(), "Layer", LayerColor::Preset(0));
let mut vis_roads1 = Node::group(doc.alloc_id(), vec![]);
vis_roads1.name = Some("Roads".to_string());
vis_roads1.locked = false;
let mut vis_roads2 = Node::group(doc.alloc_id(), vec![]);
vis_roads2.name = Some("Roads".to_string());
vis_roads2.locked = false;
if let NodeKind::Layer { children, .. } = &mut vis_layer.kind {
children.push(Arc::new(vis_roads1));
children.push(Arc::new(vis_roads2));
}
let mut visible_layers = vec![Arc::new(vis_layer)];
let private_layers = vec![super::native::layers::LockTree::from_node(&priv_layer)];
super::native::layers::apply_private_layer_locks(&mut visible_layers, &private_layers);
let r1 = visible_layers[0].children().unwrap()[0].clone();
let r2 = visible_layers[0].children().unwrap()[1].clone();
assert!(!r1.locked, "ambiguous duplicate visible name does not receive private lock");
assert!(!r2.locked, "second duplicate visible name remains unlocked");
}
/// #9176: a file with more text objects than the page's type can be matched with each, all but one
/// of them made from its text document, opens with its layers, and what is locked in it stays
/// locked. Only the one text object whose type isn't made is matched with the page's type; the made
/// ones are weighed by where they lie. (Our own minimized copy of the reported file's structure:
/// about two thousand text objects whose type the text document makes, a few it can't, and as many
/// pieces of type on the page, with locked groups.)
#[test]
fn a_file_with_many_made_text_objects_and_one_unread_keeps_its_layers_and_locks() {
// Every text object against every piece of the page's type is past `MAX_PAIRS` (four million).
let many = 2050;
let doc =
last_frame_unread(&text_document(&[("Hi there\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0), ("Odd\r", 0, (8200.0, 8160.0), (0.0, 0.0), 0.0)]));
let locked_group = format!("1 A\nu\n{}\nU\n0 A\n", square(10, 10));
let art = native_with_text(&layer("Map", true, &(locked_group + &text_object(0).repeat(many) + &text_object(1))), &doc);
// The PDF part: the square, the made type where the text document puts it, once per text object,
// and as many small pieces of type apart from one another, which the one text object whose type
// isn't made takes.
let mut page = pdf_part(10.0, 86.0);
let layer_id = page.layers[0].id;
let put = |page: &mut Document, at: (f64, f64), text: &str, size: f64| {
let style = vectorcraft_doc::CharStyle { size, ..Default::default() };
let text = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::new(at.0, at.1), text, style);
let id = page.alloc_id();
let end = page.layers[0].children().map_or(0, |c| c.len());
page.insert(Some(layer_id), end, Node::new(id, NodeKind::Text(Box::new(text)))).unwrap();
};
for _ in 0..many {
put(&mut page, (58.5, 38.5), "Hi there", 14.0);
}
for k in 0..many {
// Down each column, so that no two pieces painted one after the other are on one line.
put(&mut page, (1.0 + (k / 46) as f64 * 2.1, 1.0 + (k % 46) as f64 * 2.1), "o", 1.0);
}
let (d, w, read) = crate::layered_ai(&private(&art), page, vec![], false, false, 1.0);
assert!(read, "{w:?}");
assert_eq!(names(&d), ["Map"], "{w:?}");
let group = d.layers[0].children().and_then(|c| c.iter().find(|n| matches!(n.kind, NodeKind::Group { .. })));
assert!(group.is_some_and(|g| g.locked), "the group locked in the file stays locked: {w:?}");
assert!(all_texts(&d).iter().filter(|t| *t == "Hi there").count() >= many, "{w:?}");
}
/// The page's "2014" drawn as one piece 20 points across the art, and two text objects "20" and
/// "14" anchored at `twenty` and `fourteen`, set in the bundled Source Sans 3 at 14 points (a digit
/// 6.958 points wide) so that where they draw doesn't hang on the fonts installed.
+23 -12
View File
@@ -301,12 +301,23 @@ fn spread_gradients_are_written_with_their_stops_repeated() {
fn a_spread_gradient_without_stops_is_written() {
use vectorcraft_color::GradientSpread;
for kind in [GradientKind::Linear, GradientKind::Radial, GradientKind::Conic, GradientKind::Diamond] {
let g = GradientPaint::new(Gradient { spread: GradientSpread::Repeat, repeats: 3, ..Gradient::new(kind, vec![]) });
let paint = Paint::Gradient(Box::new(g));
let d = doc_with(|d| vec![path(d, shapes::rectangle(Rect::new(20.0, 20.0, 180.0, 180.0)), paint.clone(), paint, 4.0)]);
export(&d, &opts(&d), None, None).unwrap();
export_legacy_ai(&d, &LegacyAiOptions::default()).unwrap();
crate::export_ai_editing(&d, &crate::AiEditingOptions::default()).unwrap();
let doc = |spread: GradientSpread| {
let g = GradientPaint::new(Gradient { spread, repeats: 3, ..Gradient::new(kind, vec![]) });
let paint = Paint::Gradient(Box::new(g));
doc_with(|d| vec![path(d, shapes::rectangle(Rect::new(20.0, 20.0, 180.0, 180.0)), paint.clone(), paint, 4.0)])
};
let (d, pad) = (doc(GradientSpread::Repeat), doc(GradientSpread::Pad));
assert_eq!(page_of(&d, &opts(&d)), page_of(&pad, &opts(&pad)), "{kind:?}: EPS");
assert_eq!(
export_legacy_ai(&d, &LegacyAiOptions::default()).unwrap().bytes,
export_legacy_ai(&pad, &LegacyAiOptions::default()).unwrap().bytes,
"{kind:?}: legacy .ai"
);
assert_eq!(
crate::export_ai_editing(&d, &crate::AiEditingOptions::default()).unwrap().program,
crate::export_ai_editing(&pad, &crate::AiEditingOptions::default()).unwrap().program,
"{kind:?}: .ai editing data"
);
}
}
@@ -2359,15 +2370,15 @@ fn symbol_art_effects_are_written_where_they_draw() {
#[test]
fn level_preview_and_overprint_ids_read_back() {
for l in Level::ALL {
assert_eq!(Level::from_id(l.id()), Some(l));
}
assert_eq!(Level::from_id("3"), Some(Level::Three));
assert_eq!(Level::from_id("LanguageLevel 2"), Some(Level::Two));
assert_eq!(Level::from_id("1"), None);
for p in Preview::ALL {
assert_eq!(Preview::from_id(p.id()), Some(p));
}
assert_eq!(Level::from_id("23"), None);
assert_eq!(Preview::from_id(" TIFFCOLOR "), Some(Preview::TiffColor));
assert_eq!(Preview::from_id("tiffBw"), Some(Preview::TiffBlackWhite));
assert_eq!(Preview::from_id("tiff"), None);
assert_eq!(Overprint::from_id("DISCARD"), Some(Overprint::Discard));
assert_eq!(Overprint::from_id(""), None);
}
#[test]
+30 -3
View File
@@ -422,15 +422,17 @@ mod tests {
}
/// A replaced file that had no access ACL gets none from the folder's default ACL, whose named
/// users the old file's group bits would let in. (Skipped where `setfacl` or ACLs are missing.)
/// users the old file's group bits would let in. The default ACL is set through its extended
/// attribute, so the test runs where the `acl` tools are not installed. (Skipped on a file system
/// without ACLs.)
#[cfg(target_os = "linux")]
#[test]
fn a_replacement_takes_no_inherited_acl_the_old_file_lacked() {
let d = dir("acl");
let f = d.join("doc.vectorcraft");
std::fs::write(&f, b"old").unwrap();
let set = std::process::Command::new("setfacl").args(["-d", "-m", "u:nobody:rw"]).arg(&d).status();
if !set.is_ok_and(|s| s.success()) {
if !set_default_acl_for_nobody(&d) {
let _ = std::fs::remove_dir_all(&d);
return;
}
write_atomic(&f, b"new").unwrap();
@@ -439,6 +441,31 @@ mod tests {
let _ = std::fs::remove_dir_all(&d);
}
/// Give folder `d` the default ACL `u::rw-,u:nobody:rw-,g::r--,m::rw-,o::r--`, written as the
/// kernel's `system.posix_acl_default` attribute (version 2, then tag, permissions and id per entry).
#[cfg(target_os = "linux")]
/// `false` when the folder's file system keeps no ACLs.
fn set_default_acl_for_nobody(d: &Path) -> bool {
const NO_ID: u32 = u32::MAX;
let mut acl = 2u32.to_le_bytes().to_vec();
for (tag, perm, id) in [(0x01u16, 6u16, NO_ID), (0x02, 6, 65534), (0x04, 4, NO_ID), (0x10, 6, NO_ID), (0x20, 4, NO_ID)] {
acl.extend(tag.to_le_bytes());
acl.extend(perm.to_le_bytes());
acl.extend(id.to_le_bytes());
}
match rustix::fs::setxattr(d, "system.posix_acl_default", &acl, rustix::fs::XattrFlags::empty()) {
Ok(()) => {}
Err(e) if e == rustix::io::Errno::NOTSUP => return false,
Err(e) => panic!("setting the default ACL: {e}"),
}
let mut buf = vec![0u8; 4096];
let probe = d.join("probe");
std::fs::write(&probe, b"").unwrap();
assert!(rustix::fs::getxattr(&probe, "system.posix_acl_access", &mut buf[..]).is_ok(), "a new file takes the default ACL");
std::fs::remove_file(&probe).unwrap();
true
}
/// The other files in `d` besides `keep`.
fn leftovers(d: &Path, keep: &str) -> Vec<String> {
std::fs::read_dir(d).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().to_string()).filter(|n| n != keep).collect()
+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);
+5 -9
View File
@@ -68,20 +68,16 @@ problem;
#[test]
fn json2_polyfill_round_trips_with_the_built_in_json() {
let mut realm = Realm::new();
match realm.run(NEEDS) {
Ok(JsValue::Bool(true)) => {}
other => panic!("json2: the interpreter lacks Date, String.prototype.replace or RegExp, which json2.js uses: {other:?}"),
}
let Some(path) = json2_file() else {
println!("json2: SKIPPED (no json2.js; run cargo xtask test262)");
return;
};
let source = std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("{}: {e}", path.display()));
let mut realm = Realm::new();
match realm.run(NEEDS) {
Ok(JsValue::Bool(true)) => {}
Ok(JsValue::Bool(false)) => {
println!("json2: SKIPPED (the interpreter lacks Date, String.prototype.replace or RegExp, which json2.js uses)");
return;
}
other => panic!("json2: the built-in check failed: {other:?}"),
}
match realm.run(&format!("{BEFORE}\n{source}\n{ROUND_TRIP}")) {
Ok(JsValue::String(s)) if s == "ok" => println!("json2: the polyfill and the built-in JSON agree on every sample"),
other => panic!("json2: {other:?}"),
+22 -10
View File
@@ -735,6 +735,18 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"",
"{} flip the last sharp-corner arc of the path the Quick Pen tool is drawing to the other side of its chord, as C and the toolbar's Flip Arc button do, as one undo step; first finishes any pending tool edit (which can change the document), then returns false, changing nothing more, when the Quick Pen tool is not active, no path is being drawn or the last piece is not a sharp-corner arc",
),
(
"tool.quickPen.arcLarger",
"Increase Arc Size",
"",
"{} make the Quick Pen tool's arc size 15° larger, for the last sharp-corner arc of the path being drawn and the arcs after it, as ] and Ctrl+wheel up over the canvas do; first finishes any pending tool edit (which can change the document), then returns false, changing nothing more, when the Quick Pen tool is not active or a step would take the arc size above 359°",
),
(
"tool.quickPen.arcSmaller",
"Decrease Arc Size",
"",
"{} make the Quick Pen tool's arc size 15° smaller, for the last sharp-corner arc of the path being drawn and the arcs after it, as [ and Ctrl+wheel down over the canvas do; first finishes any pending tool edit (which can change the document), then returns false, changing nothing more, when the Quick Pen tool is not active or a step would take the arc size below 1°",
),
(
"window.dock",
"Panels",
@@ -1274,7 +1286,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"ui.layerOptions",
"Options for Selection…",
"",
"{ids?|id?} open Layer Options for Layers panel rows (default: the highlighted rows, else the current layer), filled in from the first: dialog `layerOptions`, fields name, color (a preset name such as \"Light Blue\" or #rrggbb), template, locked, visible, printable, preview, dimImages (bool), dimPercent (0–100); an object's row has name, visible and locked. Unchanged OK adds no undo step; edits run layer.setProps in one undo step. Existing names are preserved unless Name is edited or explicitly set; for several rows it sends only the fields set in the dialog",
"{ids?|id?} open Layer Options for Layers panel rows (default: the highlighted rows, else the current layer), filled in from the first: dialog `ui.layerOptions`, fields name, color (a preset name such as \"Light Blue\" or #rrggbb), template, locked, visible, printable, preview, dimImages (bool), dimPercent (0–100); an object's row has name, visible and locked. Unchanged OK adds no undo step; edits run layer.setProps in one undo step. Existing names are preserved unless Name is edited or explicitly set; for several rows it sends only the fields set in the dialog",
),
(
"ui.layerDelete",
@@ -1292,7 +1304,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"ui.newLayer",
"New Layer Options…",
"Cmd+Alt+L",
"{sublayer?: bool} open Layer Options for a new layer (or a sublayer of the current layer), named and coloured as it would be: dialog `layerOptions` with mode new|newSublayer; OK runs layer.new or layer.newSublayer with the fields. In isolation mode, a layer that would be outside the isolated art is an error and nothing opens; OK checks again, and with isolation mode started since, it returns the same error and makes no layer",
"{sublayer?: bool} open Layer Options for a new layer (or a sublayer of the current layer), named and coloured as it would be: dialog `ui.layerOptions` with mode new|newSublayer; OK runs layer.new or layer.newSublayer with the fields. In isolation mode, a layer that would be outside the isolated art is an error and nothing opens; OK checks again, and with isolation mode started since, it returns the same error and makes no layer",
),
(
"ui.newArtboard",
@@ -1310,13 +1322,13 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"ui.layersPanelOptions",
"Panel Options…",
"",
"{} open the Layers panel's Panel Options: dialog `layersPanelOptions`, fields layersOnly, locateSelected (Locate Selected Objects, off by default: when the last selected object changes outside the panel, on the canvas or by a command, the panel opens the layers and groups around it and scrolls to its row, as after layer.locate, without highlighting the row; when Show Layers Only, a search or the filter leaves the object without a row, the panel opens no rows for it and scrolls as with the option off; a change made during a drag is located when the drag ends), rowSize (small|medium|large|other), otherSize (12–100 pt), thumbLayers, thumbGroups, thumbObjects; OK applies them (kept with the UI state)",
"{} open the Layers panel's Panel Options: dialog `ui.layersPanelOptions`, fields layersOnly, locateSelected (Locate Selected Objects, off by default: when the last selected object changes outside the panel, on the canvas or by a command, the panel opens the layers and groups around it and scrolls to its row, as after layer.locate, without highlighting the row; when Show Layers Only, a search or the filter leaves the object without a row, the panel opens no rows for it and scrolls as with the option off; a change made during a drag is located when the drag ends), rowSize (small|medium|large|other), otherSize (12–100 pt), thumbLayers, thumbGroups, thumbObjects; OK applies them (kept with the UI state)",
),
(
"ui.navigatorPanelOptions",
"Panel Options…",
"",
"{color?: #rrggbb or a preset name (Light Red, the default, then the layer colors such as \"Light Blue\"), solidDashes?: bool (Draw Dashed Lines as Solid Lines, off by default: the Navigator's thumbnail draws dashed strokes without their dashes; the canvas, printing and exports keep them), viewArtboardContentsOnly?: bool (View Artboard Contents Only in the panel menu, on by default and for UI state saved without it: the thumbnail fits the artboards and draws only the art inside them, cut at each artboard's edges; off, it also shows the art on the pasteboard)} set the Navigator panel's options, the color its view box is drawn in, solid dashes and artboard contents only (kept with the UI state) → {color, solidDashes, viewArtboardContentsOnly}; with none, open its Panel Options (dialog `navigatorPanelOptions`, fields color, solidDashes; OK sets them); an error for a value that is not a color or not true or false, which changes nothing",
"{color?: #rrggbb or a preset name (Light Red, the default, then the layer colors such as \"Light Blue\"), solidDashes?: bool (Draw Dashed Lines as Solid Lines, off by default: the Navigator's thumbnail draws dashed strokes without their dashes; the canvas, printing and exports keep them), viewArtboardContentsOnly?: bool (View Artboard Contents Only in the panel menu, on by default and for UI state saved without it: the thumbnail fits the artboards and draws only the art inside them, cut at each artboard's edges; off, it also shows the art on the pasteboard)} set the Navigator panel's options, the color its view box is drawn in, solid dashes and artboard contents only (kept with the UI state) → {color, solidDashes, viewArtboardContentsOnly}; with none, open its Panel Options (dialog `ui.navigatorPanelOptions`, fields color, solidDashes; OK sets them); an error for a value that is not a color or not true or false, which changes nothing",
),
(
"ui.attributesPanelOptions",
@@ -1531,7 +1543,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"ui.menuDialog",
"Menu Dialog",
"",
"{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.arrange.groupRows|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.arrange.markBounds|addon.color.applyNearestSwatch|addon.color.randomFill|addon.select.byArtboards|addon.select.editPointsOnly|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)",
"{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.arrange.groupRows|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.commonTangents|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.arrange.markBounds|addon.color.applyNearestSwatch|addon.color.randomFill|addon.select.byArtboards|addon.select.editPointsOnly|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `addon.pathtools.commonTangents` for addon.pathtools.bridge, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)",
),
(
"ui.widthPointEdit",
@@ -1645,7 +1657,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"ui.rasterEffectsSettingsDialog",
"Document Raster Effects Settings Dialog",
"",
"{} open Document Raster Effects Settings (dialog `rasterEffectsSettings`: the document.rasterEffectsSettings fields); OK runs it. The menu item opens it too",
"{} open Document Raster Effects Settings (dialog `document.rasterEffectsSettings`: the document.rasterEffectsSettings fields); OK runs it. The menu item opens it too",
),
(
"ui.effectGalleryDialog",
@@ -1663,7 +1675,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"ui.pdfPresetDialog",
"PDF Preset",
"",
"{name?: a saved preset to edit | preset?: the preset a new one starts from (default VectorCraft Default)} open the preset editor (dialog `pdfPreset`: the Save PDF dialog's option fields plus `name` and `description`); OK runs pdf.preset.save and returns to PDF Presets",
"{name?: a saved preset to edit | preset?: the preset a new one starts from (default VectorCraft Default)} open the preset editor (dialog `pdf-export`: the Save PDF dialog's option fields plus `name` and `description`); OK runs pdf.preset.save and returns to PDF Presets",
),
("file.openRecent11", "Open Recent File 11", "", "{}"),
("file.openRecent12", "Open Recent File 12", "", "{}"),
@@ -1918,7 +1930,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"ui.actionSet.reset",
"Reset Actions",
"",
"{mode?: \"replace\" | \"append\"} Reset Actions. replace (the default) replaces every set in the Actions panel with a new copy of the built-in Default Actions set, makes it current and selected, clears the panel's selected action and step and its expanded actions, and closes an open Set Options, New Action, Batch or step dialog that names a set; when the panel already shows only the built-in set as it comes in that state, nothing changes, the sets keep their ids and changed is false. append adds a new copy of the built-in set after the sets there are, with the next free number when its name is in use (Default Actions 2), and keeps the current set and the selection. Omitted params count as {}. Params of another type, another key, another mode, or a reset while an action records or plays (also while it waits at a stop) is an error and changes nothing. No undo step is recorded. The panel menu's Reset Actions asks first (dialog `resetActions`): OK runs this with replace, Append with append → {changed, mode, set: the first built-in set's index}",
"{mode?: \"replace\" | \"append\"} Reset Actions. replace (the default) replaces every set in the Actions panel with a new copy of the built-in Default Actions set, makes it current and selected, clears the panel's selected action and step and its expanded actions, and closes an open Set Options, New Action, Batch or step dialog that names a set; when the panel already shows only the built-in set as it comes in that state, nothing changes, the sets keep their ids and changed is false. append adds a new copy of the built-in set after the sets there are, with the next free number when its name is in use (Default Actions 2), and keeps the current set and the selection. Omitted params count as {}. Params of another type, another key, another mode, or a reset while an action records or plays (also while it waits at a stop) is an error and changes nothing. No undo step is recorded. The panel menu's Reset Actions asks first (dialog `actionsQuestion`): OK runs this with replace, Append with append → {changed, mode, set: the first built-in set's index}",
),
(
"ui.actionSet.clear",
@@ -1949,7 +1961,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"file.saveForWeb",
"Save for Web (Legacy)…",
"Cmd+Alt+Shift+S",
"{} open Save for Web (dialog `saveForWeb`: fields = the webExport.settings settings, `preset` loads a preset, __view: original|optimized|2up|4up, __zoom, __kbps; Save… remembers the settings and writes the files, Done only remembers them); with settings = document.exportForWeb, written to path, else a picked file (the web downloads the files) → {path, files, bytes}",
"{} open Save for Web (dialog `save-for-web`: fields = the webExport.settings settings, `preset` loads a preset, __view: original|optimized|2up|4up, __zoom, __kbps; Save… remembers the settings and writes the files, Done only remembers them); with settings = document.exportForWeb, written to path, else a picked file (the web downloads the files) → {path, files, bytes}",
),
(
"file.saveForWeb.browser",
@@ -2202,7 +2214,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"ui.livePaintGapOptions",
"Gap Options…",
"",
"{} open Gap Options (Object › Live Paint › Gap Options…; dialog `livePaintGapOptions`: detect, size small|medium|large|custom, custom (pt), color (#rrggbb or a layer color's name), closeGaps, preview) on the selected Live Paint groups, filled in from the first; with preview on, the options apply live and the gaps found draw on the canvas in the preview color: OK runs livePaint.gapOptions as one undo step; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing, and with preview on a #rrggbbaa color is not previewed: the groups keep their own color and the gaps draw in black",
"{} open Gap Options (Object › Live Paint › Gap Options…; dialog `livePaintGapOptions`: detect, size small|medium|large|custom, custom (pt), color (#rrggbb or a layer color's name), closeGaps, preview) on the selected Live Paint groups, filled in from the first; with preview on, the options apply live and the gaps found draw on the canvas in the preview color: OK runs livePaint.gapOptions as one undo step; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing, and with preview on a #rrggbbaa color is not previewed: the groups keep their own color and the gaps draw in black; a preview that fails shows its error in the status bar, puts the groups back as they were and stops drawing the dialog's preview of the gaps (View › Show Live Paint Gaps still draws the restored groups' own gaps)",
),
(
"ui.perspectivePlane",
@@ -816,11 +816,14 @@ mod tests {
// Squaring these lengths overflows f64.
let (a, b) = (circle(0.0, 0.0, 5e153), circle(1.5e154, 0.0, 5e153));
let sp = smooth_bridge(a, b, 5e153).unwrap();
// At least one anchor for each of the two circles and the two arcs.
assert!(sp.closed && sp.anchors.len() >= 4, "{}", sp.anchors.len());
assert!(sp.anchors.iter().all(|q| [q.p, q.h_in, q.h_out].iter().all(|p| p.x.is_finite() && p.y.is_finite())));
assert_smooth(&sp);
// The two radius sums fit in f64, but not their total.
let (a, b) = (circle(-5e307, 0.0, 1e307), circle(5e307, 0.0, 1e307));
let sp = smooth_bridge(a, b, 1.5e308).unwrap();
assert!(sp.closed && sp.anchors.len() >= 4, "{}", sp.anchors.len());
assert!(sp.anchors.iter().all(|q| [q.p, q.h_in, q.h_out].iter().all(|p| p.x.is_finite() && p.y.is_finite())));
// The arcs' centers would lie beyond the largest f64.
let (a, b) = (circle(0.0, 0.0, 1e308), circle(1.5e308, 0.0, 1e308));
@@ -609,12 +609,12 @@ mod tests {
fn each_kind_draws_a_closed_outline_in_its_box() {
for kind in ShapeKind::ALL {
let s = shape(kind);
assert_eq!(ShapeKind::parse(kind.id()), Some(kind));
assert_eq!(s.check(), Ok(()), "{kind:?}");
let p = s.path().unwrap();
assert!(closed(&p) && within_box(&p, &s), "{kind:?}: {:?}", p.bounds());
assert!(p.anchors().all(|(_, _, a)| a.p.x.is_finite() && a.p.y.is_finite()));
}
assert_eq!(ShapeKind::parse("gear"), Some(ShapeKind::Gear));
assert_eq!(ShapeKind::parse("cloud"), None);
}
@@ -262,9 +262,7 @@ fn a_smooth_end_whose_handles_part_turns_into_a_corner() {
}
#[test]
fn follow_names_round_trip() {
for f in Follow::ALL {
assert_eq!(Follow::parse(f.id()), Some(f));
}
fn follow_names_parse() {
assert_eq!(Follow::parse("b"), Some(Follow::Second));
assert_eq!(Follow::parse("up"), None);
}
+3 -2
View File
@@ -31,11 +31,12 @@ pub use fit::{fit_cubics, fit_cubics_through};
pub use offset::{Cap, Join, MAX_OFFSET_SEGMENT_PAIRS, offset_path, outline_stroke, stroke_region, try_offset_path};
pub use pathfinder::{
FaceMerger, PathfinderOp, Region, Shape, merge_regions, pathfinder, pathfinder_with, region_at, regions, regions_with, regions_within,
try_pathfinder_with,
};
pub use planar::{
Adjacency, BuilderArrangement, MapEdge, MapFace, MapOutline, SHAPE_BUILDER_MAX_GAP, SHAPE_BUILDER_MAX_MAP_EDGES, SHAPE_BUILDER_MAX_SEGMENTS,
adjacency, cut_out, encloses_area, find_gaps, has_open_path, interior_point, live_paint, live_paint_with_gaps, run_around, shape_builder,
shape_builder_with_gap,
TooManyPieces, adjacency, cut_out, encloses_area, find_gaps, has_open_path, interior_point, live_paint, live_paint_with_gaps, run_around,
shape_builder, shape_builder_with_gap, try_live_paint, try_live_paint_with_gaps,
};
pub use thickness::{MAX_DOCUMENT_THICKNESS_WORK, MAX_THICKNESS_PIECES, ThicknessBudget, thinner_than, thinner_than_within};
pub use trap::{TRAP_HEIGHT_WIDTH_RANGE, TRAP_MAX_WIDTH, TRAP_MIN_WIDTH, trap_band};
+33 -8
View File
@@ -109,6 +109,36 @@ pub fn pathfinder(op: PathfinderOp, shapes: &[Shape]) -> Vec<Shape> {
pathfinder_with(op, shapes, DEFAULT_PRECISION)
}
/// [`pathfinder_with`], or [`TooManyPieces`](crate::TooManyPieces) when Divide's open paths and the
/// shapes they cut have more than [`SHAPE_BUILDER_MAX_SEGMENTS`](crate::SHAPE_BUILDER_MAX_SEGMENTS)
/// segments, or the sweep cuts them into more than
/// [`SHAPE_BUILDER_MAX_MAP_EDGES`](crate::SHAPE_BUILDER_MAX_MAP_EDGES) pieces, or they exceed the
/// sweep's work budget. [`pathfinder_with`] then divides only the filled areas and leaves the open
/// paths out.
pub fn try_pathfinder_with(op: PathfinderOp, shapes: &[Shape], precision: f64) -> Result<Vec<Shape>, crate::TooManyPieces> {
if op == PathfinderOp::Divide && crate::has_open_path(shapes) {
let precision = if precision.is_finite() && precision > 0.0 { precision } else { DEFAULT_PRECISION };
let (faces, capped) = divide_with_open_paths(shapes, precision, false);
return if capped { Err(crate::TooManyPieces) } else { Ok(faces) };
}
Ok(pathfinder_with(op, shapes, precision))
}
/// Divide with open paths as cutting edges, through the Shape Builder's bounded planar map (and,
/// with `fallback`, its filled-area fallback), and whether that map was skipped for its size.
fn divide_with_open_paths(shapes: &[Shape], precision: f64, fallback: bool) -> (Vec<Shape>, bool) {
let (arrangement, capped) = crate::planar::builder_capped(shapes, false, 0.0, precision, fallback);
let faces = arrangement
.regions
.into_iter()
.filter_map(|r| {
let key = shapes.get(r.top()?)?.key;
Some(Shape::new(r.path, FillRule::NonZero, key))
})
.collect();
(faces, capped)
}
/// [`pathfinder`] at Pathfinder Options › Precision: results are refit to within `precision`
/// (document units) and pieces thinner than it are dropped. A smaller value follows the inputs more
/// closely. A value that isn't positive and finite is [`DEFAULT_PRECISION`].
@@ -130,14 +160,7 @@ pub fn pathfinder_with(op: PathfinderOp, shapes: &[Shape], precision: f64) -> Ve
// Open paths are cutting edges for Divide; the filled-only operations keep their
// implicit closure. Reuse Shape Builder's bounded planar map and its fallback.
if op == PathfinderOp::Divide && crate::has_open_path(shapes) {
return crate::planar::builder(shapes, false, 0.0, precision)
.regions
.into_iter()
.filter_map(|r| {
let key = shapes.get(r.top()?)?.key;
Some(Shape::new(r.path, FillRule::NonZero, key))
})
.collect();
return divide_with_open_paths(shapes, precision, true).0;
}
let Some(arr) = arrangement(shapes, precision) else { return Vec::new() };
let p = &arr.tidy;
@@ -1645,6 +1668,8 @@ mod tests {
assert_eq!(faces.len(), 1, "a segment past the cap falls back to filled areas");
assert_eq!(faces[0].key, 7);
assert!((crate::area(&faces[0].path, faces[0].rule) - 10000.0).abs() < 1e-6);
// The checked Divide reports that it left the lines out.
assert_eq!(try_pathfinder_with(PathfinderOp::Divide, &inputs, DEFAULT_PRECISION), Err(crate::TooManyPieces));
}
fn old_trim(shapes: &[Shape], precision: f64) -> Vec<Shape> {
+4 -4
View File
@@ -37,14 +37,14 @@ pub use adjacency::{Adjacency, MapEdge, MapFace, MapOutline, adjacency};
pub(crate) use graph::pin_ends;
#[cfg(test)]
use index::{Crossings, RectIndex, reference_budget, segment_footprint, work_done};
pub use live_paint::{find_gaps, live_paint, live_paint_with_gaps};
pub use live_paint::{find_gaps, live_paint, live_paint_with_gaps, try_live_paint, try_live_paint_with_gaps};
pub use map::interior_point;
pub(crate) use map::{Map, Rest, map};
pub use shape_builder::{
BuilderArrangement, SHAPE_BUILDER_MAX_GAP, SHAPE_BUILDER_MAX_MAP_EDGES, SHAPE_BUILDER_MAX_SEGMENTS, cut_out, encloses_area, has_open_path,
run_around, shape_builder, shape_builder_with_gap,
BuilderArrangement, SHAPE_BUILDER_MAX_GAP, SHAPE_BUILDER_MAX_MAP_EDGES, SHAPE_BUILDER_MAX_SEGMENTS, TooManyPieces, cut_out, encloses_area,
has_open_path, run_around, shape_builder, shape_builder_with_gap,
};
pub(crate) use shape_builder::{builder, gap_inputs};
pub(crate) use shape_builder::{builder_capped, gap_inputs};
#[cfg(test)]
mod tests;
Loaded 100 of 257 files, more files were not shown because too many files have changed in this diff. Show more