mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-05 05:22:58 -05:00
Merge main into feat/scripts-api-d5-swatches-symbols
This commit is contained in:
commit
96e66b5e8d
114 files changed
+5938
-853
No files matched your search
Generated
+92
-93
@@ -1255,7 +1255,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
dependencies = [
|
||||
"craft-automation",
|
||||
"craft-behavior",
|
||||
@@ -1297,7 +1297,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-affinity"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
dependencies = [
|
||||
"crc32fast",
|
||||
"flate2",
|
||||
@@ -1318,7 +1318,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-appkit"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
dependencies = [
|
||||
"block2 0.6.2",
|
||||
"objc2 0.6.5",
|
||||
@@ -1330,7 +1330,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-atomic"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
dependencies = [
|
||||
"rustix 1.1.6",
|
||||
]
|
||||
@@ -1338,7 +1338,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-automation"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
dependencies = [
|
||||
"base64 0.23.1",
|
||||
"craft-behavior",
|
||||
@@ -1363,7 +1363,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-behavior"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
dependencies = [
|
||||
"accesskit",
|
||||
"bitflags 2.13.2",
|
||||
@@ -1381,7 +1381,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-browse"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-docpath",
|
||||
@@ -1399,7 +1399,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-cdr"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
dependencies = [
|
||||
"crc32fast",
|
||||
"flate2",
|
||||
@@ -1408,7 +1408,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-cloud-ui"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
dependencies = [
|
||||
"egui",
|
||||
]
|
||||
@@ -1416,7 +1416,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-cms"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
dependencies = [
|
||||
"md-5",
|
||||
"rayon",
|
||||
@@ -1425,12 +1425,12 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-codepage"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
|
||||
[[package]]
|
||||
name = "craft-color-ui"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-cms",
|
||||
@@ -1450,7 +1450,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-control"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
dependencies = [
|
||||
"craft-ai-agents",
|
||||
"craft-atomic",
|
||||
@@ -1466,7 +1466,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-control-protocol"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
dependencies = [
|
||||
"getrandom 0.3.4",
|
||||
"serde_json",
|
||||
@@ -1476,7 +1476,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-dds"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
dependencies = [
|
||||
"rayon",
|
||||
]
|
||||
@@ -1484,7 +1484,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-dialogs"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
dependencies = [
|
||||
"block2 0.6.2",
|
||||
"craft-appkit",
|
||||
@@ -1510,7 +1510,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-doc"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"craft-ecproj-format",
|
||||
@@ -1526,7 +1526,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-docpath"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
dependencies = [
|
||||
"serde",
|
||||
]
|
||||
@@ -1534,7 +1534,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-draw"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-color-ui",
|
||||
@@ -1553,7 +1553,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-dwg"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
dependencies = [
|
||||
"acadrust",
|
||||
"log",
|
||||
@@ -1562,7 +1562,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-dxf"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
dependencies = [
|
||||
"craft-codepage",
|
||||
"encoding_rs",
|
||||
@@ -1574,7 +1574,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ecproj-format"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -1584,12 +1584,12 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-eps"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
|
||||
[[package]]
|
||||
name = "craft-flags"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
dependencies = [
|
||||
"craft-atomic",
|
||||
"dirs",
|
||||
@@ -1599,7 +1599,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-font-catalog"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
dependencies = [
|
||||
"fontique",
|
||||
"harfrust 0.13.3",
|
||||
@@ -1614,7 +1614,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-font-manager"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-font-catalog",
|
||||
@@ -1633,7 +1633,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-font-os-windows"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
dependencies = [
|
||||
"windows-registry",
|
||||
"windows-sys 0.61.2",
|
||||
@@ -1642,7 +1642,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-font-store"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
dependencies = [
|
||||
"cap-primitives",
|
||||
"craft-atomic",
|
||||
@@ -1665,12 +1665,12 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-fonts-build"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
|
||||
[[package]]
|
||||
name = "craft-gif"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
dependencies = [
|
||||
"gif",
|
||||
]
|
||||
@@ -1678,7 +1678,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-gzip"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
]
|
||||
@@ -1686,7 +1686,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-host"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"craft-i18n",
|
||||
@@ -1699,7 +1699,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-i18n"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
dependencies = [
|
||||
"brotli 9.1.3",
|
||||
"brotli-decompressor 6.3.2",
|
||||
@@ -1729,7 +1729,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-image-codecs"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
dependencies = [
|
||||
"craft-dds",
|
||||
"craft-jpeg",
|
||||
@@ -1756,7 +1756,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-imaging"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-color-ui",
|
||||
@@ -1774,7 +1774,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-jpeg"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
@@ -1782,7 +1782,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-jxl"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
dependencies = [
|
||||
"brotli-decompressor 5.0.3",
|
||||
"jixel",
|
||||
@@ -1793,7 +1793,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-keymap"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
dependencies = [
|
||||
"craft-host",
|
||||
"craft-i18n",
|
||||
@@ -1808,7 +1808,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-layers"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-i18n",
|
||||
@@ -1822,7 +1822,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-menu"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -1840,7 +1840,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-metadata"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
dependencies = [
|
||||
"brotli-decompressor 6.3.2",
|
||||
"chrono",
|
||||
@@ -1852,7 +1852,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-metafile"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"image",
|
||||
@@ -1863,7 +1863,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-mime"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"craft-codepage",
|
||||
@@ -1873,7 +1873,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-nightly"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
dependencies = [
|
||||
"uds_windows",
|
||||
"winsafe",
|
||||
@@ -1882,7 +1882,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-pages"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-keymap",
|
||||
@@ -1898,7 +1898,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-pbr"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
dependencies = [
|
||||
"craft-texture",
|
||||
"thiserror 2.0.21",
|
||||
@@ -1907,7 +1907,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-pcraft-format"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"serde",
|
||||
@@ -1918,7 +1918,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-pdf"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
dependencies = [
|
||||
"hayro-interpret",
|
||||
"hayro-syntax",
|
||||
@@ -1930,7 +1930,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-platform"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
dependencies = [
|
||||
"async-channel",
|
||||
"async-io",
|
||||
@@ -1963,7 +1963,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-plotter"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
dependencies = [
|
||||
"kurbo 0.13.1",
|
||||
"thiserror 2.0.21",
|
||||
@@ -1972,7 +1972,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-print"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -1996,7 +1996,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-proof"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
dependencies = [
|
||||
"log",
|
||||
"miniz_oxide 0.9.1",
|
||||
@@ -2007,7 +2007,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ps"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
dependencies = [
|
||||
"craft-eps",
|
||||
"flate2",
|
||||
@@ -2021,7 +2021,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-psd"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"flate2",
|
||||
@@ -2032,7 +2032,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-quit"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
dependencies = [
|
||||
"dispatch2",
|
||||
"egui",
|
||||
@@ -2045,7 +2045,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-raster3d"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
dependencies = [
|
||||
"rayon",
|
||||
"thiserror 2.0.21",
|
||||
@@ -2054,7 +2054,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-review"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
dependencies = [
|
||||
"base64 0.23.1",
|
||||
"craft-behavior",
|
||||
@@ -2073,7 +2073,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-settings"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
dependencies = [
|
||||
"craft-atomic",
|
||||
"craft-host",
|
||||
@@ -2090,7 +2090,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-stream-codecs"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
dependencies = [
|
||||
"fax",
|
||||
"hayro-ccitt",
|
||||
@@ -2101,7 +2101,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-svg"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
dependencies = [
|
||||
"craft-image-codecs",
|
||||
"craft-xml",
|
||||
@@ -2122,7 +2122,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-table"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-keymap",
|
||||
@@ -2134,7 +2134,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-text"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-font-manager",
|
||||
@@ -2159,7 +2159,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-texture"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
@@ -2167,7 +2167,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-theme"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"craft-tracked",
|
||||
@@ -2182,7 +2182,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-theme-store"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
dependencies = [
|
||||
"craft-atomic",
|
||||
"craft-behavior",
|
||||
@@ -2197,7 +2197,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-tiff"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"thiserror 2.0.21",
|
||||
@@ -2207,7 +2207,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-time"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"thiserror 2.0.21",
|
||||
@@ -2216,7 +2216,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-timeline"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-keymap",
|
||||
@@ -2231,12 +2231,12 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-tracked"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
|
||||
[[package]]
|
||||
name = "craft-ui"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
dependencies = [
|
||||
"craft-cloud-ui",
|
||||
"craft-ui-canvas",
|
||||
@@ -2250,7 +2250,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-canvas"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-font-catalog",
|
||||
@@ -2267,7 +2267,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-contract"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
dependencies = [
|
||||
"accesskit",
|
||||
"craft-behavior",
|
||||
@@ -2305,7 +2305,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-macros"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
dependencies = [
|
||||
"proc-macro-crate",
|
||||
"proc-macro2",
|
||||
@@ -2316,7 +2316,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-panels"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -2334,7 +2334,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-patterns"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -2355,7 +2355,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-shell"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -2376,7 +2376,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-widgets"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -2395,7 +2395,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-update"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"chrono",
|
||||
@@ -2427,7 +2427,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-vectorcraft-format"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"serde",
|
||||
@@ -2438,7 +2438,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-wayland"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
dependencies = [
|
||||
"raw-window-handle",
|
||||
"wayland-backend",
|
||||
@@ -2448,7 +2448,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-web-api"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
dependencies = [
|
||||
"js-sys",
|
||||
"serde_json",
|
||||
@@ -2459,7 +2459,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-win32"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
dependencies = [
|
||||
"winsafe",
|
||||
]
|
||||
@@ -2467,7 +2467,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-window"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
dependencies = [
|
||||
"craft-appkit",
|
||||
"craft-atomic",
|
||||
@@ -2499,7 +2499,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-xml"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
dependencies = [
|
||||
"quick-xml 0.41.0",
|
||||
"serde",
|
||||
@@ -3859,7 +3859,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a"
|
||||
[[package]]
|
||||
name = "hayro-cmap"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
dependencies = [
|
||||
"brotli 8.0.4",
|
||||
"hayro-postscript",
|
||||
@@ -3868,7 +3868,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "hayro-interpret"
|
||||
version = "0.7.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"hayro-cmap",
|
||||
@@ -3886,7 +3886,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "hayro-jbig2"
|
||||
version = "0.3.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
dependencies = [
|
||||
"fearless_simd",
|
||||
"hayro-ccitt",
|
||||
@@ -3904,12 +3904,12 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "hayro-postscript"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
|
||||
[[package]]
|
||||
name = "hayro-syntax"
|
||||
version = "0.7.2"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"hayro-ccitt",
|
||||
@@ -4892,7 +4892,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "krilla"
|
||||
version = "0.8.2"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"bumpalo",
|
||||
@@ -5049,7 +5049,7 @@ checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4"
|
||||
[[package]]
|
||||
name = "linesweeper"
|
||||
version = "0.5.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
dependencies = [
|
||||
"arrayvec",
|
||||
"kurbo 0.13.1",
|
||||
@@ -7615,8 +7615,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "skrifa"
|
||||
version = "0.44.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "819ab7d62b1d3e72d9d9dea5650bac30424f9111364bb94928dbf5ecad1baa68"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"read-fonts 0.41.0",
|
||||
|
||||
+43
-41
@@ -10,57 +10,57 @@ license = "MIT OR Apache-2.0"
|
||||
rust-version = "1.95"
|
||||
|
||||
[workspace.dependencies]
|
||||
craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6", default-features = false, features = ["interpret", "write"] }
|
||||
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" }
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97", default-features = false, features = ["interpret", "write"] }
|
||||
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" }
|
||||
craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" }
|
||||
# Language packs: the Craft apps' shared font store installs them (#4936).
|
||||
craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" }
|
||||
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" }
|
||||
# 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 = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" }
|
||||
craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" }
|
||||
# `.pcraft` documents: their manifest, full-size composite, preview, layer pixels and ICC profile.
|
||||
craft-doc = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6", features = ["pcraft-pixels"] }
|
||||
craft-doc = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97", features = ["pcraft-pixels"] }
|
||||
# Native Affinity documents (craft-libs#914).
|
||||
craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" }
|
||||
# Bounded CDR (v1-v27) and CMX (32-bit) reader (craft-libs#778).
|
||||
craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" }
|
||||
# SVG parsing, limits, SVGZ and writer (craft-libs#778).
|
||||
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6", features = ["tree"] }
|
||||
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97", features = ["tree"] }
|
||||
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" }
|
||||
# EPS container, previews, ASCII85 and DSC comments (craft-libs#778).
|
||||
craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" }
|
||||
# DXF tags, reader and writer (craft-libs#778, #926, #927).
|
||||
craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" }
|
||||
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" }
|
||||
# DWG to DXF bytes, in a child process on desktop builds (acadrust 0.6.6, MPL-2.0, unmodified).
|
||||
craft-dwg = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
craft-dwg = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" }
|
||||
# WMF, EMF and EMF+ reader (craft-libs#778).
|
||||
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6", default-features = false, features = ["read", "write"] }
|
||||
craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" }
|
||||
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" }
|
||||
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" }
|
||||
craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" }
|
||||
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" }
|
||||
craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97", default-features = false, features = ["read", "write"] }
|
||||
craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" }
|
||||
craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" }
|
||||
craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" }
|
||||
craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" }
|
||||
# The metallic-roughness BRDF and environment light the 3D effects' Roughness and Metallic shade with.
|
||||
craft-pbr = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
craft-pbr = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" }
|
||||
# The CPU rasterizer that draws a 3D effect's Render Settings › Rendered image: depth-buffered triangles, shadow maps.
|
||||
craft-raster3d = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
craft-raster3d = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" }
|
||||
# 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 = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
craft = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" }
|
||||
# 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 = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
craft-color-ui = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" }
|
||||
craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" }
|
||||
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" }
|
||||
# Nightly profile isolation, launch protocol, and security fence.
|
||||
craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" }
|
||||
# internal
|
||||
vectorcraft-geom = { path = "crates/geom" }
|
||||
vectorcraft-color = { path = "crates/color" }
|
||||
@@ -200,13 +200,15 @@ lto = "thin"
|
||||
codegen-units = 1
|
||||
|
||||
[patch.crates-io]
|
||||
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
krilla = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
|
||||
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" }
|
||||
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" }
|
||||
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" }
|
||||
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" }
|
||||
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" }
|
||||
krilla = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" }
|
||||
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" }
|
||||
# skrifa 0.44 (epaint, glifo, usvg) with the automatic hinter's long blue-zone exit (craft-libs vendor/skrifa).
|
||||
skrifa = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" }
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "861d60a65c50850e995bbb3dcee7c1f3b06815f6" }
|
||||
emath = { git = "https://github.com/storytold/egui.git", rev = "861d60a65c50850e995bbb3dcee7c1f3b06815f6" }
|
||||
epaint = { git = "https://github.com/storytold/egui.git", rev = "861d60a65c50850e995bbb3dcee7c1f3b06815f6" }
|
||||
|
||||
@@ -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 = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6", version = "0.1.0" }
|
||||
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97", version = "0.1.0" }
|
||||
|
||||
wasm-bindgen = "0.2"
|
||||
serde_json = { workspace = true }
|
||||
|
||||
@@ -178,7 +178,7 @@ pub(crate) struct Converter {
|
||||
|
||||
const PATTERN_HATCH: &str = "pattern hatches come in as their boundaries";
|
||||
const GRADIENT_HATCH: &str = "gradient hatches are filled with their first colour";
|
||||
const MESHES: &str = "3D polygon meshes and polyface meshes are left out";
|
||||
const MESH_VERTICES: &str = "polygon meshes and polyface mesh faces whose vertices are missing are left out";
|
||||
const BIG_ARRAY: &str = "array inserts are limited to 10,000 copies each";
|
||||
const MANY_ARRAYS: &str = "array inserts are limited to 2,000,000 copies in all";
|
||||
const FAR_AWAY: &str = "entities with coordinates out of range are left out";
|
||||
@@ -233,14 +233,20 @@ impl Converter {
|
||||
path(ellipse(m.common.extrusion, *center, *major, *ratio, *start, *end)?)
|
||||
}
|
||||
model::EntityKind::LwPolyline(p) => lwpolyline(p, ocs),
|
||||
model::EntityKind::Polyline(p) => self.polyline(p, ocs),
|
||||
model::EntityKind::Polyline(p) => self.polyline(p, &g, ocs),
|
||||
model::EntityKind::Spline(s) => path(spline(s)?),
|
||||
model::EntityKind::Solid { corners } | model::EntityKind::Trace { corners } => {
|
||||
let [a, b, c, d] = corners.map(point);
|
||||
// The corners zigzag: the outline runs 1, 2, 4, 3.
|
||||
Some(Geom::Path { bp: transformed(polygon(&[a, b, d, c]), ocs), fill: true, width: 0.0 })
|
||||
}
|
||||
model::EntityKind::Face3d { corners, .. } => path(polygon(&corners.map(point))),
|
||||
model::EntityKind::Face3d { corners, hidden_edges } => {
|
||||
// Bit n of group 70 hides the edge from corner n.
|
||||
let corners: Vec<(Point, bool)> = corners.iter().enumerate().map(|(i, c)| (point(*c), hidden_edges & (1 << i) == 0)).collect();
|
||||
let mut bp = BezPath::new();
|
||||
face(&mut bp, &corners);
|
||||
(!bp.elements().is_empty()).then_some(bp).and_then(path)
|
||||
}
|
||||
model::EntityKind::Hatch(h) => self.hatch(h, ocs),
|
||||
model::EntityKind::Text(t) => text(t, &g, false, ocs).map(Geom::Text),
|
||||
model::EntityKind::MText(t) => mtext(t, e.tags).map(Geom::Text),
|
||||
@@ -253,10 +259,11 @@ impl Converter {
|
||||
}
|
||||
}
|
||||
|
||||
fn polyline(&mut self, p: &model::Polyline, ocs: Affine) -> Option<Geom> {
|
||||
if p.is_mesh() || p.is_polyface() {
|
||||
self.warn(MESHES);
|
||||
return None;
|
||||
fn polyline(&mut self, p: &model::Polyline, g: &Groups<'_>, ocs: Affine) -> Option<Geom> {
|
||||
// Meshes are in world coordinates, seen from above.
|
||||
if p.is_polyface() || p.is_mesh() {
|
||||
let bp = if p.is_polyface() { self.polyface(p) } else { self.mesh(p, g) }?;
|
||||
return Some(Geom::Path { bp, fill: false, width: 0.0 });
|
||||
}
|
||||
// Spline frame control points and polyface faces aren't on the line.
|
||||
let verts: Vec<Vertex> =
|
||||
@@ -267,6 +274,60 @@ impl Converter {
|
||||
Some(Geom::Path { bp, fill: false, width: p.start_width.max(0.0) })
|
||||
}
|
||||
|
||||
/// A polyface mesh's faces: each one's visible edges, closed when all of them are.
|
||||
fn polyface(&mut self, p: &model::Polyline) -> Option<BezPath> {
|
||||
let points: Vec<Point> = p.vertices.iter().filter(|v| !v.is_face()).map(|v| point(v.location)).collect();
|
||||
let mut bp = BezPath::new();
|
||||
for f in p.vertices.iter().filter(|v| v.is_face()) {
|
||||
// Vertex numbers count from 1, negative when the edge from that vertex is hidden;
|
||||
// 0 ends a triangle's list.
|
||||
let corners: Option<Vec<(Point, bool)>> = f
|
||||
.face
|
||||
.iter()
|
||||
.take_while(|n| **n != 0)
|
||||
.map(|n| {
|
||||
let i = usize::try_from(n.unsigned_abs()).ok()?.checked_sub(1)?;
|
||||
Some((*points.get(i)?, *n > 0))
|
||||
})
|
||||
.collect();
|
||||
match corners {
|
||||
Some(corners) => face(&mut bp, &corners),
|
||||
None => self.warn(MESH_VERTICES),
|
||||
}
|
||||
}
|
||||
(!bp.elements().is_empty()).then_some(bp)
|
||||
}
|
||||
|
||||
/// A polygon mesh as its M lines and N lines. Its vertices go row by row (N to a row); a
|
||||
/// smoothed mesh holds its surface's vertices (groups 73 and 74 count them) after the frame.
|
||||
fn mesh(&mut self, p: &model::Polyline, g: &Groups<'_>) -> Option<BezPath> {
|
||||
let points: Vec<Point> = p.vertices.iter().filter(|v| !v.is_spline_frame()).map(|v| point(v.location)).collect();
|
||||
let size = |m: i64, n: i64| {
|
||||
let (m, n) = (usize::try_from(m).ok()?, usize::try_from(n).ok()?);
|
||||
(m > 0 && n > 0 && m.checked_mul(n) == Some(points.len())).then_some((m, n))
|
||||
};
|
||||
let (frame, surface) = ((p.m, p.n), (g.i_or(73, 0), g.i_or(74, 0)));
|
||||
// Without the frame's vertices only the surface's counts describe the grid.
|
||||
let dims = if p.vertices.iter().any(model::Vertex::is_spline_frame) {
|
||||
size(surface.0, surface.1)
|
||||
} else {
|
||||
size(frame.0, frame.1).or_else(|| size(surface.0, surface.1))
|
||||
};
|
||||
let Some((m, n)) = dims else {
|
||||
self.warn(MESH_VERTICES);
|
||||
return None;
|
||||
};
|
||||
let mut bp = BezPath::new();
|
||||
for row in points.chunks(n) {
|
||||
line(&mut bp, row, p.flags & 32 != 0);
|
||||
}
|
||||
for col in 0..n {
|
||||
let pts: Vec<Point> = (0..m).map(|r| points[r * n + col]).collect();
|
||||
line(&mut bp, &pts, p.closed());
|
||||
}
|
||||
(!bp.elements().is_empty()).then_some(bp)
|
||||
}
|
||||
|
||||
fn insert(&mut self, ins: &model::Insert, followers: &[model::Record<'_>], ocs: Affine) -> Option<Geom> {
|
||||
let block = Some(ins.block.trim()).filter(|b| !b.is_empty())?.to_uppercase();
|
||||
let [sx, sy, _] = ins.scale;
|
||||
@@ -398,6 +459,46 @@ fn polygon(pts: &[Point]) -> BezPath {
|
||||
bp
|
||||
}
|
||||
|
||||
/// Adds the line through `pts` to `bp`, closed if `closed` (nothing for fewer than two points).
|
||||
fn line(bp: &mut BezPath, pts: &[Point], closed: bool) {
|
||||
if pts.len() < 2 {
|
||||
return;
|
||||
}
|
||||
for (i, p) in pts.iter().enumerate() {
|
||||
if i == 0 { bp.move_to(*p) } else { bp.line_to(*p) }
|
||||
}
|
||||
if closed {
|
||||
bp.close_path();
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds a face's outline to `bp`: its corners with whether the edge from each to the next is
|
||||
/// visible. All visible, the outline is closed; otherwise each run of visible edges is an open
|
||||
/// line.
|
||||
fn face(bp: &mut BezPath, corners: &[(Point, bool)]) {
|
||||
let pts: Vec<Point> = corners.iter().map(|c| c.0).collect();
|
||||
let Some(hidden) = corners.iter().position(|c| !c.1) else {
|
||||
line(bp, &pts, true);
|
||||
return;
|
||||
};
|
||||
// Start after a hidden edge, so that no run is split where the list wraps.
|
||||
let n = corners.len();
|
||||
let mut run: Vec<Point> = Vec::new();
|
||||
for k in 1..=n {
|
||||
let i = (hidden + k) % n;
|
||||
if corners[i].1 {
|
||||
if run.is_empty() {
|
||||
run.push(pts[i]);
|
||||
}
|
||||
run.push(pts[(i + 1) % n]);
|
||||
} else {
|
||||
line(bp, &run, false);
|
||||
run.clear();
|
||||
}
|
||||
}
|
||||
line(bp, &run, false);
|
||||
}
|
||||
|
||||
fn cross(a: [f64; 3], b: [f64; 3]) -> [f64; 3] {
|
||||
[a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]
|
||||
}
|
||||
|
||||
@@ -248,6 +248,125 @@ fn polyline_bulges_are_exact_arcs() {
|
||||
assert!((b.y1 - height(&doc)).abs() < 1e-4, "the arc's chord is at y 0: {b:?}");
|
||||
}
|
||||
|
||||
/// The straight segments of the paths of the one object a drawing brings in, in drawing
|
||||
/// coordinates (y up), each with its ends in order, sorted.
|
||||
fn drawn_edges(r: &Imported) -> Vec<[(i64, i64); 2]> {
|
||||
let doc = &r.document;
|
||||
assert_eq!(doc.layers[0].children().map_or(0, Vec::len), 1, "one object: {:?}", r.warnings);
|
||||
let h = height(doc);
|
||||
let at = |p: Point| (p.x.round() as i64, (h - p.y).round() as i64);
|
||||
let mut edges = vec![];
|
||||
for n in leaves(doc) {
|
||||
let NodeKind::Path { path, .. } = &n.kind else { panic!("not a path: {:?}", n.kind) };
|
||||
for s in path.to_bezpath().segments() {
|
||||
let kurbo::PathSeg::Line(l) = s else { panic!("not a line: {s:?}") };
|
||||
edges.push([at(l.p0), at(l.p1)]);
|
||||
}
|
||||
}
|
||||
sorted(edges)
|
||||
}
|
||||
|
||||
/// Edges with their ends in order, sorted.
|
||||
fn sorted(mut e: Vec<[(i64, i64); 2]>) -> Vec<[(i64, i64); 2]> {
|
||||
for x in &mut e {
|
||||
x.sort_unstable();
|
||||
}
|
||||
e.sort_unstable();
|
||||
e
|
||||
}
|
||||
|
||||
fn vertex(flags: &'static str, x: &'static str, y: &'static str, z: &'static str) -> [(i32, &'static str); 5] {
|
||||
[(0, "VERTEX"), (70, flags), (10, x), (20, y), (30, z)]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn polyface_meshes_draw_their_faces_visible_edges_from_above() {
|
||||
// A square at two heights as two triangles sharing a hidden diagonal, and a face naming a
|
||||
// vertex the mesh doesn't have.
|
||||
let mut e: Vec<(i32, &str)> = vec![(0, "POLYLINE"), (66, "1"), (70, "64"), (71, "4"), (72, "3")];
|
||||
for (x, y, z) in [("0", "0", "5"), ("10", "0", "5"), ("10", "10", "0"), ("0", "10", "0")] {
|
||||
e.extend(vertex("192", x, y, z));
|
||||
}
|
||||
for f in [["1", "2", "-3"], ["3", "4", "-1"], ["1", "2", "9"]] {
|
||||
e.extend(vertex("128", "0", "0", "0"));
|
||||
e.extend([(71, f[0]), (72, f[1]), (73, f[2])]);
|
||||
}
|
||||
e.push((0, "SEQEND"));
|
||||
let r = open(&entities(&e), &points());
|
||||
let square = sorted(vec![[(0, 0), (10, 0)], [(10, 0), (10, 10)], [(10, 10), (0, 10)], [(0, 10), (0, 0)]]);
|
||||
assert_eq!(drawn_edges(&r), square, "the outline without the diagonal");
|
||||
assert!(r.warnings.iter().any(|w| w.contains("vertices are missing")), "{:?}", r.warnings);
|
||||
// With every edge visible, each face is a closed outline.
|
||||
let e: Vec<(i32, &str)> = e.iter().map(|&(c, v)| (c, v.trim_start_matches('-'))).collect();
|
||||
let r = open(&entities(&e), &points());
|
||||
let diagonal = drawn_edges(&r).iter().filter(|e| **e == [(0, 0), (10, 10)]).count();
|
||||
assert_eq!(diagonal, 2, "the diagonal, once per face");
|
||||
let faces = leaves(&r.document);
|
||||
assert_eq!(faces.len(), 2);
|
||||
assert!(faces.iter().all(|f| f.path_data().is_some_and(|p| p.subpaths.iter().all(|s| s.closed))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn polygon_meshes_draw_their_m_and_n_lines_from_above() {
|
||||
// Rows of 3 vertices: N runs along x, M along y.
|
||||
let grid = |flags: &'static str, m: &'static str, n: &'static str, rows: &[&'static str]| {
|
||||
let mut e: Vec<(i32, &str)> = vec![(0, "POLYLINE"), (66, "1"), (70, flags), (71, m), (72, n)];
|
||||
for y in rows {
|
||||
for x in ["0", "10", "20"] {
|
||||
e.extend(vertex("64", x, y, "7"));
|
||||
}
|
||||
}
|
||||
e.push((0, "SEQEND"));
|
||||
e
|
||||
};
|
||||
let edges = |e: &[(i32, &str)]| drawn_edges(&open(&entities(e), &points()));
|
||||
let rows = vec![[(0, 0), (10, 0)], [(10, 0), (20, 0)], [(0, 10), (10, 10)], [(10, 10), (20, 10)]];
|
||||
let cols = vec![[(0, 0), (0, 10)], [(10, 0), (10, 10)], [(20, 0), (20, 10)]];
|
||||
let open_grid = sorted([rows.clone(), cols.clone()].concat());
|
||||
assert_eq!(edges(&grid("16", "2", "3", &["0", "10"])), open_grid);
|
||||
// Closed in N (32): each row joins its last vertex to its first.
|
||||
let wrap = vec![[(20, 0), (0, 0)], [(20, 10), (0, 10)]];
|
||||
assert_eq!(edges(&grid("48", "2", "3", &["0", "10"])), sorted([rows, cols, wrap].concat()));
|
||||
// Closed in M (1): each column joins its last vertex to its first.
|
||||
let tall = edges(&grid("17", "3", "3", &["0", "10", "20"]));
|
||||
for e in [[(0, 0), (0, 20)], [(10, 0), (10, 20)], [(20, 0), (20, 20)]] {
|
||||
assert_eq!(tall.iter().filter(|x| **x == e).count(), 1, "{e:?} in {tall:?}");
|
||||
}
|
||||
// A smoothed mesh draws its surface (73 by 74 vertices), not the frame before it, even when
|
||||
// the frame (3 by 2) has as many vertices.
|
||||
let mut e: Vec<(i32, &str)> = vec![(0, "POLYLINE"), (66, "1"), (70, "20"), (71, "3"), (72, "2"), (73, "2"), (74, "3"), (75, "6")];
|
||||
for (x, y) in [("-50", "-50"), ("50", "-50"), ("-50", "0"), ("50", "0"), ("-50", "50"), ("50", "50")] {
|
||||
e.extend(vertex("80", x, y, "0"));
|
||||
}
|
||||
e.extend_from_slice(&grid("16", "2", "3", &["0", "10"])[5..]);
|
||||
assert_eq!(edges(&e), open_grid);
|
||||
// When the surface counts (2 by 4) don't fit, the frame's (3 by 2) don't describe the surface
|
||||
// vertices either: the mesh is left out with a warning.
|
||||
let i = e.iter().position(|t| *t == (74, "3")).unwrap_or_else(|| panic!("no group 74 in {e:?}"));
|
||||
e[i] = (74, "4");
|
||||
let r = open(&entities(&e), &points());
|
||||
assert!(leaves(&r.document).is_empty());
|
||||
assert!(r.warnings.iter().any(|w| w.contains("vertices are missing")), "{:?}", r.warnings);
|
||||
// Vertices that don't fill the grid: the mesh is left out with a warning.
|
||||
let r = open(&entities(&grid("16", "2", "4", &["0", "10"])), &points());
|
||||
assert!(leaves(&r.document).is_empty());
|
||||
assert!(r.warnings.iter().any(|w| w.contains("vertices are missing")), "{:?}", r.warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn three_d_faces_leave_out_their_hidden_edges() {
|
||||
let edges = |hidden: &'static str| {
|
||||
let mut e: Vec<(i32, &str)> = vec![(0, "3DFACE"), (70, hidden)];
|
||||
e.extend([(10, "0"), (20, "0"), (11, "10"), (21, "0"), (12, "10"), (22, "10"), (13, "0"), (23, "10")]);
|
||||
drawn_edges(&open(&entities(&e), &points()))
|
||||
};
|
||||
let square = sorted(vec![[(0, 0), (10, 0)], [(10, 0), (10, 10)], [(10, 10), (0, 10)], [(0, 10), (0, 0)]]);
|
||||
assert_eq!(edges("0"), square);
|
||||
// Bit 0 hides the edge from the first corner, bit 2 the one from the third.
|
||||
assert_eq!(edges("1"), sorted(vec![[(10, 0), (10, 10)], [(10, 10), (0, 10)], [(0, 10), (0, 0)]]));
|
||||
assert_eq!(edges("5"), sorted(vec![[(10, 0), (10, 10)], [(0, 10), (0, 0)]]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nurbs_splines_stay_within_a_hundredth() {
|
||||
// A rational quadratic circle of radius 100: nine weighted control points.
|
||||
|
||||
+55
-14
@@ -318,7 +318,7 @@ impl Document {
|
||||
/// it, read once and without copying its index path; otherwise, and when that place no longer holds it, as
|
||||
/// [`Document::index_path`] finds it.
|
||||
pub fn node(&self, id: NodeId) -> Option<&Node> {
|
||||
if let Some(n) = self.index.get().and_then(|cached| cached.node_in(&self.layers, id)) {
|
||||
if let Some(n) = self.index.get().and_then(|cached| cached.node_in(&self.layers, id).or_else(|| cached.added_node_in(&self.layers, id))) {
|
||||
crate::id_index::note_path_lookup();
|
||||
return Some(n);
|
||||
}
|
||||
@@ -365,10 +365,21 @@ impl Document {
|
||||
Some(None) => return self.walk_index_path(id),
|
||||
_ => {}
|
||||
}
|
||||
let stale = cached.contains_key(&id);
|
||||
// An id the table doesn't have, at the path an earlier walk found for it, while the node
|
||||
// there still has the id.
|
||||
if !stale
|
||||
&& let Some(p) = cached.added(&id)
|
||||
&& self.node_at(&p).is_some_and(|n| n.id == id)
|
||||
{
|
||||
return Some(p);
|
||||
}
|
||||
// A stale path (the tree changed) or an id the cache doesn't have (deleted or added
|
||||
// since): walk, and rebuild now and then.
|
||||
let found = self.walk_index_path(id);
|
||||
let stale = cached.contains_key(&id);
|
||||
if !stale && let Some(p) = &found {
|
||||
cached.note_added(id, p);
|
||||
}
|
||||
if (stale || found.is_some()) && self.index.missed() {
|
||||
self.index.rebuild(&self.layers);
|
||||
}
|
||||
@@ -425,23 +436,37 @@ impl Document {
|
||||
// Cached paths that still check out ([`id_index`]); the rest take one walk. For a good
|
||||
// share of the document, one walk is quicker than checking each cached path.
|
||||
if let Some(cache) = self.index.get().filter(|c| want.len().saturating_mul(8) < c.len()) {
|
||||
want.retain(|id| match cache.get(id) {
|
||||
Some(Some(p)) if self.node_at(&p).is_some_and(|n| n.id == *id) => {
|
||||
want.retain(|id| match self.cached_path(&cache, *id) {
|
||||
Some(p) => {
|
||||
out.insert(*id, p);
|
||||
false
|
||||
}
|
||||
_ => true,
|
||||
None => true,
|
||||
});
|
||||
}
|
||||
if !want.is_empty() {
|
||||
crate::id_index::note_tree_walk();
|
||||
let mut rest = HashMap::with_capacity(want.len());
|
||||
walk(&self.layers, &want, &mut Vec::new(), &mut rest);
|
||||
// The cache keeps the paths of found ids it doesn't have, for the next lookup.
|
||||
if let Some(cache) = self.index.get().filter(|_| rest.len() <= crate::id_index::ADDED_PATHS) {
|
||||
rest.iter().for_each(|(id, p)| cache.note_added(*id, p));
|
||||
}
|
||||
out.extend(rest);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The path the lookup cache `cache` has for `id`, while the node there has the id: the table's
|
||||
/// path, or for an id the table doesn't have, the path an earlier walk found ([`id_index`]).
|
||||
fn cached_path(&self, cache: &crate::id_index::Paths, id: NodeId) -> Option<Vec<usize>> {
|
||||
let p = match cache.get(&id) {
|
||||
Some(p) => p?,
|
||||
None => cache.added(&id)?,
|
||||
};
|
||||
self.node_at(&p).is_some_and(|n| n.id == id).then_some(p)
|
||||
}
|
||||
|
||||
/// Every node whose id is in `ids`, in tree order (the order of [`Document::walk`]): unlike
|
||||
/// [`Document::index_paths`], an id that appears more than once (a damaged file) gives every
|
||||
/// node that has it. When the cache ([`id_index`]) holds each id once, at a path that still
|
||||
@@ -452,7 +477,8 @@ impl Document {
|
||||
let want: std::collections::HashSet<NodeId, std::hash::BuildHasherDefault<crate::id_index::IdHasher>> = ids.into_iter().collect();
|
||||
// As in `index_paths`, one walk is quicker than checking the cached paths of a good share
|
||||
// of the document.
|
||||
if let Some(cache) = self.index.get().filter(|c| want.len().saturating_mul(8) < c.len()) {
|
||||
let cache = self.index.get().filter(|c| want.len().saturating_mul(8) < c.len());
|
||||
if let Some(cache) = &cache {
|
||||
let mut paths = Vec::with_capacity(want.len());
|
||||
let cached = want.iter().all(|id| match cache.get(id) {
|
||||
Some(Some(p)) if self.node_at(&p).is_some_and(|n| n.id == *id) => {
|
||||
@@ -476,6 +502,10 @@ impl Document {
|
||||
out.push(n);
|
||||
}
|
||||
});
|
||||
// Found ids the table doesn't have count toward a rebuild for later ordered lookups.
|
||||
if cache.is_some_and(|cache| out.iter().any(|n| !cache.contains_key(&n.id))) && self.index.missed() {
|
||||
self.index.rebuild(&self.layers);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -584,10 +614,14 @@ impl Document {
|
||||
|
||||
/// Remove a node and return it.
|
||||
pub fn remove(&mut self, id: NodeId) -> Result<Arc<Node>, DocError> {
|
||||
let parent = self.parent_of(id);
|
||||
let path = self.index_path(id).ok_or(DocError::NoNode(id))?;
|
||||
let idx = *path.last().ok_or(DocError::NoNode(id))?;
|
||||
let ch = self.children_mut(parent)?;
|
||||
self.remove_at(id, &path)
|
||||
}
|
||||
|
||||
/// Remove the node at `path`, the index path [`Document::index_path`] gave for `id`, and return it.
|
||||
fn remove_at(&mut self, id: NodeId, path: &[usize]) -> Result<Arc<Node>, DocError> {
|
||||
let (&idx, up) = path.split_last().ok_or(DocError::NoNode(id))?;
|
||||
let ch = self.children_at(up).ok_or(DocError::NoNode(id))?;
|
||||
if idx >= ch.len() {
|
||||
return Err(DocError::NoNode(id));
|
||||
}
|
||||
@@ -602,10 +636,11 @@ impl Document {
|
||||
{
|
||||
return Err(DocError::Invalid("cannot move an object into itself".into()));
|
||||
}
|
||||
if let Some(n) = self.node(id) {
|
||||
let path = self.index_path(id).ok_or(DocError::NoNode(id))?;
|
||||
if let Some(n) = self.node_at(&path) {
|
||||
self.check_ruler_guide_place(n, parent)?;
|
||||
}
|
||||
let n = self.remove(id)?;
|
||||
let n = self.remove_at(id, &path)?;
|
||||
let ch = self.children_mut(parent)?;
|
||||
let i = Node::insert_index(ch, index, &n);
|
||||
ch.insert(i, n);
|
||||
@@ -623,9 +658,15 @@ impl Document {
|
||||
|
||||
/// Position of `id` within its parent: (parent, index, sibling count).
|
||||
pub fn position(&self, id: NodeId) -> Option<(Option<NodeId>, usize, usize)> {
|
||||
let parent = self.parent_of(id);
|
||||
let idx = *self.index_path(id)?.last()?;
|
||||
let n = self.children(parent)?.len();
|
||||
let path = self.index_path(id)?;
|
||||
let (&idx, up) = path.split_last()?;
|
||||
let (parent, n) = match up {
|
||||
[] => (None, self.layers.len()),
|
||||
_ => {
|
||||
let parent = self.node_at(up)?;
|
||||
(Some(parent.id), parent.children()?.len())
|
||||
}
|
||||
};
|
||||
Some((parent, idx, n))
|
||||
}
|
||||
|
||||
|
||||
@@ -4,10 +4,15 @@
|
||||
//! The tree is edited in many places through public fields, so the cache can't be kept in step
|
||||
//! with it. It is checked instead: a cached path is used only while the node at that path still
|
||||
//! has the id (a check as deep as the tree). A path that no longer checks out rebuilds the cache,
|
||||
//! and an id the cache doesn't have (added since, or removed) is looked up by walking, as before.
|
||||
//! and an id the cache doesn't have (added since, or removed) is looked up by walking.
|
||||
//! An id that appears more than once (a damaged file) is never cached, so lookups keep returning
|
||||
//! its first place in tree order.
|
||||
//!
|
||||
//! The path a walk finds for an id the table doesn't have is kept beside the table, shared by every
|
||||
//! document that reads it, and checked the same way before it is used. Documents that each start
|
||||
//! from the same copy and add the same object (every preview of a drag starts from the document as
|
||||
//! it was at the press) then find that object without walking the tree.
|
||||
//!
|
||||
//! [`crate::Document::remove_many`] keeps the cache and notes the nodes it removes, so the cache
|
||||
//! places each node after a removed sibling one lower and finds no path for a removed node or one
|
||||
//! inside it. Once the removed nodes are half the cache's entries, the cache is let go. The first
|
||||
@@ -16,8 +21,10 @@
|
||||
//! The one case a cached lookup can answer differently from a walk: a second node with an
|
||||
//! existing id put in the tree *after* the cache was built, earlier in tree order than the first.
|
||||
//! The lookup then returns the original node (also one with that id) instead of the new one. The
|
||||
//! app never makes such a node (paste and duplicate give new ids, undo restores whole trees);
|
||||
//! duplicated ids come from damaged files, which are cached afresh when opened.
|
||||
//! same holds for an id the table doesn't have: once a walk in one document has found it, a copy
|
||||
//! that holds a second node with that id earlier in tree order gets the node at the path the walk
|
||||
//! found. The app never makes such a node (paste and duplicate give new ids, undo restores whole
|
||||
//! trees); duplicated ids come from damaged files, which are cached afresh when opened.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::hash::{BuildHasherDefault, Hasher};
|
||||
@@ -65,8 +72,15 @@ type Gaps = HashMap<u32, Vec<u32>>;
|
||||
pub(crate) struct Paths {
|
||||
table: Arc<Table>,
|
||||
gaps: Arc<Gaps>,
|
||||
/// The index paths that walks found for ids the table doesn't have, at most [`ADDED_PATHS`] of
|
||||
/// them. Every document that reads the table reads them too, and checks a path against its own
|
||||
/// tree before using it.
|
||||
added: Arc<RwLock<IdMap<Vec<usize>>>>,
|
||||
}
|
||||
|
||||
/// The most paths [`Paths`] keeps for ids its table doesn't have; one more lets the kept ones go.
|
||||
pub(crate) const ADDED_PATHS: usize = 4096;
|
||||
|
||||
/// Where each node was when the cache was built: its parent's entry (`u32::MAX` for a top-level
|
||||
/// layer) and its index among its siblings. One flat table, so building it allocates nothing per
|
||||
/// node.
|
||||
@@ -152,6 +166,36 @@ impl Paths {
|
||||
Err(k) => Some(i - k as u32),
|
||||
}
|
||||
}
|
||||
/// The index path a walk found for `id`, an id the table doesn't have ([`Paths::note_added`]);
|
||||
/// the caller checks that the node there has the id.
|
||||
pub(crate) fn added(&self, id: &NodeId) -> Option<Vec<usize>> {
|
||||
let path = self.added.read().ok()?.get(id)?.clone();
|
||||
note_path_copy();
|
||||
Some(path)
|
||||
}
|
||||
/// The node with `id` in `layers` at the path [`Paths::added`] has for it, found without copying
|
||||
/// the path: `None` when there is none or the node there does not have the id.
|
||||
pub(crate) fn added_node_in<'a>(&self, layers: &'a [Arc<Node>], id: NodeId) -> Option<&'a Node> {
|
||||
let added = self.added.read().ok()?;
|
||||
let (first, rest) = added.get(&id)?.split_first()?;
|
||||
let mut node: &Node = layers.get(*first)?;
|
||||
for &i in rest {
|
||||
node = node.children()?.get(i)?;
|
||||
}
|
||||
(node.id == id).then_some(node)
|
||||
}
|
||||
/// Keep `path`, which a walk found for `id`, when the table doesn't have `id`. Past
|
||||
/// [`ADDED_PATHS`] ids, the kept paths are let go first.
|
||||
pub(crate) fn note_added(&self, id: NodeId, path: &[usize]) {
|
||||
if self.table.ids.contains_key(&id) {
|
||||
return;
|
||||
}
|
||||
let Ok(mut added) = self.added.write() else { return };
|
||||
if added.len() >= ADDED_PATHS && !added.contains_key(&id) {
|
||||
added.clear();
|
||||
}
|
||||
added.insert(id, path.to_vec());
|
||||
}
|
||||
}
|
||||
|
||||
/// Lookups that had to walk (the cache didn't have the id, or its path no longer checks out)
|
||||
@@ -297,7 +341,7 @@ impl IdIndex {
|
||||
note_tree_walk();
|
||||
let mut table = Table::default();
|
||||
walk(layers, u32::MAX, &mut table);
|
||||
let out = Arc::new(Paths { table: Arc::new(table), gaps: Arc::default() });
|
||||
let out = Arc::new(Paths { table: Arc::new(table), gaps: Arc::default(), added: Arc::default() });
|
||||
if let Ok(mut g) = self.0.write() {
|
||||
*g = Some(out.clone());
|
||||
}
|
||||
|
||||
@@ -608,3 +608,89 @@ fn node_lookups_copy_no_index_path() {
|
||||
agree(&d, &ids[..200], "after remove_many");
|
||||
agree(&d, &nested, "nested");
|
||||
}
|
||||
|
||||
/// Copies of one document that each add the same object, as the previews of a drag do from the document at the press,
|
||||
/// find that object where a walk finds it. The first copy walks the tree once for it and the later copies do not walk,
|
||||
/// and [`Document::node`] finds it without copying an index path.
|
||||
/// A copy that adds the object elsewhere, adds an object below it, groups it or deletes it, and the document they
|
||||
/// were copied from, still find what a walk finds. A copy that adds it twice finds one node with its id, and
|
||||
/// [`Document::nodes_in_order`] finds both.
|
||||
#[test]
|
||||
fn copies_that_add_an_object_find_it_without_walking_again() {
|
||||
let (mut base, ids) = squares(2_000);
|
||||
let layer = base.layers[0].id;
|
||||
let added = base.alloc_id();
|
||||
let new = || Node::path(added, shapes::rectangle(Rect::new(0.0, 0.0, 2.0, 2.0)), Appearance::default_art());
|
||||
base.drop_lookup_cache();
|
||||
base.node(layer);
|
||||
let walks = tree_walks();
|
||||
let mut node_copies = 0;
|
||||
for copy in 0..20 {
|
||||
let mut d = base.clone();
|
||||
d.insert(Some(layer), usize::MAX, new()).unwrap();
|
||||
let copies = path_copies();
|
||||
assert!(d.node(added).is_some_and(|n| n.id == added), "copy {copy}");
|
||||
node_copies += path_copies() - copies;
|
||||
assert_eq!(d.index_path(added), Some(vec![0, ids.len()]), "copy {copy}");
|
||||
assert_eq!(d.index_paths([added, ids[5]]).get(&added), Some(&vec![0, ids.len()]), "copy {copy}");
|
||||
assert_eq!(d.ancestry(added), Some(vec![layer, added]), "copy {copy}");
|
||||
}
|
||||
assert_eq!(tree_walks() - walks, 1, "walks of the tree for 20 copies");
|
||||
assert_eq!(node_copies, 0, "index paths copied by node for 20 copies");
|
||||
|
||||
// A copy that adds the object twice: lookups give one node with its id, and nodes_in_order,
|
||||
// which reads only the table's paths, gives both.
|
||||
let mut d = base.clone();
|
||||
d.insert(Some(layer), usize::MAX, new()).unwrap();
|
||||
d.insert(Some(layer), 3, new()).unwrap();
|
||||
agree_except(&d, &[added, ids[3], ids[0]], Some(added), "added twice");
|
||||
assert_eq!(d.nodes_in_order([ids[7], added]).iter().map(|n| n.id).collect::<Vec<_>>(), [added, ids[7], added], "added twice");
|
||||
let gone = d.index_path(added).unwrap();
|
||||
assert_eq!(d.remove(added).unwrap().id, added);
|
||||
assert_eq!(d.walk_index_path(added).filter(|p| *p != gone).map(|_| ()), Some(()), "the other one stays");
|
||||
assert_eq!(d.layers[0].children().unwrap().len(), ids.len() + 1, "removed one node");
|
||||
|
||||
// The object lower in the layer, with another object below it, and the next copy back at the top.
|
||||
let mut d = base.clone();
|
||||
d.insert(Some(layer), 10, new()).unwrap();
|
||||
agree(&d, &[added, ids[9], ids[10]], "added at 10");
|
||||
let below = square(&mut d);
|
||||
let below = d.insert(Some(layer), 0, below).unwrap();
|
||||
agree(&d, &[added, below, ids[9]], "an object below it");
|
||||
let mut d = base.clone();
|
||||
d.insert(Some(layer), usize::MAX, new()).unwrap();
|
||||
agree(&d, &[added], "back at the top");
|
||||
|
||||
// Grouped with the object below it, then deleted.
|
||||
let gid = d.alloc_id();
|
||||
let members = vec![d.remove(ids[ids.len() - 1]).unwrap(), d.remove(added).unwrap()];
|
||||
d.insert(Some(layer), usize::MAX, Node::group(gid, members)).unwrap();
|
||||
assert_eq!(d.index_path(added), Some(vec![0, ids.len() - 1, 1]));
|
||||
agree(&d, &[added, gid, ids[ids.len() - 1]], "grouped");
|
||||
d.remove(gid).unwrap();
|
||||
assert!(d.node(added).is_none() && d.index_path(added).is_none(), "deleted with its group");
|
||||
agree(&d, &[added, gid], "deleted");
|
||||
|
||||
// The document the copies came from has no such object, and a copy that adds it again finds it.
|
||||
assert!(base.node(added).is_none() && base.index_path(added).is_none() && base.index_paths([added]).is_empty());
|
||||
let mut d = base.clone();
|
||||
d.insert(Some(layer), usize::MAX, new()).unwrap();
|
||||
agree(&d, &[added, ids[0]], "added again");
|
||||
}
|
||||
|
||||
/// Repeated ordered lookups of an added object rebuild the table and then use its cached path.
|
||||
#[test]
|
||||
fn ordered_lookups_of_an_added_object_stop_walking() {
|
||||
let (mut d, _) = squares(2_000);
|
||||
let layer = d.layers[0].id;
|
||||
d.drop_lookup_cache();
|
||||
d.node(layer);
|
||||
let new = square(&mut d);
|
||||
let added = d.insert(Some(layer), usize::MAX, new).unwrap();
|
||||
assert!(d.node(added).is_some_and(|n| n.id == added));
|
||||
let walks = tree_walks();
|
||||
for lookup in 0..20 {
|
||||
assert_eq!(d.nodes_in_order([added]).iter().map(|n| n.id).collect::<Vec<_>>(), [added], "lookup {lookup}");
|
||||
}
|
||||
assert!(tree_walks() - walks <= 5, "walks of the tree for 20 ordered lookups");
|
||||
}
|
||||
@@ -262,7 +262,7 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
|
||||
ROTATE,
|
||||
"Rotate…",
|
||||
&["Effect", "3D and Materials"],
|
||||
"{rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; in the shaded faces the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it; with render mode rendered, every light with an intensity above 0 casts shadows in the image), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the plane, as Extrude & Bevel's, with face front only), material: object ({roughness: 1, metallic: 0}; as Revolve's), render: object ({mode: shaded}; mode: shaded|wireframe|rendered, quality, resolution and background, as Revolve's)}. Turns the flat art in 3D about the centre of its bounds; every fill and stroke keeps its paint, shaded as one plane.",
|
||||
"{rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; in the shaded faces the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it; with render mode rendered, every light with an intensity above 0 casts shadows in the image), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the plane, as Extrude & Bevel's, with face front only), material: object ({roughness: 1, metallic: 0}; as Revolve's), render: object ({mode: shaded}; mode: shaded|wireframe|rendered, quality, resolution and background, as Revolve's; rendered mode checks the paint of every fill and stroke)}. Turns the flat art in 3D about the centre of its bounds; every fill and stroke keeps its paint, shaded as one plane.",
|
||||
json!({"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"graphics":[],"material":{"roughness":1.0,"metallic":0.0},"render":{"mode":"shaded"}}),
|
||||
),
|
||||
g(
|
||||
|
||||
@@ -1013,6 +1013,12 @@ fn solid_items(shape: &Profile) -> impl Iterator<Item = &AppearanceItem> {
|
||||
shape.items.iter().enumerate().filter(move |(k, i)| Some(*k) == top_fill || matches!(i, AppearanceItem::Stroke(_))).map(|(_, i)| i)
|
||||
}
|
||||
|
||||
/// The fills and strokes 3D effect `id` draws for `shapes`: every one for Rotate, which draws a
|
||||
/// plane for each ([`meshes_for`]), and [`solid_items`] for the other effects.
|
||||
fn drawn_items<'a>(id: &str, shapes: &'a [Profile]) -> Box<dyn Iterator<Item = &'a AppearanceItem> + 'a> {
|
||||
if is_plane(id) { Box::new(shapes.iter().flat_map(|s| s.items.iter())) } else { Box::new(shapes.iter().flat_map(solid_items)) }
|
||||
}
|
||||
|
||||
/// The parts Extrude & Bevel and Inflate build solids from: each shape's top fill and its strokes,
|
||||
/// a group's members from the back up, each with its shape's opacity, the region it paints and its
|
||||
/// shape's scopes. The solids share the bounds of all their parts (`fallback` when none has any):
|
||||
@@ -2086,7 +2092,7 @@ fn art_for(
|
||||
{
|
||||
let image = if rendered::reshapes_paths_only(later) {
|
||||
Err(rendered::PATHS_ONLY.into())
|
||||
} else if mapped_graphics(&p).is_empty() && rendered::takes(shapes.iter().flat_map(solid_items), has_masks(shapes)) {
|
||||
} else if mapped_graphics(&p).is_empty() && rendered::takes(drawn_items(&fx.id, shapes), has_masks(shapes)) {
|
||||
meshes_for(fx, shapes, &mut 0, MAX_MESH_TRIANGLES).and_then(|meshes| {
|
||||
let lighting = rendered::lighting(&fx.id, &p);
|
||||
let lighting = match cast_shadow_with(&fx.id, &p, shapes, rendered::plane_settings(&p, &lighting))? {
|
||||
|
||||
@@ -70,7 +70,7 @@ const FOUR: [&str; 4] = [super::super::EXTRUDE, crate::REVOLVE, super::super::IN
|
||||
fn rendered_eligibility_ignores_fills_below_the_top_fill() {
|
||||
use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint, GradientStop};
|
||||
let doc = vectorcraft_doc::Document::new(400.0, 400.0);
|
||||
for id in [super::super::EXTRUDE, super::super::INFLATE, super::super::ROTATE] {
|
||||
for id in [super::super::EXTRUDE, super::super::INFLATE] {
|
||||
let mut n = solid_square(id, Color::BLACK, json!({"render": {"mode": "rendered", "quality": "low"}}));
|
||||
let stops = vec![GradientStop::new(0.0, Color::BLACK), GradientStop::new(1.0, Color::WHITE)];
|
||||
let lower = vectorcraft_doc::AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(Paint::Gradient(Box::new(GradientPaint::new(
|
||||
@@ -85,6 +85,28 @@ fn rendered_eligibility_ignores_fills_below_the_top_fill() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Rotate draws a plane for every fill and stroke, so a gradient fill below the top fill keeps it
|
||||
/// from rendering, as a gradient top fill does.
|
||||
#[test]
|
||||
fn rotate_rendered_eligibility_checks_every_fill() {
|
||||
use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint, GradientStop};
|
||||
let doc = vectorcraft_doc::Document::new(400.0, 400.0);
|
||||
let n = solid_square(super::super::ROTATE, Color::BLACK, json!({"render": {"mode": "rendered", "quality": "low"}}));
|
||||
assert_eq!(crate::rendered_warning(&doc, &n), None);
|
||||
assert_eq!(images(&drawn(&n)).len(), 1);
|
||||
let stops = vec![GradientStop::new(0.0, Color::BLACK), GradientStop::new(1.0, Color::WHITE)];
|
||||
let lower = vectorcraft_doc::AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(
|
||||
GradientKind::Linear,
|
||||
stops,
|
||||
))))));
|
||||
for at in [0, 1] {
|
||||
let mut n = n.clone();
|
||||
n.appearance.items.insert(at, lower.clone());
|
||||
assert_eq!(crate::rendered_warning(&doc, &n).as_deref(), Some(OPAQUE_ONLY), "gradient fill at {at}");
|
||||
assert!(images(&drawn(&n)).is_empty(), "gradient fill at {at}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn later_pathfinder_uses_shaded_faces_and_reports_the_fallback() {
|
||||
let doc = vectorcraft_doc::Document::new(400.0, 400.0);
|
||||
|
||||
@@ -8,10 +8,12 @@
|
||||
//! objects whose visual bounds overlap, Group by Row groups them by the rows (or columns) their
|
||||
//! visual bounds share, Randomize Opacity gives each selected object a random
|
||||
//! opacity, and Sort Objects sorts the selected objects by one attribute and gives them another in
|
||||
//! that order. Mark Bounds of Each ([`marks`]) draws marks on the bounds of each selected object.
|
||||
//! that order. Mark Bounds of Each ([`marks`]) draws marks on the bounds of each selected object,
|
||||
//! and Add Artboard Guides puts a rectangular guide around artboards ([`artboard_guides`]).
|
||||
//! Its submenu (Object › Plug-ins › Arrange Tools), its dialogs and Zoom to Selection (a view
|
||||
//! command) are the UI's.
|
||||
|
||||
mod artboard_guides;
|
||||
pub mod marks;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -31,8 +33,8 @@ use super::super::edit::selected_roots;
|
||||
use super::super::graph::{capture_series_object_opacity, series_groups_among};
|
||||
use super::super::menucmds::whole_or;
|
||||
use super::super::object::{
|
||||
aligned_symbol_transforms, choice, keep_aligned_in_with, keep_symbol_instances_aligned, object_bounds_transform, object_bounds_transform_keeping,
|
||||
refit_drawn, scaling, transform_node, transform_patterns,
|
||||
aligned_symbol_transforms, aligned_symbols, choice, keep_aligned_in_with, keep_symbol_instances_aligned, object_bounds_transform,
|
||||
object_bounds_transform_keeping, refit_drawn, scaling, snaps_after_edit, transform_node, transform_patterns,
|
||||
};
|
||||
use super::super::objects_on_path;
|
||||
use super::super::typecmd::refresh_bounds_of;
|
||||
@@ -102,7 +104,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Match Objects",
|
||||
["Object", "Plug-ins", "Arrange Tools"],
|
||||
None,
|
||||
"{source?: \"key\" (the key object, select.key) | \"top\" (the frontmost selected object) | \"bottom\" (the backmost) (default: the key object when the selection has one, else \"top\"), size?: \"none\" | \"width\" (each target takes the source's width, its height following in proportion) | \"height\" (the source's height, the width following in proportion) | \"both\" (the source's width and height, each on its own) (\"none\"), rotate?: false (true: each target takes the source's bounding-box angle, measured counter-clockwise, turning the shorter way, at most 180°), stacking?: false (true: the targets go directly above the source in the stacking order, in its layer or group, in the order they had), reference?: 0..8 (the 9-point grid row by row from the top-left; 4, the center: the point of each target that stays put as it is sized and turned), scaleStrokes?: the Scale Strokes & Effects preference, corners?: the Scale Corners preference, patterns?: the Transform Pattern Tiles preference (at least one of size, rotate and stacking)} make the other selected objects (the top-level ones, at most 20000) match the source, which stays as it is, as one undo step (none when nothing changes). Sizes are measured and set as object.setBounds measures them (Use Preview Bounds), each in the object's own bounding-box frame after it is turned, with no smallest scale. The side that follows in proportion follows the object's box before the match. Art that is aligned to the pixel grid is measured before it snaps. A size that a target has no width or height to take, or that a stroke or an effect that does not scale keeps it from reaching, is refused, as is a stacking match that would move a clipping path; to match places, use object.align {to: \"key\"} → {source, count}",
|
||||
"{source?: \"key\" (the key object, select.key) | \"top\" (the frontmost selected object) | \"bottom\" (the backmost) (default: the key object when the selection has one, else \"top\"), size?: \"none\" | \"width\" (each target takes the source's width, its height following in proportion) | \"height\" (the source's height, the width following in proportion) | \"both\" (the source's width and height, each on its own) (\"none\"), rotate?: false (true: each target takes the source's bounding-box angle, measured counter-clockwise, turning the shorter way, at most 180°), stacking?: false (true: the targets go directly above the source in the stacking order, in its layer or group, in the order they had), reference?: 0..8 (the 9-point grid row by row from the top-left; 4, the center: the point of each target that stays put as it is sized and turned), scaleStrokes?: the Scale Strokes & Effects preference, corners?: the Scale Corners preference, patterns?: the Transform Pattern Tiles preference (at least one of size, rotate and stacking)} make the other selected objects (the top-level ones, at most 20000) match the source, which stays as it is, as one undo step (none when nothing changes). Sizes are measured and set as object.setBounds measures them (Use Preview Bounds), each in the object's own bounding-box frame after it is turned, with no smallest scale. The side that follows in proportion follows the object's box before the match. Art that is aligned to the pixel grid is measured before it snaps. A size that a target has no width or height to take, or that a stroke or an effect that does not scale keeps it from reaching, is refused, as is a stacking match whose targets are not already directly above the source and that would move a clipping path, restack into or out of a locked layer or group, take a target out of the blend input it is in (to restack the blend itself, select the whole blend), put a target where the Layers panel can't (a blend's inputs, for one) or move Live Paint art; a turned target with a live effect that moves it keeps its measured reference point in place, and with Use Preview Bounds, for a target the match turns that carries a visible geometry or 3D effect or a live compound shape on itself or inside it, or a visible geometry or 3D effect in a placed symbol's art, the match is refused when pixel snapping would move that target's reference point or change a dimension it was asked to match, as it is for a turned target that is pixel-aligned or holds pixel-aligned art or an instance of a pixel-aligned symbol, with or without Use Preview Bounds; to match places, use object.align {to: \"key\"} → {source, count}",
|
||||
has_multi,
|
||||
match_objects
|
||||
),
|
||||
@@ -144,6 +146,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
),
|
||||
]
|
||||
.into_iter()
|
||||
.chain(artboard_guides::specs())
|
||||
.chain(marks::specs())
|
||||
.collect()
|
||||
}
|
||||
@@ -526,6 +529,11 @@ fn match_objects(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
};
|
||||
let angle = s.doc()?.doc.bbox_angle(&[source]);
|
||||
let mut xfs = Vec::with_capacity(targets.len());
|
||||
// Where each turned target's reference point is before the match; it stays there.
|
||||
let mut pinned: HashMap<NodeId, Point> = HashMap::new();
|
||||
// The turned targets whose reference point is checked after pixel snapping.
|
||||
let mut checked: HashMap<NodeId, Point> = HashMap::new();
|
||||
let symbols = if rotate { aligned_symbols(&s.doc()?.doc) } else { HashMap::new() };
|
||||
for &id in &targets {
|
||||
let turn = if rotate { vectorcraft_geom::normalize_deg(angle - s.doc()?.doc.bbox_angle(&[id])) } else { 0.0 };
|
||||
let Some(b) = s.transform_box(&[id]) else {
|
||||
@@ -551,6 +559,16 @@ fn match_objects(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let turned = Affine::rotate_about(-turn.to_radians(), at);
|
||||
if turn.abs() > 1e-9 {
|
||||
xf = turned * xf;
|
||||
let preview = s.bounds_measure().preview;
|
||||
let d = &s.doc()?.doc;
|
||||
if preview && d.node(id).is_some_and(|n| effects::preview::draws_geometry(&d.symbol_boxes(), n)) {
|
||||
pinned.insert(id, at);
|
||||
}
|
||||
// Pixel snapping after the turn can move a pixel-aligned target: its point is checked
|
||||
// too, but not put back, since that would move its aligned art off the grid.
|
||||
if pinned.contains_key(&id) || d.node(id).is_some_and(|n| snaps_after_edit(n, &symbols)) {
|
||||
checked.insert(id, at);
|
||||
}
|
||||
}
|
||||
if wanted.is_some() {
|
||||
let fit = Fit { at, refi: reference as usize, goal: match_goal(size, (w, h), b.rect), strokes, corners };
|
||||
@@ -571,6 +589,32 @@ fn match_objects(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(bad(C, "a clipping path can't change its place in the stacking order"));
|
||||
}
|
||||
let parent = d.parent_of(source);
|
||||
// Each target leaves its own container, so a target's locked container refuses too.
|
||||
let locked = |p: Option<NodeId>| p.is_some_and(|p| crate::cmd::layer::locked_within(d, p));
|
||||
if locked(parent) || targets.iter().any(|t| locked(d.parent_of(*t))) {
|
||||
return Err(bad(C, "the layer or group is locked"));
|
||||
}
|
||||
// A blend's input objects, and art inside them, stay in the blend: the whole blend can still be
|
||||
// restacked, and art can still move within the blend's input it is in.
|
||||
let is_blend = |a: &NodeId| d.node(*a).is_some_and(|n| matches!(n.kind, NodeKind::Blend { .. }));
|
||||
let destination = parent.and_then(|p| d.ancestry(p)).unwrap_or_default();
|
||||
let leaves_blend = |t: &NodeId| {
|
||||
let chain = d.ancestry(*t).unwrap_or_default();
|
||||
chain.windows(2).filter(|w| is_blend(&w[0])).any(|w| !destination.windows(2).any(|v| v == w))
|
||||
};
|
||||
if targets.iter().any(leaves_blend) {
|
||||
return Err(bad(C, "a blend's input objects can't leave their blend input: to restack the blend, select the whole blend"));
|
||||
}
|
||||
// Live Paint art is rebuilt from its paths when they move: Match Objects leaves it in place.
|
||||
let in_live_paint =
|
||||
|id: NodeId| d.ancestry(id).unwrap_or_default().iter().any(|a| d.node(*a).is_some_and(vectorcraft_tools::builder::is_live_paint));
|
||||
if parent.is_some_and(in_live_paint) || targets.iter().any(|t| d.parent_of(*t).is_some_and(in_live_paint)) {
|
||||
return Err(bad(C, "Live Paint art can't be restacked here: use the Layers panel"));
|
||||
}
|
||||
// The source's container takes each target only as the Layers panel would (not a blend's inputs).
|
||||
if let Some(n) = targets.iter().filter_map(|id| d.node(*id)).find(|n| !crate::cmd::layer::accepts(d, parent, n)) {
|
||||
return Err(bad(C, format!("{} can't go beside the source object", n.display_name())));
|
||||
}
|
||||
if let Some(what) = targets.iter().filter_map(|id| d.node(*id)).find_map(|n| crate::cmd::intertwine::refused_in(d, parent, n)) {
|
||||
return Err(bad(C, format!("{what} can't be intertwined")));
|
||||
}
|
||||
@@ -585,11 +629,26 @@ fn match_objects(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let ids: Vec<NodeId> = xfs.iter().map(|(id, _)| *id).collect();
|
||||
let mut sc = scaling(s, &q);
|
||||
sc.patterns = transform_patterns(s, &q, &ids)?;
|
||||
let measure = s.bounds_measure();
|
||||
let before = s.doc()?.doc.clone();
|
||||
s.edit("Match Objects", |d, _| {
|
||||
for (id, xf) in &xfs {
|
||||
if let Some(n) = d.node_mut(*id) {
|
||||
transform_node(n, *xf, sc, true);
|
||||
}
|
||||
// A live effect that moves the art in page space (a Transform effect's offset) does
|
||||
// not turn with it: the measured reference point is put back where it was.
|
||||
if let Some(at) = pinned.get(id)
|
||||
&& let Some(b) = effects::preview::oriented_bounds_with(d, &[*id], measure)
|
||||
{
|
||||
let now = b.to_doc() * vectorcraft_geom::reference_point(b.rect, reference as usize);
|
||||
let off = *at - now;
|
||||
if off.hypot() > 1e-9
|
||||
&& let Some(n) = d.node_mut(*id)
|
||||
{
|
||||
transform_node(n, Affine::translate(off), sc, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
if restack {
|
||||
let moved = d.remove_many(&targets)?;
|
||||
@@ -597,6 +656,26 @@ fn match_objects(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// Targets moved out of an Intertwine group leave it as ordinary art.
|
||||
crate::cmd::intertwine::settle_members(d, &placed, &left)?;
|
||||
}
|
||||
if !checked.is_empty() {
|
||||
// Measured on a snapped copy: the edit itself snaps once, after Global Edit.
|
||||
let mut snapped = d.clone();
|
||||
crate::cmd::refresh_pixel_aligned(&before, &mut snapped);
|
||||
for (id, _) in &xfs {
|
||||
let Some(at) = checked.get(id) else { continue };
|
||||
let ob = effects::preview::oriented_bounds_with(&snapped, &[*id], measure);
|
||||
let kept = ob.is_some_and(|b| (*at - b.to_doc() * vectorcraft_geom::reference_point(b.rect, reference as usize)).hypot() <= 1e-6);
|
||||
let misses = !kept
|
||||
|| ob.is_none_or(|b| match size {
|
||||
"none" => false,
|
||||
"width" => (b.rect.width() - w).abs() > 1e-6,
|
||||
"height" => (b.rect.height() - h).abs() > 1e-6,
|
||||
_ => (b.rect.width() - w).abs() > 1e-6 || (b.rect.height() - h).abs() > 1e-6,
|
||||
});
|
||||
if misses {
|
||||
return Err(bad(C, format!("object {} can't keep its size and reference point as it turns", id.0)));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(count)
|
||||
|
||||
@@ -0,0 +1,202 @@
|
||||
//! Add Artboard Guides (`addon.arrange.artboardGuides`): a rectangular guide around each chosen
|
||||
//! artboard, `offset` outside its edges (inside when negative), on a top-level layer named
|
||||
//! Artboard Guides. Its dialog is the UI's.
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
use std::collections::HashSet;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{Document, Node, NodeId, NodeKind};
|
||||
use vectorcraft_geom::{Anchor, PathData, Point, Rect, shapes};
|
||||
|
||||
use super::super::super::panelcmds::{artboard_at, listed_artboards};
|
||||
use super::super::super::{CommandSpec, bad, cmd, has_doc, switch_or};
|
||||
use super::{LIMIT, number_in};
|
||||
use crate::sanity::rect_in_range;
|
||||
use crate::{DocState, Result, Session};
|
||||
|
||||
/// The command.
|
||||
pub(crate) const COMMAND: &str = "addon.arrange.artboardGuides";
|
||||
/// The top-level layer the guides go on, made when the document has none of that name.
|
||||
pub(crate) const LAYER: &str = "Artboard Guides";
|
||||
|
||||
pub(super) fn specs() -> Vec<CommandSpec> {
|
||||
vec![cmd!(
|
||||
"addon.arrange.artboardGuides",
|
||||
"Add Artboard Guides",
|
||||
["Object", "Plug-ins", "Arrange Tools"],
|
||||
None,
|
||||
"{offset?: pt −1000000..1000000 (0: on the artboard's edges; more than 0 outside them, less than 0 inside), artboards?: [index…] (0-based; default: the active artboard, `artboard`), artboard?: index (the active artboard, which the app passes; default the view's, which the journal then records as `artboard` for a replay), all?: false (true: every artboard; not with `artboards`)} add a rectangular guide path around each of those artboards, `offset` from its edges, as one undo step. The guides go on the topmost top-level layer named Artboard Guides, which keeps its lock and visibility; a new one is made above the others when there is none. The guide paths have the current paint (Release Guides makes them paths with it). A guide anywhere in that layer with the same rectangle is not added again, and a run that adds none makes no step. It is an error when an inset leaves an artboard no width or no height, and when an edge of a guide would lie more than 4,000,000 pt from the origin along either axis. Off without artboards → {ids, layer: id (null when nothing was added and there is no such layer), skipped (guides already there)}",
|
||||
has_artboards,
|
||||
artboard_guides
|
||||
)]
|
||||
}
|
||||
|
||||
/// A document with at least one artboard is open.
|
||||
fn has_artboards(s: &Session) -> std::result::Result<(), String> {
|
||||
has_doc(s)?;
|
||||
if s.doc().map_err(|e| e.to_string())?.doc.artboards.is_empty() { Err("the document has no artboards".into()) } else { Ok(()) }
|
||||
}
|
||||
|
||||
/// The index of the view's active artboard ([`DocState::active_artboard`]): when the document no
|
||||
/// longer has it, the artboard the document opened on, else the first.
|
||||
fn active_artboard(st: &DocState) -> usize {
|
||||
let d = &st.doc;
|
||||
let at = |id: Option<u32>| id.and_then(|id| d.artboards.iter().position(|a| a.id == id));
|
||||
at(st.active_artboard).or_else(|| at(d.opened_artboard)).unwrap_or(0)
|
||||
}
|
||||
|
||||
/// The topmost top-level layer named [`LAYER`].
|
||||
fn guide_layer(d: &Document) -> Option<NodeId> {
|
||||
d.layers.iter().rev().find(|l| matches!(l.kind, NodeKind::Layer { .. }) && l.name.as_deref() == Some(LAYER)).map(|l| l.id)
|
||||
}
|
||||
|
||||
/// `r`'s corners as an exact hash key, whichever way round `r` runs.
|
||||
fn rect_key(r: Rect) -> [u64; 4] {
|
||||
let r = r.abs();
|
||||
[r.x0, r.y0, r.x1, r.y1].map(|v| if v == 0.0 { 0 } else { v.to_bits() })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
static GUIDE_NODES_VISITED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
fn guide_rectangles(d: &Document, layer: Option<NodeId>) -> HashSet<[u64; 4]> {
|
||||
let mut rects = HashSet::new();
|
||||
if let Some(n) = layer.and_then(|id| d.node(id)) {
|
||||
n.walk(&mut |c| {
|
||||
#[cfg(test)]
|
||||
GUIDE_NODES_VISITED.with(|count| count.set(count.get() + 1));
|
||||
// The anchors' bounds: `traces` only accepts segments that stay between their anchors.
|
||||
if let NodeKind::Path { path, guide: true, .. } = &c.kind
|
||||
&& let [sp] = &path.subpaths[..]
|
||||
&& let Some(first) = sp.anchors.first()
|
||||
{
|
||||
let r = sp.anchors.iter().fold(Rect::from_points(first.p, first.p), |r, a| r.union_pt(a.p));
|
||||
let corners = [Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x1, r.y1), Point::new(r.x0, r.y1)];
|
||||
if traces(path, &corners) {
|
||||
rects.insert(rect_key(r));
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
rects
|
||||
}
|
||||
|
||||
/// Does the segment from `a` to `b` run straight along a horizontal or vertical line, from `a` to `b`
|
||||
/// without turning back? Its handles lie on that line, and the curve's position along it never reverses.
|
||||
fn straight(a: &Anchor, b: &Anchor) -> bool {
|
||||
let along = |f: fn(Point) -> f64, g: fn(Point) -> f64| {
|
||||
if [a.h_out, b.h_in].iter().any(|h| g(*h) != g(a.p)) || g(a.p) != g(b.p) {
|
||||
return false;
|
||||
}
|
||||
let s = (f(b.p) - f(a.p)).signum();
|
||||
let [p0, p1, p2, p3] = [a.p, a.h_out, b.h_in, b.p].map(|p| f(p) * s);
|
||||
// The derivative along the line, as a quadratic Bernstein form: never negative on [0, 1].
|
||||
let (u, v, w) = (p1 - p0, p2 - p1, p3 - p2);
|
||||
let curve = u - 2.0 * v + w;
|
||||
let vertex = if curve > 0.0 && (0.0..=1.0).contains(&((u - v) / curve)) { u - (u - v) * (u - v) / curve } else { 0.0 };
|
||||
u >= 0.0 && w >= 0.0 && vertex >= 0.0
|
||||
};
|
||||
if a.p == b.p {
|
||||
return a.h_out == a.p && b.h_in == a.p;
|
||||
}
|
||||
along(|p| p.x, |p| p.y) || along(|p| p.y, |p| p.x)
|
||||
}
|
||||
|
||||
/// Is `path` one closed run of straight segments through `corners`, from any corner, either way round?
|
||||
fn traces(path: &PathData, corners: &[Point; 4]) -> bool {
|
||||
let [sp] = &path.subpaths[..] else { return false };
|
||||
if !sp.closed || sp.anchors.len() < 4 {
|
||||
return false;
|
||||
}
|
||||
let n = sp.anchors.len();
|
||||
if (0..n).any(|i| !straight(&sp.anchors[i], &sp.anchors[(i + 1) % n])) {
|
||||
return false;
|
||||
}
|
||||
let points: Vec<Point> = sp
|
||||
.anchors
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(i, a)| {
|
||||
let prev = sp.anchors[(i + sp.anchors.len() - 1) % sp.anchors.len()].p;
|
||||
let next = sp.anchors[(i + 1) % sp.anchors.len()].p;
|
||||
let interior = (prev.x == a.p.x && a.p.x == next.x && a.p.y > prev.y.min(next.y) && a.p.y < prev.y.max(next.y))
|
||||
|| (prev.y == a.p.y && a.p.y == next.y && a.p.x > prev.x.min(next.x) && a.p.x < prev.x.max(next.x));
|
||||
(!interior).then_some(a.p)
|
||||
})
|
||||
.collect();
|
||||
let [first, second, _, _] = &points[..] else { return false };
|
||||
let (Some(start), Some(next)) = (corners.iter().position(|c| c == first), corners.iter().position(|c| c == second)) else {
|
||||
return false;
|
||||
};
|
||||
// 1 runs the way `corners` does, 3 the other way.
|
||||
let step = (next + 4 - start) % 4;
|
||||
(step == 1 || step == 3) && points.iter().enumerate().all(|(k, p)| *p == corners[(start + k * step) % 4])
|
||||
}
|
||||
|
||||
fn artboard_guides(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = COMMAND;
|
||||
let offset = number_in(p, "offset", 0.0, (-LIMIT, LIMIT), C)?;
|
||||
let all = switch_or(p, "all", false, C)?;
|
||||
let listed = p.get("artboards").filter(|v| !v.is_null());
|
||||
if all && listed.is_some() {
|
||||
return Err(bad(C, "give `all` or `artboards`, not both"));
|
||||
}
|
||||
let st = s.doc()?;
|
||||
let d = &st.doc;
|
||||
if d.artboards.is_empty() {
|
||||
return Err(bad(C, "the document has no artboards"));
|
||||
}
|
||||
// The active artboard: the one the app passes, else the view's, recorded for a replay.
|
||||
let active = artboard_at(d, p, "artboard", C)?;
|
||||
let indices: Vec<usize> = match listed {
|
||||
Some(v) => listed_artboards(d, v, "artboards", C)?,
|
||||
None if all => (0..d.artboards.len()).collect(),
|
||||
None => vec![active.unwrap_or_else(|| active_artboard(st))],
|
||||
};
|
||||
if let (false, None, None, Some(&i)) = (all, listed, active, indices.first()) {
|
||||
s.note_journal("artboard", json!(i));
|
||||
}
|
||||
let st = s.doc()?;
|
||||
let d = &st.doc;
|
||||
let layer = guide_layer(d);
|
||||
let mut existing = guide_rectangles(d, layer);
|
||||
let (mut rects, mut skipped) = (Vec::with_capacity(indices.len()), 0);
|
||||
for i in indices {
|
||||
let Some(board) = d.artboards.get(i) else { continue };
|
||||
let r = board.rect.inflate(offset, offset);
|
||||
if !(r.width() > 0.0 && r.height() > 0.0) {
|
||||
return Err(bad(C, format!("the inset leaves artboard {i} ({}) no width or height", board.name)));
|
||||
}
|
||||
if !rect_in_range(r) {
|
||||
return Err(bad(C, "the guide would reach past the edge of the canvas"));
|
||||
}
|
||||
if !existing.insert(rect_key(r)) {
|
||||
skipped += 1;
|
||||
} else {
|
||||
rects.push(r);
|
||||
}
|
||||
}
|
||||
if rects.is_empty() {
|
||||
return Ok(json!({ "ids": [], "layer": layer.map(|l| l.0), "skipped": skipped }));
|
||||
}
|
||||
let look = s.new_art_look(s.paint.fill.clone(), s.paint.stroke.clone(), s.paint.stroke_width);
|
||||
let (layer, ids) = s.edit("Add Artboard Guides", |d, _| {
|
||||
let layer = guide_layer(d).unwrap_or_else(|| d.add_layer(Some(LAYER)));
|
||||
let mut ids = Vec::with_capacity(rects.len());
|
||||
for r in &rects {
|
||||
let mut n = Node::path(d.alloc_id(), shapes::rectangle(*r), Default::default());
|
||||
look.apply(d, &mut n);
|
||||
if let NodeKind::Path { guide, .. } = &mut n.kind {
|
||||
*guide = true;
|
||||
}
|
||||
ids.push(d.insert(Some(layer), usize::MAX, n)?);
|
||||
}
|
||||
Ok((layer, ids))
|
||||
})?;
|
||||
Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "layer": layer.0, "skipped": skipped }))
|
||||
}
|
||||
@@ -0,0 +1,312 @@
|
||||
//! Add Artboard Guides: the guide rectangles it adds and where, the artboards it takes, the layer
|
||||
//! it reuses, one undo step (none when nothing is added), when it is off, and bad params refused
|
||||
//! without a change.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{NodeId, NodeKind};
|
||||
use vectorcraft_geom::{PathData, Point, Rect, SubPath};
|
||||
|
||||
use super::{COMMAND, LAYER};
|
||||
use crate::Session;
|
||||
|
||||
/// A new document with one 400 × 300 pt artboard and a second one beside it.
|
||||
fn session() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
s.execute("artboard.new", &json!({"x": 600, "y": 0, "width": 200, "height": 100})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn steps(s: &Session) -> usize {
|
||||
s.doc().unwrap().history.undo.len()
|
||||
}
|
||||
|
||||
fn board(s: &Session, i: usize) -> Rect {
|
||||
s.doc().unwrap().doc.artboards[i].rect
|
||||
}
|
||||
|
||||
fn ids(r: &Value) -> Vec<NodeId> {
|
||||
r["ids"].as_array().unwrap().iter().map(|v| NodeId(v.as_u64().unwrap())).collect()
|
||||
}
|
||||
|
||||
/// The guide rectangle of path `id`: its bounds, and that it is a guide on layer `layer`.
|
||||
fn guide(s: &Session, layer: NodeId, id: NodeId) -> Rect {
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let n = d.node(id).unwrap();
|
||||
assert!(matches!(n.kind, NodeKind::Path { guide: true, .. }), "{id:?} is a guide path");
|
||||
assert!(d.node(layer).unwrap().children().unwrap().iter().any(|c| c.id == id), "{id:?} is on the guides layer");
|
||||
n.geometric_bounds().unwrap()
|
||||
}
|
||||
|
||||
fn near(a: Rect, b: Rect) -> bool {
|
||||
[(a.x0, b.x0), (a.y0, b.y0), (a.x1, b.x1), (a.y1, b.y1)].iter().all(|(x, y)| (x - y).abs() < 1e-9)
|
||||
}
|
||||
|
||||
fn layer_names(s: &Session) -> Vec<String> {
|
||||
s.doc().unwrap().doc.layers.iter().map(|l| l.display_name()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_positive_offset_puts_a_guide_outside_the_active_artboard_on_a_new_layer() {
|
||||
let mut s = session();
|
||||
let n = steps(&s);
|
||||
let before = layer_names(&s);
|
||||
let r = s.execute(COMMAND, &json!({"offset": 9})).unwrap();
|
||||
assert_eq!(steps(&s), n + 1, "one undo step");
|
||||
let layer = NodeId(r["layer"].as_u64().unwrap());
|
||||
assert_eq!(r["skipped"], json!(0));
|
||||
let [id] = ids(&r)[..] else { panic!("one guide: {r}") };
|
||||
// The active artboard is the first when the view has not picked one.
|
||||
assert!(near(guide(&s, layer, id), board(&s, 0).inflate(9.0, 9.0)), "{:?}", guide(&s, layer, id));
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_eq!(d.layers.last().unwrap().id, layer, "the new layer goes above the others");
|
||||
assert_eq!(d.layers.last().unwrap().display_name(), LAYER);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(layer_names(&s), before, "undo takes the layer away with the guide");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_active_artboard_is_the_one_the_view_keeps() {
|
||||
let mut s = session();
|
||||
let second = s.doc().unwrap().doc.artboards[1].id;
|
||||
s.doc_mut().unwrap().active_artboard = Some(second);
|
||||
let r = s.execute(COMMAND, &json!({})).unwrap();
|
||||
let layer = NodeId(r["layer"].as_u64().unwrap());
|
||||
let [id] = ids(&r)[..] else { panic!("one guide: {r}") };
|
||||
assert!(near(guide(&s, layer, id), board(&s, 1)), "offset 0: on the artboard's edges");
|
||||
assert_eq!(s.journal.last().unwrap().1["artboard"], json!(1), "the journal records the artboard for a replay");
|
||||
// The artboard the app passes wins over the view's.
|
||||
let r = s.execute(COMMAND, &json!({"offset": 4, "artboard": 0})).unwrap();
|
||||
let [id] = ids(&r)[..] else { panic!("one guide: {r}") };
|
||||
assert!(near(guide(&s, layer, id), board(&s, 0).inflate(4.0, 4.0)));
|
||||
assert!(s.execute(COMMAND, &json!({"artboard": 5})).is_err(), "no such artboard");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_negative_offset_insets_every_artboard_and_reuses_the_layer_keeping_its_lock_and_visibility() {
|
||||
let mut s = session();
|
||||
let layer = NodeId(s.execute("layer.new", &json!({"name": LAYER})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("layer.new", &json!({"name": "Art"})).unwrap();
|
||||
s.execute("layer.setProps", &json!({"id": layer.0, "locked": true})).unwrap();
|
||||
s.execute("layer.setProps", &json!({"ids": [layer.0], "visible": false})).unwrap();
|
||||
let (layers, n) = (s.doc().unwrap().doc.layers.len(), steps(&s));
|
||||
let r = s.execute(COMMAND, &json!({"offset": -12, "all": true})).unwrap();
|
||||
assert_eq!(steps(&s), n + 1, "one undo step for every artboard");
|
||||
assert_eq!(r["layer"], json!(layer.0), "the layer of that name is reused");
|
||||
assert_eq!(s.doc().unwrap().doc.layers.len(), layers, "no layer is added");
|
||||
let added = ids(&r);
|
||||
assert_eq!(added.len(), 2);
|
||||
for (i, id) in added.into_iter().enumerate() {
|
||||
assert!(near(guide(&s, layer, id), board(&s, i).inflate(-12.0, -12.0)), "artboard {i}");
|
||||
}
|
||||
let l = s.doc().unwrap().doc.node(layer).unwrap().clone();
|
||||
assert!(l.locked && !l.visible, "the layer keeps its lock and visibility");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn listed_artboards_get_a_guide_each_and_a_guide_already_there_is_not_added_again() {
|
||||
let mut s = session();
|
||||
let r = s.execute(COMMAND, &json!({"offset": 5, "artboards": [1]})).unwrap();
|
||||
let layer = NodeId(r["layer"].as_u64().unwrap());
|
||||
let [id] = ids(&r)[..] else { panic!("one guide: {r}") };
|
||||
assert!(near(guide(&s, layer, id), board(&s, 1).inflate(5.0, 5.0)));
|
||||
// Again: nothing to add, and no undo step.
|
||||
let (before, n) = (s.doc().unwrap().doc.clone(), steps(&s));
|
||||
let again = s.execute(COMMAND, &json!({"offset": 5, "artboards": [1, 1]})).unwrap();
|
||||
assert_eq!(again, json!({"ids": [], "layer": layer.0, "skipped": 1}));
|
||||
assert_eq!(steps(&s), n, "a run that adds nothing makes no step");
|
||||
assert!(Arc::ptr_eq(&s.doc().unwrap().doc, &before) || *s.doc().unwrap().doc == *before);
|
||||
// Both artboards: only the new one is added.
|
||||
let both = s.execute(COMMAND, &json!({"offset": 5, "artboards": [0, 1]})).unwrap();
|
||||
assert_eq!(both["skipped"], json!(1));
|
||||
let [first] = ids(&both)[..] else { panic!("one guide: {both}") };
|
||||
assert!(near(guide(&s, layer, first), board(&s, 0).inflate(5.0, 5.0)));
|
||||
assert_eq!(steps(&s), n + 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_guide_grouped_inside_the_layer_is_not_added_again() {
|
||||
let mut s = session();
|
||||
let r = s.execute(COMMAND, &json!({"offset": 5})).unwrap();
|
||||
let layer = NodeId(r["layer"].as_u64().unwrap());
|
||||
let [id] = ids(&r)[..] else { panic!("one guide: {r}") };
|
||||
s.execute("view.guides.lock", &json!({"locked": false})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert!(d.node(layer).unwrap().children().unwrap().iter().any(|c| c.id == group));
|
||||
assert!(d.node(group).unwrap().children().unwrap().iter().any(|c| c.id == id));
|
||||
let (before, n) = (d.clone(), steps(&s));
|
||||
let again = s.execute(COMMAND, &json!({"offset": 5})).unwrap();
|
||||
assert_eq!(again, json!({"ids": [], "layer": layer.0, "skipped": 1}));
|
||||
assert_eq!(steps(&s), n, "a run that adds nothing makes no step");
|
||||
assert!(*s.doc().unwrap().doc == *before, "the document is unchanged");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_guide_drawn_the_other_way_round_or_from_another_corner_is_not_added_again() {
|
||||
let mut s = session();
|
||||
let r = s.execute(COMMAND, &json!({"offset": 5})).unwrap();
|
||||
let layer = NodeId(r["layer"].as_u64().unwrap());
|
||||
let [id] = ids(&r)[..] else { panic!("one guide: {r}") };
|
||||
let b = board(&s, 0).inflate(5.0, 5.0);
|
||||
let corners = [Point::new(b.x0, b.y1), Point::new(b.x1, b.y1), Point::new(b.x1, b.y0), Point::new(b.x0, b.y0)];
|
||||
// Reversed from the top-left corner, reversed from the bottom-left one, and the same way round from the bottom-right one.
|
||||
for points in [vec![corners[3], corners[0], corners[1], corners[2]], corners.to_vec(), vec![corners[1], corners[0], corners[3], corners[2]]] {
|
||||
let d = Arc::make_mut(&mut s.doc_mut().unwrap().doc);
|
||||
if let Some(NodeKind::Path { path, .. }) = d.node_mut(id).map(|n| &mut n.kind) {
|
||||
*path = PathData::single(SubPath::polyline(&points, true));
|
||||
}
|
||||
let n = steps(&s);
|
||||
let again = s.execute(COMMAND, &json!({"offset": 5})).unwrap();
|
||||
assert_eq!(again, json!({"ids": [], "layer": layer.0, "skipped": 1}), "{points:?}");
|
||||
assert_eq!(steps(&s), n);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn collinear_midpoints_do_not_add_another_guide_or_history_step() {
|
||||
let mut s = session();
|
||||
let r = s.execute(COMMAND, &json!({})).unwrap();
|
||||
let [id] = ids(&r)[..] else { panic!("one guide: {r}") };
|
||||
let b = board(&s, 0);
|
||||
let points = [
|
||||
Point::new(b.center().x, b.y0),
|
||||
Point::new(b.x1, b.y0),
|
||||
Point::new(b.x1, b.center().y),
|
||||
Point::new(b.x1, b.y1),
|
||||
Point::new(b.center().x, b.y1),
|
||||
Point::new(b.x0, b.y1),
|
||||
Point::new(b.x0, b.center().y),
|
||||
Point::new(b.x0, b.y0),
|
||||
];
|
||||
for reverse in [false, true] {
|
||||
let mut points = points.to_vec();
|
||||
if reverse {
|
||||
points.reverse();
|
||||
}
|
||||
let d = Arc::make_mut(&mut s.doc_mut().unwrap().doc);
|
||||
let NodeKind::Path { path, .. } = &mut d.node_mut(id).unwrap().kind else { panic!("guide path") };
|
||||
*path = PathData::single(SubPath::polyline(&points, true));
|
||||
let (before, n) = (s.doc().unwrap().doc.clone(), steps(&s));
|
||||
let again = s.execute(COMMAND, &json!({})).unwrap();
|
||||
assert_eq!(again, json!({"ids": [], "layer": r["layer"], "skipped": 1}));
|
||||
assert_eq!(steps(&s), n);
|
||||
assert_eq!(s.doc().unwrap().doc, before);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn handles_along_a_side_still_match_and_handles_off_it_do_not() {
|
||||
let mut s = session();
|
||||
let r = s.execute(COMMAND, &json!({})).unwrap();
|
||||
let [id] = ids(&r)[..] else { panic!("one guide: {r}") };
|
||||
let b = board(&s, 0);
|
||||
let mid = Point::new(b.center().x, b.y0);
|
||||
let points = [mid, Point::new(b.x1, b.y0), Point::new(b.x1, b.y1), Point::new(b.x0, b.y1), Point::new(b.x0, b.y0)];
|
||||
let corner = points[1];
|
||||
let set = |s: &mut Session, h_in: Point, h_out: Point, corner_in: Point| {
|
||||
let mut sp = SubPath::polyline(&points, true);
|
||||
sp.anchors[0].h_in = h_in;
|
||||
sp.anchors[0].h_out = h_out;
|
||||
sp.anchors[1].h_in = corner_in;
|
||||
let d = Arc::make_mut(&mut s.doc_mut().unwrap().doc);
|
||||
let NodeKind::Path { path, .. } = &mut d.node_mut(id).unwrap().kind else { panic!("guide path") };
|
||||
*path = PathData::single(sp);
|
||||
};
|
||||
// The extra anchor's handles lie along the top side: the guide still matches.
|
||||
// Then a handle past the corner on a segment that still runs one way (along x: 0, 9, 6, 8 eighths).
|
||||
let eighth = (corner.x - mid.x) / 8.0;
|
||||
for (h_out, corner_in) in
|
||||
[(Point::new(mid.x + 20.0, b.y0), corner), (Point::new(mid.x + 9.0 * eighth, b.y0), Point::new(mid.x + 6.0 * eighth, b.y0))]
|
||||
{
|
||||
set(&mut s, Point::new(mid.x - 20.0, b.y0), h_out, corner_in);
|
||||
let (before, n) = (s.doc().unwrap().doc.clone(), steps(&s));
|
||||
let again = s.execute(COMMAND, &json!({})).unwrap();
|
||||
assert_eq!(again, json!({"ids": [], "layer": r["layer"], "skipped": 1}), "{h_out:?} {corner_in:?}");
|
||||
assert_eq!(steps(&s), n);
|
||||
assert_eq!(s.doc().unwrap().doc, before);
|
||||
}
|
||||
// A handle off the side bends it: the path is not that guide, so one is added.
|
||||
set(&mut s, Point::new(mid.x - 20.0, b.y0), Point::new(mid.x + 20.0, b.y0 + 10.0), corner);
|
||||
let other = s.execute(COMMAND, &json!({})).unwrap();
|
||||
assert_eq!(other["skipped"], json!(0));
|
||||
assert_eq!(ids(&other).len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_artboard_shares_one_walk_of_existing_guides() {
|
||||
let mut s = session();
|
||||
s.execute(COMMAND, &json!({"all": true})).unwrap();
|
||||
super::GUIDE_NODES_VISITED.with(|count| count.set(0));
|
||||
s.execute(COMMAND, &json!({})).unwrap();
|
||||
let single = super::GUIDE_NODES_VISITED.with(|count| count.replace(0));
|
||||
assert!(single > 0);
|
||||
let n = steps(&s);
|
||||
let r = s.execute(COMMAND, &json!({"all": true})).unwrap();
|
||||
assert_eq!(super::GUIDE_NODES_VISITED.with(|count| count.get()), single);
|
||||
assert!(ids(&r).is_empty());
|
||||
assert_eq!(r["skipped"], json!(2));
|
||||
assert_eq!(steps(&s), n);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn release_guides_gives_back_a_rectangle_path() {
|
||||
let mut s = session();
|
||||
let r = s.execute(COMMAND, &json!({"offset": 3})).unwrap();
|
||||
let [id] = ids(&r)[..] else { panic!("one guide: {r}") };
|
||||
s.execute("view.guides.release", &json!({"ids": [id.0]})).unwrap();
|
||||
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
|
||||
assert!(matches!(n.kind, NodeKind::Path { guide: false, .. }));
|
||||
assert!(near(n.geometric_bounds().unwrap(), board(&s, 0).inflate(3.0, 3.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_inset_that_leaves_no_width_or_height_and_bad_params_are_refused_without_a_change() {
|
||||
let mut s = session();
|
||||
let (before, n) = (s.doc().unwrap().doc.clone(), steps(&s));
|
||||
// The second artboard is 100 pt tall: an inset of 50 leaves it no height.
|
||||
for p in [
|
||||
json!({"offset": -50, "all": true}),
|
||||
json!({"offset": -200}),
|
||||
json!({"offset": "9 pt"}),
|
||||
json!({"offset": 1_000_001}),
|
||||
json!({"offset": -1e308}),
|
||||
json!({"all": 1}),
|
||||
json!({"all": true, "artboards": [0]}),
|
||||
json!({"artboards": []}),
|
||||
json!({"artboards": [2]}),
|
||||
json!({"artboards": [-1]}),
|
||||
json!({"artboards": [0.5]}),
|
||||
json!({"artboards": "0"}),
|
||||
] {
|
||||
assert!(s.execute(COMMAND, &p).is_err(), "{p}");
|
||||
}
|
||||
assert_eq!(steps(&s), n);
|
||||
assert!(*s.doc().unwrap().doc == *before, "the document is unchanged");
|
||||
let e = s.execute(COMMAND, &json!({"offset": -150})).unwrap_err().to_string();
|
||||
assert!(e.contains("no width or height"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_guide_past_the_edge_of_the_canvas_is_refused() {
|
||||
let mut s = session();
|
||||
s.execute("artboard.new", &json!({"x": 3_999_000, "y": 0, "width": 500, "height": 100})).unwrap();
|
||||
let n = steps(&s);
|
||||
let e = s.execute(COMMAND, &json!({"offset": 600, "artboards": [2]})).unwrap_err().to_string();
|
||||
assert!(e.contains("past the edge of the canvas"), "{e}");
|
||||
assert_eq!(steps(&s), n);
|
||||
s.execute(COMMAND, &json!({"offset": 400, "artboards": [2]})).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn it_is_off_without_artboards() {
|
||||
let mut s = session();
|
||||
let enabled = |s: &Session| s.commands().into_iter().find(|c| c.id == COMMAND).unwrap().enabled;
|
||||
assert!(enabled(&s));
|
||||
Arc::make_mut(&mut s.doc_mut().unwrap().doc).artboards.clear();
|
||||
assert!(!enabled(&s));
|
||||
assert!(s.execute(COMMAND, &json!({})).is_err());
|
||||
}
|
||||
@@ -525,6 +525,67 @@ fn match_size_and_rotation_measure_pixel_aligned_art_in_its_final_frame() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_rotation_refuses_when_pixel_snapping_would_move_the_reference_point() {
|
||||
for wrap in ["path", "group", "compound"] {
|
||||
let mut s = session();
|
||||
let target = rect(&mut s, 0.0, 0.0, 10.0, 11.0);
|
||||
if wrap != "compound" {
|
||||
s.execute("object.setPixelAligned", &json!({"on": true})).unwrap();
|
||||
}
|
||||
let target = match wrap {
|
||||
"group" => NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()),
|
||||
"compound" => NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap()),
|
||||
_ => target,
|
||||
};
|
||||
select(&mut s, &[target]);
|
||||
if wrap == "compound" {
|
||||
s.execute("object.setPixelAligned", &json!({"on": true})).unwrap();
|
||||
}
|
||||
let source = rect(&mut s, 100.0, 0.0, 10.0, 10.0);
|
||||
select(&mut s, &[source]);
|
||||
s.execute("object.rotate", &json!({"angle": 90})).unwrap();
|
||||
select(&mut s, &[target, source]);
|
||||
s.execute("select.key", &json!({"id": source.0})).unwrap();
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let n = steps(&s);
|
||||
// Turned a quarter about its center (5, 5.5), the 10 x 11 path's edges land on half points,
|
||||
// and snapping them back to the grid would move that center.
|
||||
let e = s.execute("addon.arrange.match", &json!({"rotate": true})).unwrap_err().to_string();
|
||||
assert!(e.contains("reference point"), "{wrap}: {e}");
|
||||
assert_eq!(steps(&s), n, "{wrap}: no undo step");
|
||||
assert!(*s.doc().unwrap().doc == *before, "{wrap}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_rotation_keeps_a_mixed_group_in_one_piece_or_refuses() {
|
||||
let mut s = session();
|
||||
let aligned = rect(&mut s, 0.0, 0.0, 10.0, 11.0);
|
||||
s.execute("object.setPixelAligned", &json!({"on": true})).unwrap();
|
||||
let loose = rect(&mut s, 20.0, 0.0, 10.0, 11.0);
|
||||
select(&mut s, &[aligned, loose]);
|
||||
let target = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
let source = rect(&mut s, 100.0, 0.0, 10.0, 10.0);
|
||||
select(&mut s, &[source]);
|
||||
s.execute("object.rotate", &json!({"angle": 90})).unwrap();
|
||||
select(&mut s, &[target, source]);
|
||||
s.execute("select.key", &json!({"id": source.0})).unwrap();
|
||||
let gap = |s: &Session| {
|
||||
let (a, b) = (s.transform_box(&[aligned]).unwrap().center(), s.transform_box(&[loose]).unwrap().center());
|
||||
b - a
|
||||
};
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
match s.execute("addon.arrange.match", &json!({"rotate": true})) {
|
||||
// Turned a quarter, the members' centers keep their distance and only change direction.
|
||||
Ok(_) => assert!((gap(&s).hypot() - 20.0).abs() < 1e-6, "the members moved apart: {:?}", gap(&s)),
|
||||
Err(e) => {
|
||||
assert!(e.to_string().contains("reference point"), "{e}");
|
||||
assert!(*s.doc().unwrap().doc == *before);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_rotation_refuses_a_target_without_bounds_when_its_angle_differs() {
|
||||
for angle in [0, 30] {
|
||||
@@ -811,6 +872,234 @@ fn match_stacking_refuses_intertwine_nesting_beside_an_empty_group() {
|
||||
assert!(*s.doc().unwrap().doc == *before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_refuses_restacking_into_a_locked_container() {
|
||||
for lock_ancestor in [false, true] {
|
||||
let mut s = session();
|
||||
let source = rect(&mut s, 0.0, 0.0, 20.0, 20.0);
|
||||
select(&mut s, &[source]);
|
||||
let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
select(&mut s, &[group]);
|
||||
let ancestor = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
let target = rect(&mut s, 100.0, 0.0, 40.0, 40.0);
|
||||
select(&mut s, &[source, target]);
|
||||
s.execute("select.key", &json!({"id": source.0})).unwrap();
|
||||
let locked = if lock_ancestor { ancestor } else { group };
|
||||
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(locked).unwrap().locked = true;
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let n = steps(&s);
|
||||
let e = s.execute("addon.arrange.match", &json!({"size": "both", "stacking": true})).unwrap_err();
|
||||
assert!(e.to_string().contains("the layer or group is locked"), "{e}");
|
||||
assert_eq!(steps(&s), n);
|
||||
assert_eq!(s.doc().unwrap().doc.layers, before.layers);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_refuses_restacking_among_a_blends_inputs() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0);
|
||||
let b = rect(&mut s, 100.0, 0.0, 20.0, 20.0);
|
||||
select(&mut s, &[a, b]);
|
||||
s.execute("object.blend.make", &json!({})).unwrap();
|
||||
let target = rect(&mut s, 200.0, 0.0, 20.0, 20.0);
|
||||
select(&mut s, &[a, target]);
|
||||
s.execute("select.key", &json!({"id": a.0})).unwrap();
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let n = steps(&s);
|
||||
let e = s.execute("addon.arrange.match", &json!({"stacking": true})).unwrap_err();
|
||||
assert!(e.to_string().contains("can't go beside the source object"), "{e}");
|
||||
assert_eq!(steps(&s), n);
|
||||
assert_eq!(s.doc().unwrap().doc.layers, before.layers);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_refuses_taking_a_target_out_of_a_locked_container() {
|
||||
let mut s = session();
|
||||
let target = rect(&mut s, 100.0, 0.0, 40.0, 40.0);
|
||||
select(&mut s, &[target]);
|
||||
let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
let source = rect(&mut s, 0.0, 0.0, 20.0, 20.0);
|
||||
select(&mut s, &[source, target]);
|
||||
s.execute("select.key", &json!({"id": source.0})).unwrap();
|
||||
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(group).unwrap().locked = true;
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let n = steps(&s);
|
||||
let e = s.execute("addon.arrange.match", &json!({"stacking": true})).unwrap_err();
|
||||
assert!(e.to_string().contains("the layer or group is locked"), "{e}");
|
||||
assert_eq!(steps(&s), n);
|
||||
assert_eq!(s.doc().unwrap().doc.layers, before.layers);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_refuses_taking_a_target_out_of_a_blend_but_restacks_the_whole_blend() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0);
|
||||
let b = rect(&mut s, 100.0, 0.0, 20.0, 20.0);
|
||||
select(&mut s, &[a, b]);
|
||||
let blend = NodeId(s.execute("object.blend.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
let between = rect(&mut s, 200.0, 0.0, 20.0, 20.0);
|
||||
let source = rect(&mut s, 250.0, 0.0, 20.0, 20.0);
|
||||
assert_eq!(layer_order(&s), [blend, between, source]);
|
||||
select(&mut s, &[a, source]);
|
||||
s.execute("select.key", &json!({"id": source.0})).unwrap();
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let n = steps(&s);
|
||||
let e = s.execute("addon.arrange.match", &json!({"stacking": true})).unwrap_err();
|
||||
assert!(e.to_string().contains("a blend's input objects"), "{e}");
|
||||
assert_eq!(steps(&s), n);
|
||||
assert_eq!(s.doc().unwrap().doc.layers, before.layers);
|
||||
select(&mut s, &[blend, source]);
|
||||
s.execute("select.key", &json!({"id": source.0})).unwrap();
|
||||
s.execute("addon.arrange.match", &json!({"stacking": true})).unwrap();
|
||||
assert_eq!(steps(&s), n + 1, "one undo step");
|
||||
assert_eq!(layer_order(&s), [between, source, blend]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_refuses_restacking_live_paint_art_but_moves_beside_a_whole_group() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
|
||||
let b = rect(&mut s, 50.0, 0.0, 100.0, 100.0);
|
||||
select(&mut s, &[a, b]);
|
||||
let g = NodeId(s.execute("livePaint.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
let between = rect(&mut s, 200.0, 0.0, 20.0, 20.0);
|
||||
let target = rect(&mut s, 250.0, 0.0, 20.0, 20.0);
|
||||
assert_eq!(layer_order(&s), [g, between, target]);
|
||||
let member = s.doc().unwrap().doc.children(Some(g)).unwrap()[0].id;
|
||||
select(&mut s, &[member, target]);
|
||||
s.execute("select.key", &json!({"id": member.0})).unwrap();
|
||||
let n = steps(&s);
|
||||
let e = s.execute("addon.arrange.match", &json!({"stacking": true})).unwrap_err();
|
||||
assert!(e.to_string().contains("Live Paint art"), "{e}");
|
||||
assert_eq!(steps(&s), n);
|
||||
select(&mut s, &[g, target]);
|
||||
s.execute("select.key", &json!({"id": g.0})).unwrap();
|
||||
let before = s.doc().unwrap().doc.node(g).unwrap().clone();
|
||||
s.execute("addon.arrange.match", &json!({"stacking": true})).unwrap();
|
||||
assert_eq!(steps(&s), n + 1, "one undo step");
|
||||
assert_eq!(layer_order(&s), [g, target, between]);
|
||||
assert_eq!(s.doc().unwrap().doc.node(g).unwrap(), &before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_turns_art_with_a_moving_effect_about_its_measured_point() {
|
||||
let mut s = session();
|
||||
s.prefs.use_preview_bounds = true;
|
||||
let a = rect(&mut s, 0.0, 0.0, 20.0, 40.0);
|
||||
select(&mut s, &[a]);
|
||||
s.execute("object.rotate", &json!({"angle": 90})).unwrap();
|
||||
let b = rect(&mut s, 100.0, 100.0, 40.0, 20.0);
|
||||
s.execute("effect.apply", &json!({"ids": [b.0], "effect": "distort.transform", "params": {"moveH": 30}})).unwrap();
|
||||
let center = |s: &Session| {
|
||||
let bx = s.transform_box(&[b]).unwrap();
|
||||
bx.to_doc() * vectorcraft_geom::reference_point(bx.rect, 4)
|
||||
};
|
||||
let before = center(&s);
|
||||
select(&mut s, &[a, b]);
|
||||
s.execute("select.key", &json!({"id": a.0})).unwrap();
|
||||
s.execute("addon.arrange.match", &json!({"rotate": true})).unwrap();
|
||||
let after = center(&s);
|
||||
assert!((after - before).hypot() < 1e-6, "{before:?} -> {after:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_checks_a_pixel_aligned_symbols_measured_point_after_snapping() {
|
||||
for size in ["none", "both"] {
|
||||
for dx in [0.0, 0.25] {
|
||||
let mut s = session();
|
||||
s.prefs.use_preview_bounds = true;
|
||||
let source = rect(&mut s, 0.0, 0.0, 40.0, 20.0);
|
||||
let art = rect(&mut s, 100.0, 100.0, 40.0, 20.0);
|
||||
select(&mut s, &[art]);
|
||||
let target = NodeId(s.execute("symbol.new", &json!({"name": "Aligned", "alignToPixelGrid": true})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("object.rotate", &json!({"angle": 30})).unwrap();
|
||||
s.execute("object.move", &json!({"dx": dx})).unwrap();
|
||||
s.execute("effect.apply", &json!({"ids": [target.0], "effect": "distort.transform", "params": {"moveH": 30}})).unwrap();
|
||||
let center = |s: &Session| {
|
||||
let b = s.transform_box(&[target]).unwrap();
|
||||
b.to_doc() * vectorcraft_geom::reference_point(b.rect, 4)
|
||||
};
|
||||
let at = center(&s);
|
||||
select(&mut s, &[source, target]);
|
||||
s.execute("select.key", &json!({"id": source.0})).unwrap();
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let n = steps(&s);
|
||||
let result = s.execute("addon.arrange.match", &json!({"rotate": true, "size": size}));
|
||||
if dx == 0.0 {
|
||||
result.unwrap();
|
||||
assert!((center(&s) - at).hypot() < 1e-6, "{size}");
|
||||
let b = s.transform_box(&[target]).unwrap();
|
||||
assert!(b.angle.abs() < 1e-6, "{size}: {b:?}");
|
||||
if size == "both" {
|
||||
let wanted = s.transform_box(&[source]).unwrap();
|
||||
assert!((b.rect.width() - wanted.rect.width()).abs() < 1e-6, "{size}: {b:?}");
|
||||
assert!((b.rect.height() - wanted.rect.height()).abs() < 1e-6, "{size}: {b:?}");
|
||||
}
|
||||
assert_eq!(steps(&s), n + 1);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
} else {
|
||||
let error = result.unwrap_err().to_string();
|
||||
assert!(error.contains("can't keep its size and reference point as it turns"), "{size}: {error}");
|
||||
}
|
||||
assert_eq!(steps(&s), n, "{size}, dx={dx}");
|
||||
assert!(*s.doc().unwrap().doc == *before, "{size}, dx={dx}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_refuses_when_snapping_moves_a_pixel_aligned_symbol_instance_without_preview_bounds() {
|
||||
let mut s = session();
|
||||
s.prefs.use_preview_bounds = false;
|
||||
let source = rect(&mut s, 0.0, 0.0, 40.0, 20.0);
|
||||
let art = rect(&mut s, 100.0, 100.0, 40.0, 20.0);
|
||||
select(&mut s, &[art]);
|
||||
let target = NodeId(s.execute("symbol.new", &json!({"name": "Aligned", "alignToPixelGrid": true})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("object.rotate", &json!({"angle": 30})).unwrap();
|
||||
s.execute("object.move", &json!({"dx": 0.25})).unwrap();
|
||||
select(&mut s, &[source, target]);
|
||||
s.execute("select.key", &json!({"id": source.0})).unwrap();
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let n = steps(&s);
|
||||
// Turned back to its natural angle, the instance snaps to whole points, which moves its center.
|
||||
let error = s.execute("addon.arrange.match", &json!({"rotate": true})).unwrap_err().to_string();
|
||||
assert!(error.contains("can't keep its size and reference point as it turns"), "{error}");
|
||||
assert_eq!(steps(&s), n);
|
||||
assert!(*s.doc().unwrap().doc == *before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_turns_art_with_a_moving_fill_effect_about_its_measured_point() {
|
||||
for grouped in [false, true] {
|
||||
let mut s = session();
|
||||
s.prefs.use_preview_bounds = true;
|
||||
let a = rect(&mut s, 0.0, 0.0, 20.0, 40.0);
|
||||
select(&mut s, &[a]);
|
||||
s.execute("object.rotate", &json!({"angle": 90})).unwrap();
|
||||
let b = rect(&mut s, 100.0, 100.0, 40.0, 20.0);
|
||||
s.execute("effect.apply", &json!({"ids": [b.0], "item": 0, "effect": "distort.transform", "params": {"moveH": 30}})).unwrap();
|
||||
let b = if grouped {
|
||||
select(&mut s, &[b]);
|
||||
NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap())
|
||||
} else {
|
||||
b
|
||||
};
|
||||
let center = |s: &Session| {
|
||||
let bx = s.transform_box(&[b]).unwrap();
|
||||
bx.to_doc() * vectorcraft_geom::reference_point(bx.rect, 4)
|
||||
};
|
||||
let before = center(&s);
|
||||
select(&mut s, &[a, b]);
|
||||
s.execute("select.key", &json!({"id": a.0})).unwrap();
|
||||
s.execute("addon.arrange.match", &json!({"rotate": true})).unwrap();
|
||||
let after = center(&s);
|
||||
assert!((after - before).hypot() < 1e-6, "grouped={grouped}: {before:?} -> {after:?}");
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert!((d.bbox_angle(&[b]) - d.bbox_angle(&[a])).abs() < 1e-6);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_replays_with_the_stroke_scaling_it_ran_with() {
|
||||
replays_the_stroke_scaling_it_ran_with("addon.arrange.match", json!({"size": "both"}));
|
||||
|
||||
@@ -140,6 +140,14 @@ pub(super) fn node_families(node: &mut Node, visit: &mut impl FnMut(&mut String)
|
||||
for run in &mut text.runs {
|
||||
visit(&mut run.style.font_family);
|
||||
}
|
||||
// The fonts the file carried for this type are found by the family its runs name.
|
||||
for font in text.file_fonts.iter_mut().flat_map(|fonts| fonts.fonts.iter_mut()) {
|
||||
visit(&mut font.family);
|
||||
}
|
||||
}
|
||||
// A live dimension makes its label again from its options.
|
||||
if let Some(dimension) = node.extras_if_any().and_then(|extras| extras.dimension.as_deref_mut()) {
|
||||
visit(&mut dimension.options.font_family);
|
||||
}
|
||||
graph_families(node, visit);
|
||||
}
|
||||
@@ -198,6 +206,20 @@ pub(super) fn plan_import(source: Vec<CompositeFont>, source_families: BTreeSet<
|
||||
target_taken.insert(font.name.to_lowercase());
|
||||
target_taken.extend(font.part_fonts().map(str::to_lowercase));
|
||||
}
|
||||
// Families the source names without defining them as composite fonts, which the target does
|
||||
// define: they stay undefined under a free name instead of taking the target's meaning.
|
||||
let undefined: Vec<String> = source_families
|
||||
.iter()
|
||||
.filter(|family| !source_names.contains(*family) && !FontDb::global().has_installed_family(family))
|
||||
.filter_map(|family| CompositeFont::named(&target.composite_fonts, family).map(|font| font.name.clone()))
|
||||
.collect();
|
||||
// Their alias may be a family the target's art already names without defining it, as an
|
||||
// earlier placement of the same art left it, so that placement and this one share resources.
|
||||
let mut alias_reserved = source_families.clone();
|
||||
for font in source.iter().chain(target.composite_fonts.iter()) {
|
||||
alias_reserved.insert(font.name.to_lowercase());
|
||||
alias_reserved.extend(font.part_fonts().map(str::to_lowercase));
|
||||
}
|
||||
let mut reserved = source_families;
|
||||
reserved.extend(target_families);
|
||||
for font in source.iter().chain(target.composite_fonts.iter()) {
|
||||
@@ -226,12 +248,18 @@ pub(super) fn plan_import(source: Vec<CompositeFont>, source_families: BTreeSet<
|
||||
combined.push(CompositeFont { name, ..font });
|
||||
}
|
||||
}
|
||||
alias_reserved.extend(names.values().map(|name| name.to_lowercase()));
|
||||
for family in undefined {
|
||||
let name = composite_alias(&family, &alias_reserved, cmd)?;
|
||||
alias_reserved.insert(name.to_lowercase());
|
||||
names.insert(family.to_lowercase(), name);
|
||||
}
|
||||
// A source document may currently lend fonts to the database. Validate the prospective
|
||||
// document, not composite names temporarily registered by a different document.
|
||||
if combined.len() > COMPOSITE_FONTS_MAX {
|
||||
return Err(bad(cmd, format!("a document keeps at most {COMPOSITE_FONTS_MAX} composite fonts")));
|
||||
}
|
||||
if let Some(font) = combined.iter().find(|font| db.has_installed_family(&font.name)) {
|
||||
if let Some(font) = combined.iter().skip(target.composite_fonts.len()).find(|font| db.has_installed_family(&font.name)) {
|
||||
return Err(bad(cmd, format!("`{}` is the name of an installed font", font.name)));
|
||||
}
|
||||
if CompositeFont::usable(&combined).is_some() {
|
||||
|
||||
@@ -108,7 +108,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Batch",
|
||||
[],
|
||||
None,
|
||||
"{label?, commands: [{command, params}], artboard?: index (the active artboard; the app passes it: each edit.pasteInPlace, edit.pasteInFront, edit.pasteInBack, object.align, object.distribute, object.distributeSpacing, select.allOnArtboard or symbol.edit step that names none gets it, and each artboard.fitToArt or artboard.fitToSelection step that names no index gets it as index, or the last artboard of a document with fewer; an artboard.fitToArt step that names neither index nor indices, while the Artboard tool is chosen with two or more artboards selected when the step runs, gets those as indices instead; the journal records the indices or index an artboard.fitToArt step got)} run several commands as ONE undo step (one in each document they edit: steps may open, switch, close or revert documents); stops at the first error and rolls everything back, documents included",
|
||||
"{label?, commands: [{command, params}], artboard?: index (the active artboard; the app passes it: each addon.arrange.artboardGuides, edit.pasteInPlace, edit.pasteInFront, edit.pasteInBack, object.align, object.distribute, object.distributeSpacing, select.allOnArtboard or symbol.edit step that names none gets it, and each artboard.fitToArt or artboard.fitToSelection step that names no index gets it as index, or the last artboard of a document with fewer; an artboard.fitToArt step that names neither index nor indices, while the Artboard tool is chosen with two or more artboards selected when the step runs, gets those as indices instead; the journal records the indices or index an artboard.fitToArt step got)} run several commands as ONE undo step (one in each document they edit: steps may open, switch, close or revert documents); stops at the first error and rolls everything back, documents included",
|
||||
has_doc,
|
||||
batch::batch
|
||||
),
|
||||
|
||||
@@ -129,7 +129,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Reorder",
|
||||
[],
|
||||
None,
|
||||
"{id, parent?: id (null = top level), index} put a row at `index` (0 = bottom) of `parent` (layers only at the top level or in layers; the clipping path of a clip group or clipping layer stays at its bottom: it does not move until the mask is released, and a row put below it goes just above it; a path other than a clip group's or clipping layer's clipping path also goes into a shown, unlocked compound path and gives up its own paint (the compound path becomes pixel-aligned when the path or the compound path it leaves was), and an empty compound path takes the paint the first path that goes in was drawn with; a path that leaves a compound path for a layer or a group takes its paint and pixel alignment; an Intertwine group takes and gives up members as layer.move does), deselecting every selected object left hidden or locked (the key object too); a Live Paint group or its paths take a row as layer.move does",
|
||||
"{id, parent?: id (null = top level), index} put a row at `index` (0 = bottom) of `parent` (layers only at the top level or in layers; the clipping path of a clip group or clipping layer stays at its bottom: it does not move until the mask is released, and a row put below it goes just above it; a path other than a clip group's or clipping layer's clipping path also goes into a shown, unlocked compound path whose layer and groups are shown and unlocked and that is not on a locked artboard (unless it is new art there that is still selected), and gives up its own paint (the compound path becomes pixel-aligned when the path or the compound path it leaves was), and an empty compound path takes the paint the first path that goes in was drawn with; a path that leaves a compound path for a layer or a group takes its paint and pixel alignment; an Intertwine group takes and gives up members as layer.move does), deselecting every selected object left hidden or locked (the key object too); a Live Paint group or its paths take a row as layer.move does",
|
||||
has_doc,
|
||||
move_node
|
||||
),
|
||||
@@ -1051,7 +1051,8 @@ fn move_node(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
// A path in a compound path keeps no paint, live shape or pixel alignment of its own, as
|
||||
// Make Compound Path leaves its paths; the compound path becomes pixel-aligned instead when
|
||||
// the path was, or when the compound path it leaves was.
|
||||
// the path was, or when the compound path it leaves was. A compound path that is
|
||||
// pixel-aligned snaps the path it takes in.
|
||||
if let Some(c) = into {
|
||||
let mut aligned = from_aligned;
|
||||
if let Some(m) = d.node_mut(id) {
|
||||
@@ -1061,9 +1062,12 @@ fn move_node(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
*live = None;
|
||||
}
|
||||
}
|
||||
if aligned && let Some(cn) = d.node_mut(c) {
|
||||
cn.extras_mut().pixel_aligned = true;
|
||||
super::object::snap_if_aligned(cn);
|
||||
if let Some(cn) = d.node_mut(c) {
|
||||
aligned |= cn.extras().pixel_aligned;
|
||||
if aligned {
|
||||
cn.extras_mut().pixel_aligned = true;
|
||||
super::object::snap_if_aligned(cn);
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some((appearance, aligned)) = out_of
|
||||
|
||||
@@ -44,7 +44,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"{on?: bool (default: toggle)} show non-printing red outlines and badges on missing linked images and placed documents in the active document; transient view state, no undo step; reads no files (the desktop app scans in the background, links.marked inspects now) → {on}",
|
||||
has_doc, show_missing_links),
|
||||
cmd!(query "links.marked", "Marked Missing Links", [], None,
|
||||
"{} inspect missing links now; only visible image objects and placed documents are marked, and none when the toggle is off → {on, images: [{id, bounds: [x0, y0, x1, y1]}]}",
|
||||
"{} inspect missing links now; only visible image objects and placed documents are marked, and none when the toggle is off; a caller whose read folders do not cover the same files as the document's, or a script command, gets its own answer and the canvas markers stay as they are → {on, images: [{id, bounds: [x0, y0, x1, y1]}]}",
|
||||
has_doc, marked),
|
||||
cmd!(
|
||||
query "links.check",
|
||||
@@ -2693,7 +2693,19 @@ fn marked(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
Some(json!({"id": id.0, "bounds": [b.x0, b.y0, b.x1, b.y1]}))
|
||||
})
|
||||
.collect();
|
||||
st.missing_link_markers = Some((st.doc.clone(), ids));
|
||||
// The canvas draws the markers the link watch finds with the read roots the document was
|
||||
// opened with ([`Session::start_link_scan`]). An answer found with other read roots stays the
|
||||
// caller's, as is one found by a script command, whose file-read gate the link watch does
|
||||
// not have.
|
||||
let same_roots = !crate::file_access::in_script_command()
|
||||
&& match (crate::file_access::current(), &st.opened_by) {
|
||||
(None, None) => true,
|
||||
(Some(a), Some(b)) => Arc::ptr_eq(&a, b) || a.same_reads(b),
|
||||
_ => false,
|
||||
};
|
||||
if same_roots {
|
||||
st.missing_link_markers = Some((st.doc.clone(), ids));
|
||||
}
|
||||
Ok(json!({"on": st.show_missing_links, "images": images}))
|
||||
}
|
||||
|
||||
|
||||
@@ -37,8 +37,8 @@ pub(crate) use bounds::{bounds_rewrite, object_bounds_transform, object_bounds_t
|
||||
pub use commands::specs;
|
||||
pub(super) use compound::{as_clipping_path, copy_transparency, make_clipping_path, release_clip};
|
||||
pub(crate) use pixelgrid::{
|
||||
align_new_object, aligned_symbol_transforms, can_align, keep_aligned_in, keep_aligned_in_with, keep_compound_aligned, keep_pixel_aligned,
|
||||
keep_symbol_instances_aligned, refresh as refresh_pixel_aligned, resnap, snap_if_aligned, snap_symbol_art,
|
||||
align_new_object, aligned_symbol_transforms, aligned_symbols, can_align, keep_aligned_in, keep_aligned_in_with, keep_compound_aligned,
|
||||
keep_pixel_aligned, keep_symbol_instances_aligned, refresh as refresh_pixel_aligned, resnap, snap_if_aligned, snap_symbol_art, snaps_after_edit,
|
||||
};
|
||||
pub(super) use shape::recut;
|
||||
pub(crate) use transform::{apply_transform, nudge_step, preview_copies, scaling, transform_node, transform_patterns, transforms_objects};
|
||||
|
||||
@@ -492,6 +492,18 @@ pub(crate) fn snap_if_aligned(n: &mut Node) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the pixel-grid snap after an edit ([`refresh`]) can move object `n`: `n` holds
|
||||
/// pixel-aligned art ([`holds_aligned`]) or an instance of a symbol in `symbols`, the document's
|
||||
/// pixel-aligned symbols ([`aligned_symbols`]).
|
||||
pub(crate) fn snaps_after_edit(n: &Node, symbols: &HashMap<String, Affine>) -> bool {
|
||||
holds_aligned(n) || !symbols.is_empty() && holds_instance(n, symbols)
|
||||
}
|
||||
|
||||
/// The pixel-aligned symbols of `d`, keyed by name, for [`snaps_after_edit`].
|
||||
pub(crate) fn aligned_symbols(d: &Document) -> HashMap<String, Affine> {
|
||||
d.pixel_aligned_symbols().into_iter().map(|name| (name, Affine::IDENTITY)).collect()
|
||||
}
|
||||
|
||||
/// Whether `n` or an object in it, or in the art of a linked opacity mask in it, is pixel-aligned.
|
||||
/// It goes only where a transform of `n` goes: not into unlinked masks.
|
||||
fn holds_aligned(n: &Node) -> bool {
|
||||
|
||||
@@ -102,7 +102,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
|
||||
/// The Objects on Path groups of `ids`: the ones among them, and the innermost one around each
|
||||
/// object in one.
|
||||
fn groups_of(d: &Document, ids: &[NodeId]) -> Vec<NodeId> {
|
||||
pub(crate) fn groups_of(d: &Document, ids: &[NodeId]) -> Vec<NodeId> {
|
||||
let mut out = vec![];
|
||||
for id in ids {
|
||||
let group = d.ancestry(*id).unwrap_or_default().into_iter().rev().find(|a| d.node(*a).is_some_and(is_objects_on_path));
|
||||
|
||||
@@ -10,7 +10,7 @@ use std::sync::Arc;
|
||||
|
||||
use vectorcraft_brush::{Brush, BrushKind};
|
||||
use vectorcraft_color::Paint;
|
||||
use vectorcraft_doc::{AppearanceItem, Document, Node, NodeKind, PatternDef, Symbol};
|
||||
use vectorcraft_doc::{AppearanceItem, CompositeFont, Document, Node, NodeKind, PatternDef, Symbol};
|
||||
|
||||
use super::super::Result;
|
||||
use super::super::clipboard::SymbolOptions;
|
||||
@@ -545,9 +545,8 @@ fn remap_composite_families(src: &Document, nodes: &mut [Node], used: &Used, bru
|
||||
|
||||
/// Discover the incoming resource frontier and its composite-font users before planning
|
||||
/// names or changing either document. Resource order and the no-composite fast path stay shared.
|
||||
fn collect_resources(src: &Document, nodes: &mut [Node]) -> (Used, Vec<Brush>, BTreeSet<String>) {
|
||||
fn collect_resources(src: &Document, nodes: &mut [Node], composites: bool) -> (Used, Vec<Brush>, BTreeSet<String>) {
|
||||
let mut used = Used::default();
|
||||
let composites = !src.composite_fonts.is_empty();
|
||||
let mut families = BTreeSet::new();
|
||||
let mut note_family = |name: &mut String| {
|
||||
families.insert(name.to_lowercase());
|
||||
@@ -596,10 +595,16 @@ fn collect_resources(src: &Document, nodes: &mut [Node]) -> (Used, Vec<Brush>, B
|
||||
/// Bring the resources `nodes` (art from `src`) use into `dst`, renaming on conflict, and point
|
||||
/// `nodes` at the names they got.
|
||||
pub(crate) fn adopt(dst: &mut Document, src: &Document, nodes: &mut [Node], cmd: &str) -> Result<()> {
|
||||
let (used, mut src_brushes, families) = collect_resources(src, nodes);
|
||||
let composites = !src.composite_fonts.is_empty() || !dst.composite_fonts.is_empty();
|
||||
let (used, mut src_brushes, families) = collect_resources(src, nodes, composites);
|
||||
let fonts = src.composite_fonts.iter().filter(|font| families.contains(&font.name.to_lowercase())).cloned().collect::<Vec<_>>();
|
||||
// A family the source does not define as a composite font, which the destination defines as
|
||||
// one, would draw in the destination's composite font after placement.
|
||||
let undefined_clash = families
|
||||
.iter()
|
||||
.any(|family| CompositeFont::named(&src.composite_fonts, family).is_none() && CompositeFont::named(&dst.composite_fonts, family).is_some());
|
||||
// All representability/validation errors precede incoming or destination mutation.
|
||||
let plan = if fonts.is_empty() { None } else { Some(plan_import(fonts, families, dst, cmd)?) };
|
||||
let plan = if fonts.is_empty() && !undefined_clash { None } else { Some(plan_import(fonts, families, dst, cmd)?) };
|
||||
let staged;
|
||||
let mut aliased = false;
|
||||
let src = if let Some(plan) = &plan {
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
|
||||
/// Commands a plug-in may call when its manifest lists them, in order.
|
||||
pub(super) const ALLOWED: &[&str] = &[
|
||||
"addon.arrange.artboardGuides",
|
||||
"addon.arrange.grid",
|
||||
"addon.arrange.groupOverlapping",
|
||||
"addon.arrange.groupRows",
|
||||
|
||||
@@ -402,6 +402,7 @@ pub const PREF_SPECS: &[PrefSpec] = &[
|
||||
p!("recentFilesCount", "File Handling", "Files", "Number of Recent Files to Display", int(0, 30)),
|
||||
p!("lowResProxyEps", "File Handling", "Files", "Use Low Resolution Proxy for Linked EPS", bool),
|
||||
p!("pdfImportEmbeddedFonts", "File Handling", "Files", "Use fonts embedded in imported PDFs", bool),
|
||||
p!("smoothBitmaps", "File Handling", "Files", "Display Bitmaps as Anti-aliased Images", bool),
|
||||
p!("antiAliasedBitmaps", "File Handling", "Files", "Display Bitmaps as Anti-aliased Images in Pixel Preview", bool),
|
||||
p!(
|
||||
"updateLinks",
|
||||
|
||||
@@ -4,8 +4,10 @@ use super::{NodeId, Value, cmd, find_command};
|
||||
/// Paste in Place, in Front and in Back paste onto it, Align to Artboard aligns to it, Distribute
|
||||
/// Objects and Distribute Spacing with Align to Artboard distribute objects across it, All on
|
||||
/// Active Artboard selects on it, and Edit Symbol from the Symbols panel centers the symbol's art
|
||||
/// on it. A `command.batch` given `artboard` passes it on to each of their steps that names none.
|
||||
pub const ON_ACTIVE_ARTBOARD: [&str; 10] = [
|
||||
/// on it, and Add Artboard Guides puts its guide around it. A `command.batch` given `artboard`
|
||||
/// passes it on to each of their steps that names none.
|
||||
pub const ON_ACTIVE_ARTBOARD: [&str; 11] = [
|
||||
"addon.arrange.artboardGuides",
|
||||
"edit.copy",
|
||||
"edit.cut",
|
||||
"edit.pasteInPlace",
|
||||
@@ -37,10 +39,11 @@ pub const DRAWS_SHAPE: [&str; 5] = ["shape.rectangle", "shape.ellipse", "shape.p
|
||||
/// Artboard tool had selected for its commands and for Paste in Place, in Front and in Back; the artboards and art Cut and Copy took with that
|
||||
/// tool chosen; the view's center the app passes to Edit Symbol); an action leaves them out
|
||||
/// ([`Session::journal_for_action`]).
|
||||
const REPLAY_ONLY: [(&str, &str); 38] = [
|
||||
const REPLAY_ONLY: [(&str, &str); 39] = [
|
||||
("edit.copy", "artboard"),
|
||||
("edit.cut", "artboard"),
|
||||
("file.new", "created"),
|
||||
("addon.arrange.artboardGuides", "artboard"),
|
||||
("edit.newDocumentFromState", "created"),
|
||||
("document.save", "modified"),
|
||||
("file.saveAs", "modified"),
|
||||
|
||||
@@ -163,6 +163,13 @@ impl AutomationRoots {
|
||||
within(&self.read, &other.read) && within(&self.write, &other.write)
|
||||
}
|
||||
|
||||
/// Whether these roots and `other` let the same files be read: each read root of either lies
|
||||
/// inside a read root of the other.
|
||||
pub(crate) fn same_reads(&self, other: &Self) -> bool {
|
||||
let within = |mine: &[Root], theirs: &[Root]| theirs.iter().all(|o| mine.iter().any(|r| inside(&o.resolved, &r.resolved)));
|
||||
within(&self.read, &other.read) && within(&other.read, &self.read)
|
||||
}
|
||||
|
||||
/// The roots for people: `read A, B; write C` (`none` for a kind without any).
|
||||
pub fn describe(&self) -> String {
|
||||
let list = |roots: &[Root]| {
|
||||
|
||||
@@ -458,6 +458,13 @@ pub struct Session {
|
||||
/// The pointer button is held: the last pointer event was a press or a drag, not a release or
|
||||
/// a move ([`Session::pointer_held`]).
|
||||
pub(crate) pointer_held: bool,
|
||||
/// While [`Session::pointer_samples`] feeds a pass's samples to the tool, the tool's previews are
|
||||
/// held in [`Self::sampled_preview`] instead of being applied.
|
||||
pub(crate) holds_previews: bool,
|
||||
/// The last preview the tool asked for during [`Session::pointer_samples`], not yet applied. It is
|
||||
/// applied before any other action of the tool, before a preview of another command, and when the
|
||||
/// samples end.
|
||||
pub(crate) sampled_preview: Option<(String, serde_json::Value)>,
|
||||
/// The id and persistent options of the tool when the press under way began, which a dropped
|
||||
/// press puts back ([`Session::drop_tool_press`]).
|
||||
pub(crate) press_options: Option<(String, serde_json::Map<String, serde_json::Value>)>,
|
||||
|
||||
@@ -306,7 +306,16 @@ pub struct Prefs {
|
||||
/// machine lacks is drawn in the file's own glyphs (on by default); off, it is set in the
|
||||
/// fallback font with the missing-font warning (#4568).
|
||||
pub pdf_import_embedded_fonts: bool,
|
||||
/// File Handling › Display Bitmaps as Anti-aliased Images in Pixel Preview: smooths images
|
||||
/// (except images marked pixelated, such as envelope images made with Anti-Alias off) while Pixel Preview draws its own pixel raster (the view zoomed above one screen pixel per
|
||||
/// document pixel and the region within the largest texture side); otherwise
|
||||
/// `smooth_bitmaps` applies, in Pixel Preview too.
|
||||
pub anti_aliased_bitmaps: bool,
|
||||
/// File Handling › Display Bitmaps as Anti-aliased Images: placed and embedded bitmaps drawn
|
||||
/// larger than their pixels are smoothed (on by default); off, each of their pixels shows as a
|
||||
/// hard-edged square (#10712). It applies whenever Pixel Preview does not draw its own pixel
|
||||
/// raster; while it does, `anti_aliased_bitmaps` applies.
|
||||
pub smooth_bitmaps: bool,
|
||||
pub update_links: String,
|
||||
/// PDF Text: what the text of a PDF, `.ai` or `.ait` file opened or placed from the app
|
||||
/// becomes when the open or place does not say (`text`: editable type in the file's fonts;
|
||||
@@ -698,6 +707,7 @@ impl Default for Prefs {
|
||||
low_res_proxy_eps: false,
|
||||
pdf_import_embedded_fonts: true,
|
||||
anti_aliased_bitmaps: false,
|
||||
smooth_bitmaps: true,
|
||||
update_links: s("askWhenModified"),
|
||||
pdf_text_as: s("text"),
|
||||
copy_as_svg: true,
|
||||
|
||||
+111
-56
@@ -38,7 +38,8 @@
|
||||
//! - After `documents[0]`, documents are listed from the one active most recently to the one
|
||||
//! active longest ago. A change a script makes to a document in the back does not move it.
|
||||
//! - `pageItems` lists every object, with the objects inside groups and compound paths after the
|
||||
//! group or compound path, and leaves out layers and ruler guides. An index out of range gives
|
||||
//! group or compound path, and leaves out layers and ruler guides. The `layers` module gives the
|
||||
//! order of a layer's, a group's and a compound path's lists. An index out of range gives
|
||||
//! `undefined`; `index` and `getByName` throw `Not found` when nothing matches.
|
||||
//! - Script coordinates are points with Y up from the bottom of the first artboard
|
||||
//! (`DOCUMENTCOORDINATESYSTEM`, the default) or points with Y down from the top-left corner of
|
||||
@@ -120,7 +121,9 @@ mod variables;
|
||||
|
||||
pub(super) use colors::of_color as color_data;
|
||||
#[cfg(test)]
|
||||
pub(crate) use paths::{PATH_LISTS, POINT_LOOKS};
|
||||
pub(crate) use paths::index_builds;
|
||||
#[cfg(test)]
|
||||
pub(crate) use paths::{PATH_LIST_BUILDS, POINT_LOOKS};
|
||||
|
||||
pub(super) use resources::{Kind as ResourceKind, gone as resources_gone, held as holds_resources};
|
||||
pub use variables::{MAX_HANDLES, STALE_DATASET, STALE_VARIABLE};
|
||||
@@ -160,6 +163,8 @@ pub const STALE_ITEM: &str = "Stale page item";
|
||||
const TRACING_NAME: &str = "The name of a tracing cannot be changed";
|
||||
/// The error for the tracing's name given to a group that holds an image first.
|
||||
const NOT_A_TRACING: &str = "Only Image Trace can make a tracing";
|
||||
/// The error of `move` and `remove()` for a tracing's source image.
|
||||
const SOURCE_STAYS: &str = "a tracing's source image cannot leave its tracing";
|
||||
/// The error for a document that was closed, or that came from an earlier run.
|
||||
pub const STALE_DOCUMENT: &str = "Stale document";
|
||||
/// The error of `index` and `getByName` when nothing matches.
|
||||
@@ -218,15 +223,20 @@ thread_local! {
|
||||
/// each kept while its document is unchanged, the lists of paths, the point changes of a path not
|
||||
/// written yet, how many times each path's points went stale and each path as the run last saw its
|
||||
/// points, the swatches, symbols, styles and brushes the run's objects name, whether a call's own
|
||||
/// savepoint ([`atomically`]) is open, the settings of each `DocumentPreset` the run made, with the
|
||||
/// size of the values they hold now and the most they may hold (the run's heap), the `Variable` and
|
||||
/// `Dataset` objects it gave out, and the tool `app.selectTool` chose last.
|
||||
/// savepoint ([`atomically`]) is open, the settings of each
|
||||
/// `DocumentPreset` the run made, with the size of the values they hold now and the most they may
|
||||
/// hold (the run's heap), the `Variable` and `Dataset` objects it gave out, the lists of art and
|
||||
/// layers its layers and groups gave, the active artboard of each document, and the tool
|
||||
/// `app.selectTool` chose last.
|
||||
#[derive(Default)]
|
||||
pub(super) struct State {
|
||||
coords: Cell<Coords>,
|
||||
items: RefCell<Vec<ItemList>>,
|
||||
/// The last list of each document's paths ([`paths`]), kept while that document is unchanged.
|
||||
paths: RefCell<Vec<ItemList>>,
|
||||
locked: RefCell<Vec<LockedList>>,
|
||||
/// The last [`paths::PATH_LISTS`] lists of paths a document's, a layer's or a group's
|
||||
/// `pathItems` gave ([`paths`]), least recently used first, each kept while its document is
|
||||
/// unchanged.
|
||||
paths: RefCell<Vec<paths::PathList>>,
|
||||
/// A path and its subpaths with the point changes the run has made to it and not written yet
|
||||
/// ([`flush`]).
|
||||
pending: RefCell<Option<(Item, Vec<vectorcraft_geom::path::SubPath>)>>,
|
||||
@@ -249,7 +259,6 @@ pub(super) struct State {
|
||||
/// The item the object model is changing ([`edit_item`]), whose points stay valid through the
|
||||
/// change.
|
||||
editing: Cell<Option<Item>>,
|
||||
locked: RefCell<Vec<LockedList>>,
|
||||
/// The resources the steps of kept commands removed or renamed, which the next lookup of a
|
||||
/// resource object or [`forget_removed`] marks stale, and how many names the last command's
|
||||
/// steps compared, which [`charge_scanned`] charges when the command ends.
|
||||
@@ -260,9 +269,9 @@ pub(super) struct State {
|
||||
/// The last [`layers::ART_LISTS`] lists of art [`layers`]' collections gave, least recently
|
||||
/// used first, each kept while its document is unchanged.
|
||||
art: RefCell<Vec<layers::ArtList>>,
|
||||
/// The last [`layers::ART_LISTS`] lists of layers `Layers` objects gave, least recently used
|
||||
/// first, each kept while its document is unchanged.
|
||||
layers: RefCell<Vec<layers::LayerList>>,
|
||||
/// The last [`layers::LAYER_LISTS`] lists of layers `layers` gave, least recently used first,
|
||||
/// each kept while its document is unchanged.
|
||||
layer_lists: RefCell<Vec<layers::LayerList>>,
|
||||
/// The uids of the documents whose active artboard `setActiveArtboardIndex` changed.
|
||||
pub(super) active_artboards: RefCell<Vec<u64>>,
|
||||
/// Each document's uid and revert generation when `setActiveArtboardIndex` last chose it.
|
||||
@@ -364,24 +373,6 @@ pub(super) fn forget_removed(h: &Host) -> std::result::Result<(), HostError> {
|
||||
/// A document's uid, the document as it was, and the ids of its page items then.
|
||||
type ItemList = (u64, Arc<Document>, Rc<Vec<NodeId>>);
|
||||
|
||||
/// The most documents whose lists [`State`] keeps at once, the least recently listed going first.
|
||||
const KEPT_LISTS: usize = 8;
|
||||
|
||||
/// The list kept in `lists` for the document `st`, while that document is unchanged.
|
||||
fn kept_list(lists: &RefCell<Vec<ItemList>>, st: &DocState) -> Option<Rc<Vec<NodeId>>> {
|
||||
lists.borrow().iter().find(|(uid, doc, _)| *uid == st.uid && Arc::ptr_eq(doc, &st.doc)).map(|(_, _, ids)| ids.clone())
|
||||
}
|
||||
|
||||
/// Keeps `ids` in `lists` as the list of the document `st`, in place of the one it had.
|
||||
fn keep_list(lists: &RefCell<Vec<ItemList>>, st: &DocState, ids: &Rc<Vec<NodeId>>) {
|
||||
let mut l = lists.borrow_mut();
|
||||
l.retain(|(uid, ..)| *uid != st.uid);
|
||||
if l.len() >= KEPT_LISTS {
|
||||
l.remove(0);
|
||||
}
|
||||
l.push((st.uid, st.doc.clone(), ids.clone()));
|
||||
}
|
||||
|
||||
/// A document's uid, the document and its new art ([`Document::new_art`]) as they were, and for
|
||||
/// each object of a layer or sublayer asked about then, whether it was on a locked artboard.
|
||||
type LockedList = (u64, Arc<Document>, Arc<HashSet<NodeId>>, HashMap<NodeId, bool>);
|
||||
@@ -663,6 +654,15 @@ fn node_handle(h: &Host, st: &DocState, id: NodeId) -> [f64; 5] {
|
||||
[float(h.run), float(st.uid), high, low, float(st.reverts)]
|
||||
}
|
||||
|
||||
/// The handle of a collection that lists the art of the layer, group or compound path `id` in the
|
||||
/// document `uid`, with the document's revert count as [`node_handle`] gives it, so that a
|
||||
/// collection read before File > Revert is stale.
|
||||
fn scoped_handle(h: &Host, uid: u64, id: NodeId) -> [f64; 5] {
|
||||
let [high, low] = id_parts(id);
|
||||
let reverts = h.session.borrow().documents().iter().find(|d| d.uid == uid).map_or(0, |d| d.reverts);
|
||||
[float(h.run), float(uid), high, low, float(reverts)]
|
||||
}
|
||||
|
||||
fn node_of(h: &Host, handle: &[f64]) -> Option<(Doc, NodeId)> {
|
||||
let &[run, uid, high, low, reverts] = handle else { return None };
|
||||
let doc = find_doc(h, run, uid)?;
|
||||
@@ -731,7 +731,7 @@ fn item_ref(h: &Host, st: &DocState, id: NodeId) -> Data {
|
||||
host_ref("PluginItem", &node_handle(h, st, tracing::origin(h, st.uid, id)))
|
||||
}
|
||||
Some(t) => host_ref(t, &node_handle(h, st, id)),
|
||||
None => host_ref("Layer", &node_handle(h, st, id)),
|
||||
None => layers::layer_ref(h, st.uid, id),
|
||||
},
|
||||
None => Data::Null,
|
||||
}
|
||||
@@ -906,7 +906,9 @@ fn restore_selection(h: &Host, doc: &Document, before: &crate::doc::Selection) -
|
||||
command(h, "select.set", &json!({"ids": kept.iter().map(|i| i.0).collect::<Vec<_>>()}))?;
|
||||
} else {
|
||||
// One `select.anchorsMany` selects every object in its order: a partly selected path with
|
||||
// its anchors, a whole path with all of them and any other object with none.
|
||||
// its anchors, a whole path with all of them and any other object with none. A path with
|
||||
// only segments selected gets no anchors here, so `select.segments` below selects it with
|
||||
// just those segments.
|
||||
let items: Vec<Value> = kept
|
||||
.iter()
|
||||
.map(|i| {
|
||||
@@ -1227,8 +1229,14 @@ fn app_show_color_picker(h: &Host, a: &[Data]) -> Answer {
|
||||
/// with a drive letter) takes `\` and `/` alike and letters in one case. On other systems `\` is a
|
||||
/// character of a file name, so `/work/a\b.ai` and `/work/a/b.ai` are different files.
|
||||
fn path_key(p: &str) -> String {
|
||||
path_key_on(p, cfg!(windows))
|
||||
}
|
||||
|
||||
/// [`path_key`] treating every path as a Windows path when `windows`, else only one that starts
|
||||
/// with a drive letter.
|
||||
pub(crate) fn path_key_on(p: &str, windows: bool) -> String {
|
||||
let b = p.as_bytes();
|
||||
let windows = cfg!(windows) || (b.len() >= 2 && b[0].is_ascii_alphabetic() && b[1] == b':');
|
||||
let windows = windows || (b.len() >= 2 && b[0].is_ascii_alphabetic() && b[1] == b':');
|
||||
if windows { p.replace('\\', "/").trim_end_matches('/').to_lowercase() } else { p.trim_end_matches('/').to_string() }
|
||||
}
|
||||
|
||||
@@ -1682,9 +1690,17 @@ fn docs_add_document(h: &Host, a: &[Data]) -> Answer {
|
||||
// Letter) with `presetSettings` over it, given in full so that a saved preset of the same name
|
||||
// does not stand in for it. Settings the built-in preset refuses are an error.
|
||||
let first = profile.and_then(|n| crate::cmd::newdoc::category(&h.session.borrow(), n)?.into_iter().next());
|
||||
let mut shadowed_by = None;
|
||||
if let Some(first) = first {
|
||||
p.insert("preset".into(), json!(first.name));
|
||||
let full = first.with_params(&Value::Object(p.clone()), "file.new").map_err(|e| HostError::Error(e.to_string()))?;
|
||||
let full = first.clone().with_params(&Value::Object(p.clone()), "file.new").map_err(|e| HostError::Error(e.to_string()))?;
|
||||
let shadowed = h.session.borrow().prefs.new_doc_presets.iter().any(|q| q.name.trim().eq_ignore_ascii_case(first.name.trim()));
|
||||
if shadowed {
|
||||
// `file.new` would find the saved preset of that name first, so the name is left out
|
||||
// and the built-in preset's settings, with `presetSettings` over them, go as params.
|
||||
shadowed_by = Some(first.clone());
|
||||
} else {
|
||||
p.insert("preset".into(), json!(first.name));
|
||||
}
|
||||
if let Value::Object(settings) = full.to_json() {
|
||||
for key in BUILT_IN_SETTINGS {
|
||||
if let Some(v) = settings.get(*key) {
|
||||
@@ -1703,6 +1719,15 @@ fn docs_add_document(h: &Host, a: &[Data]) -> Answer {
|
||||
let reason = e["reason"].as_str().unwrap_or_default();
|
||||
return Err(HostError::Error(format!("the New Document profile {profile} could not be read: {reason}")));
|
||||
}
|
||||
// The built-in preset's settings went as params: Recent keeps its name, as `file.new`
|
||||
// keeps a preset's name, unless its size changed (turning it doesn't count).
|
||||
if let Some(first) = &shadowed_by {
|
||||
let sorted = |d: &crate::cmd::newdoc::DocSettings| (d.width.min(d.height), d.width.max(d.height), d.units);
|
||||
let mut s = h.session.borrow_mut();
|
||||
if let Some(r) = s.prefs.recent_new_docs.first_mut().filter(|r| sorted(r) == sorted(first)) {
|
||||
r.name.clone_from(&first.name);
|
||||
}
|
||||
}
|
||||
// Each warning from reading the profile's file goes to the console.
|
||||
for w in value.get("warnings").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str) {
|
||||
super::each_line(&format!("addDocument: {w}"), |line, cut| h.line(super::console::Entry::Log(line), cut));
|
||||
@@ -2290,7 +2315,7 @@ fn items_doc(h: &Host, a: &[Data]) -> std::result::Result<Doc, HostError> {
|
||||
}
|
||||
|
||||
fn items_length(h: &Host, a: &[Data]) -> Answer {
|
||||
if layers::is_scoped(a, "PageItems") {
|
||||
if layers::is_scoped(a) {
|
||||
return layers::scoped_length(h, a);
|
||||
}
|
||||
let doc = items_doc(h, a)?;
|
||||
@@ -2299,7 +2324,7 @@ fn items_length(h: &Host, a: &[Data]) -> Answer {
|
||||
}
|
||||
|
||||
fn items_typename(h: &Host, a: &[Data]) -> Answer {
|
||||
if layers::is_scoped(a, "PageItems") {
|
||||
if layers::is_scoped(a) {
|
||||
return layers::scoped_typename(h, a);
|
||||
}
|
||||
items_doc(h, a)?;
|
||||
@@ -2307,7 +2332,7 @@ fn items_typename(h: &Host, a: &[Data]) -> Answer {
|
||||
}
|
||||
|
||||
fn items_to_string(h: &Host, a: &[Data]) -> Answer {
|
||||
if layers::is_scoped(a, "PageItems") {
|
||||
if layers::is_scoped(a) {
|
||||
layers::scoped_typename(h, a)?;
|
||||
return Ok(text("[PageItems]"));
|
||||
}
|
||||
@@ -2316,7 +2341,7 @@ fn items_to_string(h: &Host, a: &[Data]) -> Answer {
|
||||
}
|
||||
|
||||
fn items_parent(h: &Host, a: &[Data]) -> Answer {
|
||||
if layers::is_scoped(a, "PageItems") {
|
||||
if layers::is_scoped(a) {
|
||||
return layers::scoped_parent(h, a);
|
||||
}
|
||||
let doc = items_doc(h, a)?;
|
||||
@@ -2329,30 +2354,55 @@ fn probing(a: &[Data]) -> bool {
|
||||
matches!(arg(a, 2), Data::Bool(true))
|
||||
}
|
||||
|
||||
/// The answer of an indexer called with a name, from `found`, the collection's `getByName`: a
|
||||
/// name nothing has gives `undefined` for `name in collection` ([`probing`]) and throws otherwise.
|
||||
fn by_name_or_probe(a: &[Data], found: Answer) -> Answer {
|
||||
match found {
|
||||
Err(HostError::Error(e)) if e == NOT_FOUND && probing(a) => Ok(Data::Undefined),
|
||||
r => r,
|
||||
}
|
||||
}
|
||||
|
||||
/// The position an indexer key names when it is an array index, 0 to 2^32 - 2.
|
||||
fn position(n: f64) -> Option<usize> {
|
||||
whole(n).filter(|i| *i < u64::from(u32::MAX)).and_then(|i| usize::try_from(i).ok())
|
||||
}
|
||||
|
||||
/// The arguments of an indexer called with a number that is not an array index, such as `-1` or
|
||||
/// `1.5`, with that key given as the text of the number, the name it is looked up by: a key such
|
||||
/// as `"-1"` reaches an indexer as a number.
|
||||
fn number_named(a: &[Data]) -> Option<Vec<Data>> {
|
||||
let Data::Number(n) = arg(a, 1) else { return None };
|
||||
if position(*n).is_some() {
|
||||
return None;
|
||||
}
|
||||
let mut named = a.to_vec();
|
||||
named[1] = text(vectorcraft_js::number_to_string(*n));
|
||||
Some(named)
|
||||
}
|
||||
|
||||
/// The answer of an indexer for a number key looked up as a name ([`number_named`]), from `found`,
|
||||
/// the collection's `getByName`: `undefined` when nothing has the name.
|
||||
fn named_or_undefined(found: Answer) -> Answer {
|
||||
match found {
|
||||
Err(HostError::Error(e)) if e == NOT_FOUND => Ok(Data::Undefined),
|
||||
r => r,
|
||||
}
|
||||
}
|
||||
|
||||
/// `pageItems[i]`, and `pageItems["name"]` as `getByName` reads it. A key that is the text of a
|
||||
/// number but not an array index, such as `-1` or `1.5`, reaches the indexer as a number and is
|
||||
/// looked up as that name, giving `undefined` when no object has it.
|
||||
fn items_at(h: &Host, a: &[Data]) -> Answer {
|
||||
if layers::is_scoped(a, "PageItems") {
|
||||
if layers::is_scoped(a) {
|
||||
return layers::scoped_at(h, a);
|
||||
}
|
||||
let doc = items_doc(h, a)?;
|
||||
match arg(a, 1) {
|
||||
Data::String(_) => match items_by_name(h, a) {
|
||||
Err(HostError::Error(e)) if e == NOT_FOUND && probing(a) => Ok(Data::Undefined),
|
||||
r => r,
|
||||
},
|
||||
Data::String(_) => by_name_or_probe(a, items_by_name(h, a)),
|
||||
Data::Number(n) => match position(*n) {
|
||||
Some(i) => item_at(h, doc, i),
|
||||
None => match items_named(h, doc, &vectorcraft_js::number_to_string(*n)) {
|
||||
Err(HostError::Error(e)) if e == NOT_FOUND => Ok(Data::Undefined),
|
||||
r => r,
|
||||
},
|
||||
None => named_or_undefined(items_named(h, doc, &vectorcraft_js::number_to_string(*n))),
|
||||
},
|
||||
_ => Ok(Data::Undefined),
|
||||
}
|
||||
@@ -2364,7 +2414,7 @@ fn item_at(h: &Host, doc: Doc, i: usize) -> Answer {
|
||||
}
|
||||
|
||||
fn items_by_name(h: &Host, a: &[Data]) -> Answer {
|
||||
if layers::is_scoped(a, "PageItems") {
|
||||
if layers::is_scoped(a) {
|
||||
return layers::scoped_by_name(h, a);
|
||||
}
|
||||
let doc = items_doc(h, a)?;
|
||||
@@ -2383,7 +2433,7 @@ fn items_named(h: &Host, doc: Doc, name: &str) -> Answer {
|
||||
}
|
||||
|
||||
fn items_index(h: &Host, a: &[Data]) -> Answer {
|
||||
if layers::is_scoped(a, "PageItems") {
|
||||
if layers::is_scoped(a) {
|
||||
return layers::scoped_index(h, a);
|
||||
}
|
||||
match arg(a, 1) {
|
||||
@@ -2403,7 +2453,7 @@ fn items_index(h: &Host, a: &[Data]) -> Answer {
|
||||
/// locked object, or one in a hidden or locked layer or group, stops it before anything is deleted,
|
||||
/// and so does an object on a locked artboard.
|
||||
fn items_remove_all(h: &Host, a: &[Data]) -> Answer {
|
||||
if layers::is_scoped(a, "PageItems") {
|
||||
if layers::is_scoped(a) {
|
||||
return layers::scoped_remove_all(h, a);
|
||||
}
|
||||
let doc = items_doc(h, a)?;
|
||||
@@ -2735,8 +2785,8 @@ fn item_control(h: &Host, a: &[Data]) -> Answer {
|
||||
|
||||
/// `r` with the anchors and direction handles of the shown paths in `n`, adding the objects and
|
||||
/// anchors it visits to `steps`. Hidden objects, the objects in them and guides are left out, as
|
||||
/// the visible bounds leave them out, and a clip group or clipping layer gives only its clipping
|
||||
/// path's.
|
||||
/// the visible bounds leave them out, a clip group or clipping layer gives only its clipping
|
||||
/// path's, and the source art a Shaper Group or a tracing keeps is left out.
|
||||
fn take_in_handles(n: &crate::doc::Node, mut r: Rect, steps: &mut u64) -> Rect {
|
||||
*steps += 1;
|
||||
if !n.visible || matches!(n.kind, NodeKind::Path { guide: true, .. }) {
|
||||
@@ -2746,7 +2796,7 @@ fn take_in_handles(n: &crate::doc::Node, mut r: Rect, steps: &mut u64) -> Rect {
|
||||
*steps += 1;
|
||||
r = r.union_pt(a.p).union_pt(a.h_in).union_pt(a.h_out);
|
||||
}
|
||||
let children = n.children().map_or(&[][..], Vec::as_slice);
|
||||
let children = n.editing_children();
|
||||
let children = if n.clips() { &children[..children.len().min(1)] } else { children };
|
||||
for c in children {
|
||||
r = take_in_handles(c, r, steps);
|
||||
@@ -2908,7 +2958,8 @@ fn item_z_order_position(h: &Host, a: &[Data]) -> Answer {
|
||||
|
||||
/// `remove()`: deletes the object. A hidden or locked object, one in a hidden or locked layer or
|
||||
/// group, a group holding one, or an object on a locked artboard is refused, as [`items_remove_all`]
|
||||
/// refuses it. A compound path whose last path this is stays, empty.
|
||||
/// refuses it. A tracing's source image is refused when it is shown as well. A compound path whose
|
||||
/// last path this is stays, empty.
|
||||
fn item_remove(h: &Host, a: &[Data]) -> Answer {
|
||||
let item = this_item(h, a)?;
|
||||
let (whole, on_locked) = with_doc(h, item.doc, |_, st| {
|
||||
@@ -2920,6 +2971,10 @@ fn item_remove(h: &Host, a: &[Data]) -> Answer {
|
||||
if on_locked {
|
||||
return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {}", item.id.0)));
|
||||
}
|
||||
// A tracing keeps its source image when a script has shown it, as `move` keeps it there.
|
||||
if with_doc(h, item.doc, |_, st| crate::cmd::is_trace_source(&st.doc, item.id)) {
|
||||
return Err(HostError::Error(SOURCE_STAYS.into()));
|
||||
}
|
||||
// An image left first in an ordinary group named as a tracing would make that group one.
|
||||
if with_doc(h, item.doc, |_, st| st.doc.parent_of(item.id).is_some_and(|p| makes_tracing(&st.doc, p, item.id, None))) {
|
||||
return Err(HostError::Error(NOT_A_TRACING.into()));
|
||||
@@ -3146,7 +3201,7 @@ fn place(h: &Host, doc: Doc, id: NodeId, to: &Destination) -> std::result::Resul
|
||||
if d.parent_of(id) == Some(to.parent) {
|
||||
return Ok(0);
|
||||
}
|
||||
return Err(HostError::Error("a tracing's source image cannot leave its tracing".into()));
|
||||
return Err(HostError::Error(SOURCE_STAYS.into()));
|
||||
}
|
||||
let clips = d.node(to.parent).is_some_and(|n| n.clips() || crate::cmd::is_trace_group(n)) && count > 0;
|
||||
// The clipping path itself, put back where it is, stays the clipping path.
|
||||
@@ -3349,7 +3404,7 @@ fn doc_to_string(h: &Host, a: &[Data]) -> Answer {
|
||||
}
|
||||
|
||||
/// `toString()` of an object without a name: `[Class]`.
|
||||
fn class_text(name: &'static str) -> HostMember {
|
||||
pub(super) fn class_text(name: &'static str) -> HostMember {
|
||||
HostMember::Method(Rc::new(move |_| Ok(text(format!("[{name}]")))))
|
||||
}
|
||||
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
//!
|
||||
//! VectorCraft's own rules, which the help pages do not state:
|
||||
//! - `layers` lists layers top first, as the Layers panel shows them. A layer's or group's
|
||||
//! `pageItems`, `groupItems`, `compoundPathItems` and `textFrames`, and a compound path's
|
||||
//! `pageItems`, `groupItems`, `compoundPathItems`, `pathItems` and `textFrames`, and a compound path's
|
||||
//! `pathItems`, list the objects directly in it, topmost first. The document's `groupItems` and `compoundPathItems`
|
||||
//! hold every group or compound path at any depth, in the order of the document's `pageItems`.
|
||||
//! - `layers.add()` on the document makes a layer above every top-level layer; on a layer it makes
|
||||
@@ -41,9 +41,9 @@ use vectorcraft_js::{Data, HostClass, HostError, MemberInfo, host_ref, host_ref_
|
||||
|
||||
use super::{
|
||||
Answer, Described, Doc, Item, MAX_LISTED, MAX_TEXT_BYTES, NOT_FOUND, ON_LOCKED_ARTBOARD, Placement, STALE_DOCUMENT, STALE_ITEM, active_artboard,
|
||||
arg, boolean, command, command_value, doc_of, doc_ref, editable, find_doc, float, frame, get, handle_of, id_of, id_parts, item_of, item_ref,
|
||||
later, method, named, named_text, node_of, num, number, on_doc, on_doc_layer, page_items, placement_of, probing, property, reported_opacity,
|
||||
returns, text, typed, typename, whole, with_doc,
|
||||
arg, boolean, command, command_value, doc_of, doc_ref, editable, find_doc, float, frame, get, handle_of, id_of, item_of, item_ref, later, method,
|
||||
named, named_text, num, number, on_doc, on_doc_layer, page_items, placement_of, property, reported_opacity, returns, text, typed, typename,
|
||||
whole, with_doc,
|
||||
};
|
||||
use crate::script::{Host, Link};
|
||||
use crate::{DocState, Document, NodeId, NodeKind};
|
||||
@@ -66,8 +66,6 @@ enum Kind {
|
||||
Group,
|
||||
/// Compound paths (`CompoundPathItem`).
|
||||
Compound,
|
||||
/// Paths (`PathItem`).
|
||||
Path,
|
||||
/// Type (`TextFrame`), whose collection's other members are in `text.rs`.
|
||||
Text,
|
||||
}
|
||||
@@ -78,7 +76,6 @@ impl Kind {
|
||||
Kind::Any => "PageItems",
|
||||
Kind::Group => "GroupItems",
|
||||
Kind::Compound => "CompoundPathItems",
|
||||
Kind::Path => "PathItems",
|
||||
Kind::Text => "TextFrames",
|
||||
}
|
||||
}
|
||||
@@ -88,7 +85,6 @@ impl Kind {
|
||||
Kind::Any => typename(n).is_some(),
|
||||
Kind::Group => typename(n) == Some("GroupItem"),
|
||||
Kind::Compound => typename(n) == Some("CompoundPathItem"),
|
||||
Kind::Path => typename(n) == Some("PathItem"),
|
||||
Kind::Text => typename(n) == Some("TextFrame"),
|
||||
}
|
||||
}
|
||||
@@ -109,14 +105,16 @@ fn result_id(v: &Value, key: &str) -> Option<u64> {
|
||||
/// The layer `d` names, which must still be a layer of its document.
|
||||
pub(super) fn layer_of(h: &Host, d: &Data) -> Result<(Doc, NodeId)> {
|
||||
let Some(handle) = handle_of(d, "Layer") else { return Err(type_error("Layer")) };
|
||||
if handle.len() != 5 {
|
||||
return Err(type_error("Layer"));
|
||||
}
|
||||
// A layer read before File › Revert is stale like the page items read with it.
|
||||
let (doc, id) = node_of(h, &handle).ok_or_else(|| {
|
||||
let reverted = matches!(handle.as_slice(), [run, uid, ..] if find_doc(h, *run, *uid).is_some());
|
||||
HostError::Error(if reverted { STALE_ITEM } else { STALE_LAYER }.into())
|
||||
})?;
|
||||
let [run, uid, high, low, _] = handle.as_slice() else { return Err(type_error("Layer")) };
|
||||
let doc = find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_LAYER.into()))?;
|
||||
id_of(*high, *low).ok_or_else(|| HostError::Error(STALE_LAYER.into()))?;
|
||||
// A layer read before its document was reverted is stale as the page items read then are.
|
||||
let (doc, id) = super::node_of(h, &handle).filter(|(d, _)| d.uid == doc.uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?;
|
||||
held_layer(h, doc, id)
|
||||
}
|
||||
|
||||
/// The layer `id` of `doc`, which must still be a layer of the document.
|
||||
fn held_layer(h: &Host, doc: Doc, id: NodeId) -> Result<(Doc, NodeId)> {
|
||||
let ok = with_doc(h, doc, |_, st| st.doc.node(id).is_some_and(crate::doc::Node::is_layer));
|
||||
if !ok {
|
||||
return Err(HostError::Error(STALE_LAYER.into()));
|
||||
@@ -128,14 +126,12 @@ fn this_layer(h: &Host, a: &[Data]) -> Result<(Doc, NodeId)> {
|
||||
layer_of(h, arg(a, 0))
|
||||
}
|
||||
|
||||
fn layer_ref(h: &Host, uid: u64, id: NodeId) -> Data {
|
||||
host_ref("Layer", &layer_handle(h, uid, id))
|
||||
}
|
||||
|
||||
/// The handle of layer `id` of the document with uid `uid`, as `item_ref` gives it.
|
||||
fn layer_handle(h: &Host, uid: u64, id: NodeId) -> [f64; 5] {
|
||||
let [high, low] = id_parts(id);
|
||||
[float(h.run), float(uid), high, low, float(reverts_of(h, uid))]
|
||||
pub(super) fn layer_ref(h: &Host, uid: u64, id: NodeId) -> Data {
|
||||
let s = h.session.borrow();
|
||||
match s.documents().iter().find(|d| d.uid == uid) {
|
||||
Some(st) => host_ref("Layer", &super::node_handle(h, st, id)),
|
||||
None => Data::Null,
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads the layer `this` names with `f`.
|
||||
@@ -285,22 +281,23 @@ fn layer_parent(h: &Host, a: &[Data]) -> Answer {
|
||||
}))
|
||||
}
|
||||
|
||||
fn layer_to_string(h: &Host, a: &[Data]) -> Answer {
|
||||
named_text("Layer", layer_name(h, a))
|
||||
}
|
||||
|
||||
fn layer_typename(h: &Host, a: &[Data]) -> Answer {
|
||||
this_layer(h, a)?;
|
||||
Ok(text("Layer"))
|
||||
}
|
||||
|
||||
fn layer_to_string(h: &Host, a: &[Data]) -> Answer {
|
||||
named_text("Layer", layer_name(h, a))
|
||||
}
|
||||
|
||||
/// The layer's place among the layers beside it, from 1 at the bottom. Art beside a sublayer is
|
||||
/// not counted. The list comes from [`layers_listed`], so reading it for each layer of a loop
|
||||
/// not counted. The list comes from [`layer_ids`], so reading it for each layer of a loop
|
||||
/// lists the layers once. Each read is still charged for the search through the list.
|
||||
fn layer_z_position(h: &Host, a: &[Data]) -> Answer {
|
||||
let (doc, id) = this_layer(h, a)?;
|
||||
let at = with_doc(h, doc, |_, st| {
|
||||
let list = layers_listed(h, st, st.doc.parent_of(id))?;
|
||||
let list = layer_ids(h, st, st.doc.parent_of(id))?;
|
||||
// The scan is charged by itself: a list kept from an earlier read was charged once.
|
||||
h.charge_call(list.len() as u64)?;
|
||||
Ok::<_, HostError>(list.iter().position(|l| *l == id).map(|i| list.len() - i))
|
||||
})?;
|
||||
@@ -535,8 +532,9 @@ fn layers_scope(h: &Host, d: &Data) -> Result<(Doc, Option<NodeId>)> {
|
||||
let Some(handle) = handle_of(d, "Layers") else { return Err(type_error("Layers")) };
|
||||
match handle.as_slice() {
|
||||
[run, uid] => Ok((find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?, None)),
|
||||
[run, uid, high, low, reverts] => {
|
||||
let (doc, id) = layer_of(h, &host_ref("Layer", &[*run, *uid, *high, *low, *reverts]))?;
|
||||
[_, _, _, _, _] => {
|
||||
// A collection read before its document was reverted is stale, as its layer is.
|
||||
let (doc, id) = layer_of(h, &host_ref("Layer", &handle))?;
|
||||
Ok((doc, Some(id)))
|
||||
}
|
||||
_ => Err(type_error("Layers")),
|
||||
@@ -554,33 +552,33 @@ fn layer_list(d: &Document, parent: Option<NodeId>) -> Vec<NodeId> {
|
||||
list.into_iter().flatten().rev().filter(|n| n.is_layer()).map(|n| n.id).collect()
|
||||
}
|
||||
|
||||
/// A document's uid, the document as it was, the parent a `Layers` object lists (`None`: the top
|
||||
/// level) and the layers it listed then.
|
||||
/// A document's uid, the document as it was, a parent layer (`None`: the top level) and its layers.
|
||||
pub(super) type LayerList = (u64, Arc<Document>, Option<NodeId>, Rc<Vec<NodeId>>);
|
||||
|
||||
/// The layers of `parent` as [`layer_list`] gives them. The last [`ART_LISTS`] lists are kept while
|
||||
/// their documents are unchanged, so a loop over `layers[i]` lists the layers once. Each new list
|
||||
/// is charged by the objects it looks at.
|
||||
fn layers_listed(h: &Host, st: &DocState, parent: Option<NodeId>) -> Result<Rc<Vec<NodeId>>> {
|
||||
/// How many lists of layers [`super::State`] keeps at once.
|
||||
pub(super) const LAYER_LISTS: usize = 4;
|
||||
|
||||
/// [`layer_list`], kept while the document is unchanged for the last [`LAYER_LISTS`] parents, so a
|
||||
/// loop over `layers` builds the list once. Each new list is charged by the objects it looks at.
|
||||
fn layer_ids(h: &Host, st: &DocState, parent: Option<NodeId>) -> Result<Rc<Vec<NodeId>>> {
|
||||
{
|
||||
let mut lists = h.dom.layers.borrow_mut();
|
||||
let at = lists.iter().position(|(uid, doc, p, _)| *uid == st.uid && Arc::ptr_eq(doc, &st.doc) && *p == parent);
|
||||
if let Some(at) = at {
|
||||
let mut lists = h.dom.layer_lists.borrow_mut();
|
||||
if let Some(at) = lists.iter().position(|(uid, doc, p, _)| *uid == st.uid && Arc::ptr_eq(doc, &st.doc) && *p == parent) {
|
||||
let list = lists.remove(at);
|
||||
let ids = list.3.clone();
|
||||
lists.push(list);
|
||||
return Ok(ids);
|
||||
}
|
||||
}
|
||||
let looked_at = match parent {
|
||||
let looked = match parent {
|
||||
None => st.doc.layers.len(),
|
||||
Some(p) => st.doc.children(Some(p)).map_or(0, Vec::len),
|
||||
};
|
||||
h.charge_call(looked_at as u64)?;
|
||||
h.charge_call(looked as u64)?;
|
||||
let ids = Rc::new(layer_list(&st.doc, parent));
|
||||
let mut lists = h.dom.layers.borrow_mut();
|
||||
let mut lists = h.dom.layer_lists.borrow_mut();
|
||||
lists.retain(|(uid, doc, ..)| *uid != st.uid || Arc::ptr_eq(doc, &st.doc));
|
||||
if lists.len() >= ART_LISTS {
|
||||
if lists.len() >= LAYER_LISTS {
|
||||
lists.remove(0);
|
||||
}
|
||||
lists.push((st.uid, st.doc.clone(), parent, ids.clone()));
|
||||
@@ -589,12 +587,12 @@ fn layers_listed(h: &Host, st: &DocState, parent: Option<NodeId>) -> Result<Rc<V
|
||||
|
||||
fn layers_of(h: &Host, a: &[Data]) -> Answer {
|
||||
let (doc, id) = this_layer(h, a)?;
|
||||
Ok(host_ref("Layers", &layer_handle(h, doc.uid, id)))
|
||||
Ok(host_ref("Layers", &super::scoped_handle(h, doc.uid, id)))
|
||||
}
|
||||
|
||||
fn layers_length(h: &Host, a: &[Data]) -> Answer {
|
||||
let (doc, parent) = layers_scope(h, arg(a, 0))?;
|
||||
Ok(num(float(with_doc(h, doc, |_, st| layers_listed(h, st, parent).map(|l| l.len()))? as u64)))
|
||||
Ok(num(float(with_doc(h, doc, |_, st| layer_ids(h, st, parent).map(|l| l.len()))? as u64)))
|
||||
}
|
||||
|
||||
fn layers_parent(h: &Host, a: &[Data]) -> Answer {
|
||||
@@ -607,30 +605,26 @@ fn layers_typename(h: &Host, a: &[Data]) -> Answer {
|
||||
Ok(text("Layers"))
|
||||
}
|
||||
|
||||
/// `collection["name"]` as `getByName` reads it, or `undefined` for `"name" in collection` when
|
||||
/// nothing has the name, as the document's `pageItems` does.
|
||||
fn read_by_name(h: &Host, a: &[Data], by_name: fn(&Host, &[Data]) -> Answer) -> Answer {
|
||||
match by_name(h, a) {
|
||||
Err(HostError::Error(e)) if e == NOT_FOUND && probing(a) => Ok(Data::Undefined),
|
||||
r => r,
|
||||
}
|
||||
}
|
||||
|
||||
/// `layers[i]`, and `layers["name"]` as `getByName` reads it. A number key that is not an array
|
||||
/// index, such as `-1`, is looked up as a name, as `pageItems` looks it up.
|
||||
fn layers_at(h: &Host, a: &[Data]) -> Answer {
|
||||
let (doc, parent) = layers_scope(h, arg(a, 0))?;
|
||||
if let Data::String(_) = arg(a, 1) {
|
||||
return read_by_name(h, a, layers_by_name);
|
||||
return super::by_name_or_probe(a, layers_by_name(h, a));
|
||||
}
|
||||
if let Some(named) = super::number_named(a) {
|
||||
return super::named_or_undefined(layers_by_name(h, &named));
|
||||
}
|
||||
let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) };
|
||||
let Some(i) = whole(*n).and_then(|i| usize::try_from(i).ok()) else { return Ok(Data::Undefined) };
|
||||
with_doc(h, doc, |_, st| Ok(layers_listed(h, st, parent)?.get(i).map_or(Data::Undefined, |id| layer_ref(h, st.uid, *id))))
|
||||
let Some(i) = super::position(*n) else { return Ok(Data::Undefined) };
|
||||
with_doc(h, doc, |_, st| Ok(layer_ids(h, st, parent)?.get(i).map_or(Data::Undefined, |id| layer_ref(h, st.uid, *id))))
|
||||
}
|
||||
|
||||
fn layers_by_name(h: &Host, a: &[Data]) -> Answer {
|
||||
let (doc, parent) = layers_scope(h, arg(a, 0))?;
|
||||
let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) };
|
||||
with_doc(h, doc, |_, st| {
|
||||
let ids = layers_listed(h, st, parent)?;
|
||||
let ids = layer_ids(h, st, parent)?;
|
||||
h.charge_call(ids.len() as u64)?;
|
||||
let id = ids.iter().find(|i| st.doc.node(**i).and_then(|n| n.name.as_deref()) == Some(name.as_str()));
|
||||
id.map(|id| layer_ref(h, st.uid, *id)).ok_or_else(|| HostError::Error(NOT_FOUND.into()))
|
||||
@@ -640,6 +634,8 @@ fn layers_by_name(h: &Host, a: &[Data]) -> Answer {
|
||||
fn layers_index(h: &Host, a: &[Data]) -> Answer {
|
||||
match arg(a, 1) {
|
||||
Data::String(_) => layers_by_name(h, a),
|
||||
// A number is a position here, never a name ([`layers_at`]).
|
||||
Data::Number(n) if super::position(*n).is_none() => Err(HostError::Error(NOT_FOUND.into())),
|
||||
Data::Number(_) => match layers_at(h, a)? {
|
||||
Data::Undefined => Err(HostError::Error(NOT_FOUND.into())),
|
||||
d => Ok(d),
|
||||
@@ -673,7 +669,7 @@ fn layers_remove_all(h: &Host, a: &[Data]) -> Answer {
|
||||
if parent.is_none() {
|
||||
return Err(HostError::Error("a document needs at least one layer".into()));
|
||||
}
|
||||
let ids = with_doc(h, doc, |_, st| layers_listed(h, st, parent))?;
|
||||
let ids = with_doc(h, doc, |_, st| layer_ids(h, st, parent))?;
|
||||
// `layer.delete` takes at most this many rows; more is refused before anything is deleted.
|
||||
if ids.len() > crate::cmd::layer::MAX_ROWS {
|
||||
return Err(HostError::Range(format!("removeAll deletes at most {} layers at once", crate::cmd::layer::MAX_ROWS)));
|
||||
@@ -692,13 +688,11 @@ fn art_scope(h: &Host, d: &Data, class: &str) -> Result<(Doc, Option<NodeId>)> {
|
||||
let Some(handle) = handle_of(d, class) else { return Err(type_error(class)) };
|
||||
match handle.as_slice() {
|
||||
[run, uid] => Ok((find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?, None)),
|
||||
[run, uid, high, low, reverts] => {
|
||||
let doc = find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?;
|
||||
let id = id_of(*high, *low).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?;
|
||||
// A collection read before File › Revert is stale like its container.
|
||||
[_, _, _, _, _] => {
|
||||
// A collection read before its document was reverted is stale, as its container is.
|
||||
let (doc, id) = super::node_of(h, &handle).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?;
|
||||
let holds = with_doc(h, doc, |_, st| {
|
||||
whole(*reverts) == Some(st.reverts)
|
||||
&& st.doc.node(id).is_some_and(|n| matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. } | NodeKind::Compound { .. }))
|
||||
st.doc.node(id).is_some_and(|n| matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. } | NodeKind::Compound { .. }))
|
||||
});
|
||||
if !holds {
|
||||
return Err(HostError::Error(STALE_ITEM.into()));
|
||||
@@ -755,23 +749,15 @@ fn art_list(h: &Host, st: &DocState, kind: Kind, container: Option<NodeId>) -> R
|
||||
Ok(ids)
|
||||
}
|
||||
|
||||
/// Whether a `PageItems` or `PathItems` object's handle names its container.
|
||||
pub(super) fn is_scoped(a: &[Data], class: &str) -> bool {
|
||||
host_ref_parts(arg(a, 0)).is_some_and(|(c, handle)| c == class && handle.len() == 5)
|
||||
}
|
||||
|
||||
fn scoped_kind(a: &[Data]) -> Kind {
|
||||
if host_ref_parts(arg(a, 0)).is_some_and(|(c, _)| c == "PathItems") { Kind::Path } else { Kind::Any }
|
||||
}
|
||||
|
||||
/// How many times File › Revert has reloaded the document with uid `uid`.
|
||||
fn reverts_of(h: &Host, uid: u64) -> u64 {
|
||||
h.session.borrow().documents().iter().find(|d| d.uid == uid).map_or(0, |d| d.reverts)
|
||||
/// The `PageItems` of a layer, group or compound path: a [`super`] `PageItems` object whose handle
|
||||
/// names the container.
|
||||
pub(super) fn is_scoped(a: &[Data]) -> bool {
|
||||
host_ref_parts(arg(a, 0)).is_some_and(|(c, handle)| c == "PageItems" && handle.len() == 5)
|
||||
}
|
||||
|
||||
fn collection(h: &Host, kind: Kind, container: Option<NodeId>, uid: u64) -> Data {
|
||||
match container {
|
||||
Some(c) => host_ref(kind.class(), &[float(h.run), float(uid), id_parts(c)[0], id_parts(c)[1], float(reverts_of(h, uid))]),
|
||||
Some(c) => host_ref(kind.class(), &super::scoped_handle(h, uid, c)),
|
||||
None => host_ref(kind.class(), &[float(h.run), float(uid)]),
|
||||
}
|
||||
}
|
||||
@@ -787,26 +773,19 @@ fn art_parent(h: &Host, a: &[Data], kind: Kind) -> Answer {
|
||||
Ok(with_doc(h, doc, |_, st| c.map_or_else(|| doc_ref(h, st.uid), |c| item_ref(h, st, c))))
|
||||
}
|
||||
|
||||
/// `collection[i]`, and `collection["name"]` as `getByName` reads it. A number key that is not an
|
||||
/// array index, such as `-1`, is looked up as a name, as the document's `pageItems` looks it up.
|
||||
fn art_at(h: &Host, a: &[Data], kind: Kind) -> Answer {
|
||||
let (doc, c) = art_scope(h, arg(a, 0), kind.class())?;
|
||||
if let Data::String(_) = arg(a, 1) {
|
||||
return match art_by_name(h, a, kind) {
|
||||
Err(HostError::Error(e)) if e == NOT_FOUND && probing(a) => Ok(Data::Undefined),
|
||||
r => r,
|
||||
};
|
||||
return super::by_name_or_probe(a, art_by_name(h, a, kind));
|
||||
}
|
||||
if let Some(named) = super::number_named(a) {
|
||||
return super::named_or_undefined(art_by_name(h, &named, kind));
|
||||
}
|
||||
let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) };
|
||||
match whole(*n).filter(|i| *i < u64::from(u32::MAX)).and_then(|i| usize::try_from(i).ok()) {
|
||||
Some(i) => with_doc(h, doc, |_, st| Ok(art_list(h, st, kind, c)?.get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id)))),
|
||||
// The text of a number that is not an array index is looked up as a name.
|
||||
None => with_doc(h, doc, |_, st| {
|
||||
let ids = art_list(h, st, kind, c)?;
|
||||
h.charge_call(ids.len() as u64)?;
|
||||
let name = vectorcraft_js::number_to_string(*n);
|
||||
let id = ids.iter().find(|i| st.doc.node(**i).and_then(|n| n.name.as_deref()) == Some(name.as_str()));
|
||||
Ok(id.map_or(Data::Undefined, |id| item_ref(h, st, *id)))
|
||||
}),
|
||||
}
|
||||
let Some(i) = super::position(*n) else { return Ok(Data::Undefined) };
|
||||
with_doc(h, doc, |_, st| Ok(art_list(h, st, kind, c)?.get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id))))
|
||||
}
|
||||
|
||||
fn art_by_name(h: &Host, a: &[Data], kind: Kind) -> Answer {
|
||||
@@ -814,6 +793,7 @@ fn art_by_name(h: &Host, a: &[Data], kind: Kind) -> Answer {
|
||||
let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) };
|
||||
with_doc(h, doc, |_, st| {
|
||||
let ids = art_list(h, st, kind, c)?;
|
||||
// The scan is charged by itself: a list kept from an earlier read was charged once.
|
||||
h.charge_call(ids.len() as u64)?;
|
||||
let id = ids.iter().find(|i| st.doc.node(**i).and_then(|n| n.name.as_deref()) == Some(name.as_str()));
|
||||
id.map(|id| item_ref(h, st, *id)).ok_or_else(|| HostError::Error(NOT_FOUND.into()))
|
||||
@@ -823,8 +803,9 @@ fn art_by_name(h: &Host, a: &[Data], kind: Kind) -> Answer {
|
||||
fn art_index(h: &Host, a: &[Data], kind: Kind) -> Answer {
|
||||
match arg(a, 1) {
|
||||
Data::String(_) => art_by_name(h, a, kind),
|
||||
// A number is a position only. A stale collection throws its stale error first.
|
||||
Data::Number(n) if whole(*n).is_none_or(|i| i >= u64::from(u32::MAX)) => {
|
||||
// A number is a position here, never a name ([`art_at`]). A stale collection throws its
|
||||
// stale error first.
|
||||
Data::Number(n) if super::position(*n).is_none() => {
|
||||
art_scope(h, arg(a, 0), kind.class())?;
|
||||
Err(HostError::Error(NOT_FOUND.into()))
|
||||
}
|
||||
@@ -853,36 +834,7 @@ fn art_remove_all(h: &Host, a: &[Data], kind: Kind) -> Answer {
|
||||
let refused: Vec<u64> = ids.iter().filter(|i| !whole(i)).map(|i| i.0).take(20).collect();
|
||||
let locks = d.locked_artboards();
|
||||
let on_locked: Vec<u64> = ids.iter().filter(|i| locks.holds_id(**i)).map(|i| i.0).take(20).collect();
|
||||
// A clipping path whose group or layer keeps other art would leave the next object clipping it.
|
||||
// Deleting every path of a compound path would leave it empty, so a compound path that
|
||||
// clips counts as deleted too.
|
||||
let mut going: std::collections::HashSet<NodeId> = ids.iter().copied().collect();
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
let mut emptied: Vec<NodeId> = Vec::new();
|
||||
for p in ids.iter().filter_map(|i| d.parent_of(*i)) {
|
||||
if going.contains(&p) || !seen.insert(p) {
|
||||
continue;
|
||||
}
|
||||
let all_go = |n: &crate::doc::Node| n.children().is_some_and(|k| k.iter().all(|k| going.contains(&k.id)));
|
||||
if d.node(p).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. }) && all_go(n)) {
|
||||
emptied.push(p);
|
||||
}
|
||||
}
|
||||
going.extend(emptied.iter().copied());
|
||||
let masks: Vec<u64> = ids
|
||||
.iter()
|
||||
.chain(&emptied)
|
||||
.filter(|i| {
|
||||
d.parent_of(**i).and_then(|p| d.node(p)).is_some_and(|p| {
|
||||
let kids = p.children().map_or(&[][..], Vec::as_slice);
|
||||
p.clips()
|
||||
&& kids.first().is_some_and(|f| f.id == **i)
|
||||
&& kids.iter().any(|k| !going.contains(&k.id) && !matches!(k.kind, NodeKind::RulerGuide { .. }))
|
||||
})
|
||||
})
|
||||
.map(|i| i.0)
|
||||
.take(20)
|
||||
.collect();
|
||||
let masks = kept_clipping_paths(d, &ids);
|
||||
Ok::<_, HostError>((ids, refused, on_locked, masks))
|
||||
})?;
|
||||
if !refused.is_empty() {
|
||||
@@ -893,12 +845,7 @@ fn art_remove_all(h: &Host, a: &[Data], kind: Kind) -> Answer {
|
||||
let list = on_locked.iter().map(u64::to_string).collect::<Vec<_>>().join(", ");
|
||||
return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {list}")));
|
||||
}
|
||||
if !masks.is_empty() {
|
||||
let list = masks.iter().map(u64::to_string).collect::<Vec<_>>().join(", ");
|
||||
return Err(HostError::Error(format!(
|
||||
"cannot delete a clipping path while its group or layer keeps other objects; release the clipping mask first: {list}"
|
||||
)));
|
||||
}
|
||||
refuse_kept_clipping_paths(&masks)?;
|
||||
// Deleting the objects above an image in an ordinary group named as a tracing would make it one.
|
||||
if with_doc(h, doc, |_, st| super::removal_makes_tracing(&st.doc, &ids)) {
|
||||
return Err(HostError::Error(super::NOT_A_TRACING.into()));
|
||||
@@ -909,29 +856,75 @@ fn art_remove_all(h: &Host, a: &[Data], kind: Kind) -> Answer {
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
/// The scoped art of a container, read by `PageItems` and `PathItems` ([`is_scoped`]).
|
||||
/// The ids (at most 20) among `ids` that are the clipping path of a group or layer that keeps other
|
||||
/// objects once `ids` are deleted. Deleting one would leave the next object clipping the rest.
|
||||
/// Deleting every path of a compound path would leave it empty, so a compound path that clips
|
||||
/// counts as deleted too.
|
||||
pub(super) fn kept_clipping_paths(d: &Document, ids: &[NodeId]) -> Vec<u64> {
|
||||
let mut going: std::collections::HashSet<NodeId> = ids.iter().copied().collect();
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
let mut emptied: Vec<NodeId> = Vec::new();
|
||||
for p in ids.iter().filter_map(|i| d.parent_of(*i)) {
|
||||
if going.contains(&p) || !seen.insert(p) {
|
||||
continue;
|
||||
}
|
||||
let all_go = |n: &crate::doc::Node| n.children().is_some_and(|k| k.iter().all(|k| going.contains(&k.id)));
|
||||
if d.node(p).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. }) && all_go(n)) {
|
||||
emptied.push(p);
|
||||
}
|
||||
}
|
||||
going.extend(emptied.iter().copied());
|
||||
ids.iter()
|
||||
.chain(&emptied)
|
||||
.filter(|i| {
|
||||
d.parent_of(**i).and_then(|p| d.node(p)).is_some_and(|p| {
|
||||
let kids = p.children().map_or(&[][..], Vec::as_slice);
|
||||
p.clips()
|
||||
&& kids.first().is_some_and(|f| f.id == **i)
|
||||
&& kids.iter().any(|k| !going.contains(&k.id) && !matches!(k.kind, NodeKind::RulerGuide { .. }))
|
||||
})
|
||||
})
|
||||
.map(|i| i.0)
|
||||
.take(20)
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The error of a `removeAll()` that would delete the clipping paths `masks`, or `Ok` when there
|
||||
/// are none.
|
||||
pub(super) fn refuse_kept_clipping_paths(masks: &[u64]) -> std::result::Result<(), HostError> {
|
||||
if masks.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let list = masks.iter().map(u64::to_string).collect::<Vec<_>>().join(", ");
|
||||
Err(HostError::Error(format!(
|
||||
"cannot delete a clipping path while its group or layer keeps other objects; release the clipping mask first: {list}"
|
||||
)))
|
||||
}
|
||||
|
||||
/// The scoped `PageItems` of a container, which `PageItems`' members hand over to when their
|
||||
/// handle names one ([`is_scoped`]).
|
||||
pub(super) fn scoped_length(h: &Host, a: &[Data]) -> Answer {
|
||||
art_length(h, a, scoped_kind(a))
|
||||
art_length(h, a, Kind::Any)
|
||||
}
|
||||
|
||||
pub(super) fn scoped_parent(h: &Host, a: &[Data]) -> Answer {
|
||||
art_parent(h, a, scoped_kind(a))
|
||||
art_parent(h, a, Kind::Any)
|
||||
}
|
||||
|
||||
pub(super) fn scoped_at(h: &Host, a: &[Data]) -> Answer {
|
||||
art_at(h, a, scoped_kind(a))
|
||||
art_at(h, a, Kind::Any)
|
||||
}
|
||||
|
||||
pub(super) fn scoped_by_name(h: &Host, a: &[Data]) -> Answer {
|
||||
art_by_name(h, a, scoped_kind(a))
|
||||
art_by_name(h, a, Kind::Any)
|
||||
}
|
||||
|
||||
pub(super) fn scoped_index(h: &Host, a: &[Data]) -> Answer {
|
||||
art_index(h, a, scoped_kind(a))
|
||||
art_index(h, a, Kind::Any)
|
||||
}
|
||||
|
||||
pub(super) fn scoped_remove_all(h: &Host, a: &[Data]) -> Answer {
|
||||
art_remove_all(h, a, scoped_kind(a))
|
||||
art_remove_all(h, a, Kind::Any)
|
||||
}
|
||||
|
||||
fn groups_length(h: &Host, a: &[Data]) -> Answer {
|
||||
@@ -977,7 +970,7 @@ fn art_typename(h: &Host, a: &[Data], kind: Kind) -> Answer {
|
||||
}
|
||||
|
||||
pub(super) fn scoped_typename(h: &Host, a: &[Data]) -> Answer {
|
||||
art_typename(h, a, scoped_kind(a))
|
||||
art_typename(h, a, Kind::Any)
|
||||
}
|
||||
fn groups_typename(h: &Host, a: &[Data]) -> Answer {
|
||||
art_typename(h, a, Kind::Group)
|
||||
@@ -987,15 +980,20 @@ fn compounds_typename(h: &Host, a: &[Data]) -> Answer {
|
||||
}
|
||||
|
||||
/// `groupItems.add()` and `compoundPathItems.add()`: an empty group or compound path on top of the
|
||||
/// layer's or group's contents (the document's: the current layer's), with `object.newGroup`.
|
||||
/// → the new object.
|
||||
/// layer's or group's contents (the document's: the current layer's), with `object.newGroup`. A
|
||||
/// Live Paint group takes none. → the new object.
|
||||
fn container_add(h: &Host, a: &[Data], kind: Kind) -> Answer {
|
||||
let (doc, c) = art_scope(h, arg(a, 0), kind.class())?;
|
||||
if let Some(c) = c {
|
||||
let compound = with_doc(h, doc, |_, st| st.doc.node(c).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. })));
|
||||
let (compound, live) = with_doc(h, doc, |_, st| {
|
||||
(st.doc.node(c).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. })), super::paths::is_live_paint_group(st, c))
|
||||
});
|
||||
if compound {
|
||||
return Err(HostError::Error("a compound path holds only paths".into()));
|
||||
}
|
||||
if live {
|
||||
return Err(HostError::Error(super::paths::LIVE_PAINT_CONTAINER.into()));
|
||||
}
|
||||
}
|
||||
let mut params = c.map_or_else(|| json!({}), |c| json!({"parent": c.0}));
|
||||
if kind == Kind::Compound
|
||||
@@ -1040,10 +1038,6 @@ fn held_page_items(h: &Host, a: &[Data]) -> Answer {
|
||||
held(h, a, Kind::Any)
|
||||
}
|
||||
|
||||
fn held_paths(h: &Host, a: &[Data]) -> Answer {
|
||||
held(h, a, Kind::Path)
|
||||
}
|
||||
|
||||
fn held_groups(h: &Host, a: &[Data]) -> Answer {
|
||||
held(h, a, Kind::Group)
|
||||
}
|
||||
@@ -1052,6 +1046,24 @@ fn held_compounds(h: &Host, a: &[Data]) -> Answer {
|
||||
held(h, a, Kind::Compound)
|
||||
}
|
||||
|
||||
/// A layer's or group's `pathItems`: the paths directly in it ([`super::paths`]).
|
||||
fn held_paths(h: &Host, a: &[Data]) -> Answer {
|
||||
let this = arg(a, 0);
|
||||
if handle_of(this, "Layer").is_some() {
|
||||
let (doc, id) = layer_of(h, this)?;
|
||||
return Ok(super::paths::held_path_items(h, doc.uid, id));
|
||||
}
|
||||
let item = this_item_of(h, a, "GroupItem")?;
|
||||
Ok(super::paths::held_path_items(h, item.doc.uid, item.id))
|
||||
}
|
||||
|
||||
/// A compound path's `pathItems`: its paths, which `add()` and the shape methods make inside it
|
||||
/// ([`super::paths`]).
|
||||
fn compound_paths(h: &Host, a: &[Data]) -> Answer {
|
||||
let item = this_item_of(h, a, "CompoundPathItem")?;
|
||||
Ok(super::paths::held_path_items(h, item.doc.uid, item.id))
|
||||
}
|
||||
|
||||
fn held_text(h: &Host, a: &[Data]) -> Answer {
|
||||
held(h, a, Kind::Text)
|
||||
}
|
||||
@@ -1127,12 +1139,13 @@ pub(super) fn members(class: &str, l: &Link) -> Vec<Described> {
|
||||
("pageItems", get(l, held_page_items), listed("PageItems")),
|
||||
("groupItems", get(l, held_groups), listed("GroupItems")),
|
||||
("compoundPathItems", get(l, held_compounds), listed("CompoundPathItems")),
|
||||
("pathItems", get(l, held_paths), listed("PathItems")),
|
||||
("textFrames", get(l, held_text), listed("TextFrames")),
|
||||
]);
|
||||
m.extend(["pathItems", "symbolItems", "placedItems", "rasterItems"].map(|m| later(l, "GroupItem", m)));
|
||||
m.extend(["symbolItems", "placedItems", "rasterItems"].map(|m| later(l, "GroupItem", m)));
|
||||
m
|
||||
}
|
||||
"CompoundPathItem" => named(vec![("pathItems", get(l, held_paths), listed("PathItems"))]),
|
||||
"CompoundPathItem" => named(vec![("pathItems", get(l, compound_paths), listed("PathItems"))]),
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
@@ -1196,19 +1209,22 @@ fn board_index(st: &DocState, id: u32) -> Option<usize> {
|
||||
st.doc.artboards.iter().position(|a| a.id == id)
|
||||
}
|
||||
|
||||
/// The artboard `d` names. An artboard read before its document was reverted is stale, as a page
|
||||
/// item is: the loaded document's artboard with the same id is another artboard.
|
||||
fn board_of(h: &Host, d: &Data) -> Result<(Board, usize)> {
|
||||
let Some(handle) = handle_of(d, "Artboard") else { return Err(type_error("Artboard")) };
|
||||
let [run, uid, id, reverts] = handle.as_slice() else { return Err(type_error("Artboard")) };
|
||||
let doc = find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_ARTBOARD.into()))?;
|
||||
let id = whole(*id).and_then(|i| u32::try_from(i).ok()).ok_or_else(|| HostError::Error(STALE_ARTBOARD.into()))?;
|
||||
// An artboard read before File › Revert is stale, as the page items read with it are.
|
||||
let index = with_doc(h, doc, |_, st| board_index(st, id).filter(|_| whole(*reverts) == Some(st.reverts)))
|
||||
.ok_or_else(|| HostError::Error(STALE_ARTBOARD.into()))?;
|
||||
Ok((Board { doc }, index))
|
||||
}
|
||||
|
||||
/// An `Artboard` for the artboard `id` of the document `uid`, with the document's revert count.
|
||||
fn board_ref(h: &Host, uid: u64, id: u32) -> Data {
|
||||
host_ref("Artboard", &[float(h.run), float(uid), f64::from(id), float(reverts_of(h, uid))])
|
||||
let reverts = h.session.borrow().documents().iter().find(|d| d.uid == uid).map_or(0, |d| d.reverts);
|
||||
host_ref("Artboard", &[float(h.run), float(uid), f64::from(id), float(reverts)])
|
||||
}
|
||||
|
||||
fn this_board(h: &Host, a: &[Data]) -> Result<(Board, usize)> {
|
||||
@@ -1435,13 +1451,18 @@ fn board_index_arg(d: &Data, len: usize, what: &str) -> Result<usize> {
|
||||
.ok_or_else(|| HostError::Range(format!("{what} must be a whole number from 0 to {}", len.saturating_sub(1))))
|
||||
}
|
||||
|
||||
/// `artboards[i]`, and `artboards["name"]` as `getByName` reads it. A number key that is not an
|
||||
/// array index, such as `-1`, is looked up as a name, as `pageItems` looks it up.
|
||||
fn boards_at(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = boards_doc(h, a)?;
|
||||
if let Data::String(_) = arg(a, 1) {
|
||||
return read_by_name(h, a, boards_by_name);
|
||||
return super::by_name_or_probe(a, boards_by_name(h, a));
|
||||
}
|
||||
if let Some(named) = super::number_named(a) {
|
||||
return super::named_or_undefined(boards_by_name(h, &named));
|
||||
}
|
||||
let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) };
|
||||
let Some(i) = whole(*n).and_then(|i| usize::try_from(i).ok()) else { return Ok(Data::Undefined) };
|
||||
let Some(i) = super::position(*n) else { return Ok(Data::Undefined) };
|
||||
Ok(with_doc(h, doc, |_, st| st.doc.artboards.get(i).map_or(Data::Undefined, |ab| board_ref(h, st.uid, ab.id))))
|
||||
}
|
||||
|
||||
@@ -1458,6 +1479,8 @@ fn boards_by_name(h: &Host, a: &[Data]) -> Answer {
|
||||
fn boards_index(h: &Host, a: &[Data]) -> Answer {
|
||||
match arg(a, 1) {
|
||||
Data::String(_) => boards_by_name(h, a),
|
||||
// A number is a position here, never a name ([`boards_at`]).
|
||||
Data::Number(n) if super::position(*n).is_none() => Err(HostError::Error(NOT_FOUND.into())),
|
||||
Data::Number(_) => match boards_at(h, a)? {
|
||||
Data::Undefined => Err(HostError::Error(NOT_FOUND.into())),
|
||||
d => Ok(d),
|
||||
@@ -1543,7 +1566,7 @@ fn boards_set_active(h: &Host, a: &[Data]) -> Answer {
|
||||
}
|
||||
{
|
||||
let mut chosen = h.dom.chosen_artboards.borrow_mut();
|
||||
let reverts = reverts_of(h, doc.uid);
|
||||
let reverts = with_doc(h, doc, |_, st| st.reverts);
|
||||
if let Some((_, generation)) = chosen.iter_mut().find(|(uid, _)| *uid == doc.uid) {
|
||||
*generation = reverts;
|
||||
} else {
|
||||
@@ -1601,13 +1624,14 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
|
||||
("printable", property(l, layer_printable, layer_set_printable), typed("boolean")),
|
||||
("preview", property(l, layer_preview, layer_set_preview), typed("boolean")),
|
||||
("dimPlacedImages", property(l, layer_dim, layer_set_dim), typed("boolean")),
|
||||
("opacity", property(l, layer_opacity, layer_set_opacity), typed("number")),
|
||||
("opacity", property(l, layer_opacity, layer_set_opacity), MemberInfo { min: Some(0.0), max: Some(100.0), ..typed("number") }),
|
||||
("color", property(l, layer_color, layer_set_color), typed("RGBColor")),
|
||||
("parent", get(l, layer_parent), typed("*")),
|
||||
("layers", get(l, layers_of), listed("Layers")),
|
||||
("pageItems", get(l, held_page_items), listed("PageItems")),
|
||||
("groupItems", get(l, held_groups), listed("GroupItems")),
|
||||
("compoundPathItems", get(l, held_compounds), listed("CompoundPathItems")),
|
||||
("pathItems", get(l, held_paths), listed("PathItems")),
|
||||
("textFrames", get(l, held_text), listed("TextFrames")),
|
||||
("zOrderPosition", get(l, layer_z_position), typed("number")),
|
||||
("hasSelectedArtwork", property(l, layer_has_selected, layer_set_has_selected), typed("boolean")),
|
||||
@@ -1617,9 +1641,7 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
|
||||
("zOrder", method(l, layer_z_order), returns("undefined", &[("zOrderCmd", "ZOrderMethod")])),
|
||||
("toString", method(l, layer_to_string), returns("string", &[])),
|
||||
]);
|
||||
layer.extend(
|
||||
["pathItems", "symbolItems", "placedItems", "rasterItems", "blendingMode", "artworkKnockout", "sliced"].map(|m| later(l, "Layer", m)),
|
||||
);
|
||||
layer.extend(["symbolItems", "placedItems", "rasterItems", "blendingMode", "artworkKnockout", "sliced"].map(|m| later(l, "Layer", m)));
|
||||
vec![
|
||||
class("Layer", None, layer, None),
|
||||
class(
|
||||
@@ -1680,7 +1702,7 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
|
||||
("name", property(l, board_name, board_set_name), typed("string")),
|
||||
("parent", get(l, board_parent), typed("Document")),
|
||||
("rulerOrigin", property(l, board_ruler_origin, board_set_ruler_origin), typed("Array")),
|
||||
("rulerPAR", property(l, board_par, board_set_par), typed("number")),
|
||||
("rulerPAR", property(l, board_par, board_set_par), MemberInfo { min: Some(0.1), max: Some(10.0), ..typed("number") }),
|
||||
("showCenter", property(l, board_center, board_set_center), typed("boolean")),
|
||||
("showCrossHairs", property(l, board_cross_hairs, board_set_cross_hairs), typed("boolean")),
|
||||
("showSafeAreas", property(l, board_safe_areas, board_set_safe_areas), typed("boolean")),
|
||||
|
||||
@@ -13,7 +13,9 @@
|
||||
//!
|
||||
//! VectorCraft's own rules, which the help pages do not state:
|
||||
//! - `Document.pathItems` lists the document's paths in the order of `pageItems`, paths inside
|
||||
//! groups and compound paths included.
|
||||
//! groups and compound paths included. A layer's or group's `pathItems` list the paths directly in
|
||||
//! it, topmost first, and make their paths on top of its contents; a layer or group that is hidden
|
||||
//! or locked, or that is in a hidden or locked layer or group, throws [`CONTAINER_LOCKED`].
|
||||
//! - A change to the geometry or paint of a path that is hidden or locked, or that is in a hidden
|
||||
//! or locked layer or group, or that is on a locked artboard, throws `Cannot edit` with nothing
|
||||
//! changed, and `pathItems.removeAll()` deletes nothing when one of the paths is on a locked
|
||||
@@ -26,8 +28,8 @@
|
||||
//! fill or stroke only.
|
||||
//! - `closed` is true when every subpath of the path is closed, and assigning it opens or closes
|
||||
//! them all.
|
||||
//! - `pathItems.add()` and the shape creators make their path on top of the active layer, whatever
|
||||
//! the drawing mode, painted as new art is; `add()` makes a path with no points. `filled` and `stroked` set to true give a path with no fill or stroke new art's fill or
|
||||
//! - `pathItems.add()` and the shape creators make their path on top of the active layer (a layer's
|
||||
//! or group's: on top of its contents), whatever the drawing mode, painted as new art is; `add()` makes a path with no points. `filled` and `stroked` set to true give a path with no fill or stroke new art's fill or
|
||||
//! stroke (solid, gradient or pattern), or black when new art has none. `PathPoints.add()` adds
|
||||
//! a corner point with no handles at the last point, or at `[0, 0]` on a path with no points.
|
||||
//! Removing the last points leaves the path, with no points.
|
||||
@@ -68,9 +70,9 @@ use vectorcraft_js::{Data, HostClass, HostError, HostItem, HostMember, MemberInf
|
||||
use vectorcraft_tools::params::gradient_params;
|
||||
|
||||
use super::{
|
||||
Answer, Coords, Described, Doc, Item, Link, NOT_FOUND, ON_LOCKED_ARTBOARD, STALE_ITEM, arg, boolean, class, colors, command, coordinate, doc_of,
|
||||
edit_item, editable, find_doc, float, frame, get, given, handle_of, id_of, item_of, later, method, named, num, number, on_doc, pair, point,
|
||||
point_get, point_method, point_property, property, returns, this_doc, typed, whole, with_doc,
|
||||
Answer, Coords, Described, Doc, Item, Link, NOT_FOUND, ON_LOCKED_ARTBOARD, STALE_ITEM, arg, boolean, class, class_text, colors, command,
|
||||
coordinate, edit_item, editable, find_doc, float, frame, get, given, handle_of, id_of, item_of, later, method, named, num, number, on_doc, pair,
|
||||
point, point_get, point_method, point_property, property, returns, this_doc, typed, whole, with_doc,
|
||||
};
|
||||
use crate::{DocState, NodeId, NodeKind};
|
||||
|
||||
@@ -168,6 +170,12 @@ fn path_ref(h: &super::Host, item: Item) -> Data {
|
||||
host_ref("PathItem", &handle)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// How many times [`point_starts`] counted the points of a path on this thread.
|
||||
static INDEX_BUILDS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// The index of the first point of each subpath of `subs`, followed by the number of points.
|
||||
fn starts(subs: &[SubPath]) -> Vec<usize> {
|
||||
#[cfg(test)]
|
||||
@@ -208,6 +216,8 @@ fn point_starts(h: &super::Host, item: Item) -> std::result::Result<Rc<Vec<usize
|
||||
{
|
||||
return Ok(kept.clone());
|
||||
}
|
||||
#[cfg(test)]
|
||||
INDEX_BUILDS.with(|n| n.set(n.get() + 1));
|
||||
let counted = Rc::new(read_points(h, item, starts)?);
|
||||
*h.dom.point_starts.borrow_mut() = Some((Counted::Waiting(item), counted.clone()));
|
||||
return Ok(counted);
|
||||
@@ -219,6 +229,8 @@ fn point_starts(h: &super::Host, item: Item) -> std::result::Result<Rc<Vec<usize
|
||||
{
|
||||
return Ok(kept.clone());
|
||||
}
|
||||
#[cfg(test)]
|
||||
INDEX_BUILDS.with(|n| n.set(n.get() + 1));
|
||||
let counted = Rc::new(starts(&node.path_data().ok_or_else(|| HostError::Type("this is not a PathItem".into()))?.subpaths));
|
||||
*h.dom.point_starts.borrow_mut() = Some((Counted::Node(item.doc.uid, node), counted.clone()));
|
||||
Ok(counted)
|
||||
@@ -229,6 +241,12 @@ fn points_of(h: &super::Host, item: Item) -> std::result::Result<usize, HostErro
|
||||
Ok(point_starts(h, item)?.last().copied().unwrap_or(0))
|
||||
}
|
||||
|
||||
/// How many times [`point_starts`] counted the points of a path on this thread.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn index_builds() -> u64 {
|
||||
INDEX_BUILDS.with(std::cell::Cell::get)
|
||||
}
|
||||
|
||||
/// The subpath and the place in it of point `i`, among the subpaths `subs`.
|
||||
fn locate(subs: &[SubPath], mut i: usize) -> Option<(usize, usize)> {
|
||||
for (s, sp) in subs.iter().enumerate() {
|
||||
@@ -267,7 +285,20 @@ fn read_points<T>(h: &super::Host, item: Item, f: impl FnOnce(&[SubPath]) -> T)
|
||||
/// that is aligned to the pixel grid, or is in an object that is, is written at once, so that its
|
||||
/// points read as the grid snaps them.
|
||||
fn edit_points<T>(h: &super::Host, item: Item, f: impl FnOnce(&mut Vec<SubPath>) -> T) -> std::result::Result<T, HostError> {
|
||||
forget_waiting_starts(h);
|
||||
edit_points_keeping(h, item, false, f)
|
||||
}
|
||||
|
||||
/// [`edit_points`]. With `counts_kept`, `f` leaves the number of subpaths and of points in each as
|
||||
/// they are, so the [`starts`] of the waiting changes stay kept.
|
||||
fn edit_points_keeping<T>(
|
||||
h: &super::Host,
|
||||
item: Item,
|
||||
counts_kept: bool,
|
||||
f: impl FnOnce(&mut Vec<SubPath>) -> T,
|
||||
) -> std::result::Result<T, HostError> {
|
||||
if !counts_kept {
|
||||
forget_waiting_starts(h);
|
||||
}
|
||||
// A path that has or gains points keeps its own closed state from then on ([`is_closed`]).
|
||||
let gained = |gained: bool| {
|
||||
if gained {
|
||||
@@ -357,7 +388,7 @@ fn forget_waiting_starts(h: &super::Host) {
|
||||
fn edit_anchor(h: &super::Host, item: Item, i: usize, f: impl FnOnce(&mut Anchor)) -> std::result::Result<(), HostError> {
|
||||
let counted = point_starts(h, item)?;
|
||||
let at = locate_at(&counted, i);
|
||||
edit_points(h, item, |subs| {
|
||||
edit_points_keeping(h, item, true, |subs| {
|
||||
if let Some((s, j)) = at
|
||||
&& let Some(an) = subs.get_mut(s).and_then(|sp| sp.anchors.get_mut(j))
|
||||
{
|
||||
@@ -444,14 +475,14 @@ pub(super) fn flush(h: &super::Host) -> std::result::Result<(), HostError> {
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// How many times this thread listed a document's paths ([`path_items`]), for the tests.
|
||||
pub(crate) static PATH_LISTS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
|
||||
pub(crate) static PATH_LIST_BUILDS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// Runs `f`, a command that changes the paint, stroke or points of the path `item` and adds,
|
||||
/// removes and reorders no object of its own. When it succeeds, the document made no new object,
|
||||
/// and the path is not inside a Shaper group, the list of the document's paths ([`path_items`])
|
||||
/// stays kept. An edit inside a Shaper group regenerates the group's paths, which can drop a
|
||||
/// path without making a new id.
|
||||
/// and the path is not inside a Shaper group, the lists of the document's, its layers' and its
|
||||
/// groups' paths ([`path_items`]) stay kept. An edit inside a Shaper group regenerates the group's
|
||||
/// paths, which can drop a path without making a new id.
|
||||
fn keeping_paths<T>(h: &super::Host, item: Item, f: impl FnOnce() -> std::result::Result<T, HostError>) -> std::result::Result<T, HostError> {
|
||||
let doc_state = |h: &super::Host, run: &mut dyn FnMut(&DocState)| {
|
||||
let s = h.session.borrow();
|
||||
@@ -463,14 +494,19 @@ fn keeping_paths<T>(h: &super::Host, item: Item, f: impl FnOnce() -> std::result
|
||||
doc_state(h, &mut |st| {
|
||||
let in_shaper = st.doc.ancestry(item.id).unwrap_or_default().iter().filter_map(|i| st.doc.node(*i)).any(|a| a.extras().shaper.is_some());
|
||||
if !in_shaper {
|
||||
kept = super::kept_list(&h.dom.paths, st).map(|ids| (ids, st.doc.peek_next_id()));
|
||||
let listed = h.dom.paths.borrow().iter().any(|(uid, doc, ..)| *uid == st.uid && Arc::ptr_eq(doc, &st.doc));
|
||||
if listed {
|
||||
kept = Some((st.doc.clone(), st.doc.peek_next_id()));
|
||||
}
|
||||
}
|
||||
});
|
||||
let r = f()?;
|
||||
if let Some((ids, next)) = kept {
|
||||
if let Some((before, next)) = kept {
|
||||
doc_state(h, &mut |st| {
|
||||
if st.doc.peek_next_id() == next {
|
||||
super::keep_list(&h.dom.paths, st, &ids);
|
||||
for list in h.dom.paths.borrow_mut().iter_mut().filter(|(uid, doc, ..)| *uid == st.uid && Arc::ptr_eq(doc, &before)) {
|
||||
list.1 = st.doc.clone();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -565,21 +601,50 @@ fn keeping_paint<T>(h: &super::Host, f: impl FnOnce() -> T) -> T {
|
||||
r
|
||||
}
|
||||
|
||||
// ---- Document.pathItems ----
|
||||
// ---- Document.pathItems, Layer.pathItems and GroupItem.pathItems ----
|
||||
|
||||
/// The ids of a document's paths, in the order of its page items. Building the list again counts
|
||||
/// the page items it looks through against the run's host-call allowance.
|
||||
fn path_items(h: &super::Host, st: &DocState) -> Result<Rc<Vec<NodeId>>, HostError> {
|
||||
if let Some(ids) = super::kept_list(&h.dom.paths, st) {
|
||||
return Ok(ids);
|
||||
/// A document's uid, the document as it was, the layer or group a list of paths is of (none for the
|
||||
/// document's), and the ids it listed then.
|
||||
pub(super) type PathList = (u64, Arc<crate::Document>, Option<NodeId>, Rc<Vec<NodeId>>);
|
||||
|
||||
/// How many lists of paths [`super::State`] keeps at once.
|
||||
pub(super) const PATH_LISTS: usize = 4;
|
||||
|
||||
/// The ids of a document's paths, in the order of its page items, or of the paths directly in the
|
||||
/// layer or group `container`, topmost first. The last [`PATH_LISTS`] lists are kept while their
|
||||
/// documents are unchanged, so a loop over a collection builds its list once. A new list is
|
||||
/// charged by the objects it looks at.
|
||||
fn path_items(h: &super::Host, st: &DocState, container: Option<NodeId>) -> std::result::Result<Rc<Vec<NodeId>>, HostError> {
|
||||
{
|
||||
let mut lists = h.dom.paths.borrow_mut();
|
||||
if let Some(at) = lists.iter().position(|(uid, doc, c, _)| *uid == st.uid && Arc::ptr_eq(doc, &st.doc) && *c == container) {
|
||||
let list = lists.remove(at);
|
||||
let ids = list.3.clone();
|
||||
lists.push(list);
|
||||
return Ok(ids);
|
||||
}
|
||||
}
|
||||
#[cfg(test)]
|
||||
PATH_LISTS.with(|n| n.set(n.get() + 1));
|
||||
let all = super::page_items(h, st)?;
|
||||
h.charge_call(all.len() as u64)?;
|
||||
let ids: Rc<Vec<NodeId>> =
|
||||
Rc::new(all.iter().copied().filter(|i| st.doc.node(*i).is_some_and(|n| matches!(n.kind, NodeKind::Path { .. }))).collect());
|
||||
super::keep_list(&h.dom.paths, st, &ids);
|
||||
PATH_LIST_BUILDS.with(|n| n.set(n.get() + 1));
|
||||
let is_path = |n: &crate::doc::Node| matches!(n.kind, NodeKind::Path { .. });
|
||||
let ids: Rc<Vec<NodeId>> = match container {
|
||||
Some(c) => {
|
||||
let children: &[Arc<crate::doc::Node>] = st.doc.node(c).and_then(|n| n.children()).map_or(&[], Vec::as_slice);
|
||||
h.charge_call(children.len() as u64)?;
|
||||
Rc::new(children.iter().rev().filter(|n| is_path(n)).map(|n| n.id).collect())
|
||||
}
|
||||
None => {
|
||||
let all = super::page_items(h, st)?;
|
||||
h.charge_call(all.len() as u64)?;
|
||||
Rc::new(all.iter().copied().filter(|i| st.doc.node(*i).is_some_and(is_path)).collect())
|
||||
}
|
||||
};
|
||||
let mut lists = h.dom.paths.borrow_mut();
|
||||
lists.retain(|(uid, doc, ..)| *uid != st.uid || Arc::ptr_eq(doc, &st.doc));
|
||||
if lists.len() >= PATH_LISTS {
|
||||
lists.remove(0);
|
||||
}
|
||||
lists.push((st.uid, st.doc.clone(), container, ids.clone()));
|
||||
Ok(ids)
|
||||
}
|
||||
|
||||
@@ -588,54 +653,66 @@ pub(super) fn doc_path_items(h: &super::Host, a: &[Data]) -> Answer {
|
||||
Ok(host_ref("PathItems", &[float(h.run), float(doc.uid)]))
|
||||
}
|
||||
|
||||
fn items_doc(h: &super::Host, a: &[Data]) -> std::result::Result<Doc, HostError> {
|
||||
if super::layers::is_scoped(a, "PathItems") {
|
||||
return Err(HostError::Error("creating paths in a compound path is not available yet; move a path into it".into()));
|
||||
/// The `pathItems` of the layer or group `id` in the document `uid`.
|
||||
pub(super) fn held_path_items(h: &super::Host, uid: u64, id: NodeId) -> Data {
|
||||
host_ref("PathItems", &super::scoped_handle(h, uid, id))
|
||||
}
|
||||
|
||||
/// The document of a `PathItems` object, and the layer, group or compound path it lists the paths
|
||||
/// of, if any.
|
||||
fn items_scope(h: &super::Host, a: &[Data]) -> std::result::Result<(Doc, Option<NodeId>), HostError> {
|
||||
let Some(handle) = handle_of(arg(a, 0), "PathItems") else { return Err(HostError::Type("this is not a PathItems".into())) };
|
||||
match handle.as_slice() {
|
||||
[run, uid] => Ok((find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(super::STALE_DOCUMENT.into()))?, None)),
|
||||
[_, _, _, _, _] => {
|
||||
// A collection read before its document was reverted is stale, as its container is.
|
||||
let (doc, id) = super::node_of(h, &handle).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?;
|
||||
let holds = with_doc(h, doc, |_, st| {
|
||||
st.doc.node(id).is_some_and(|n| matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. } | NodeKind::Compound { .. }))
|
||||
});
|
||||
if !holds {
|
||||
return Err(HostError::Error(STALE_ITEM.into()));
|
||||
}
|
||||
Ok((doc, Some(id)))
|
||||
}
|
||||
_ => Err(HostError::Type("this is not a PathItems".into())),
|
||||
}
|
||||
doc_of(h, arg(a, 0), "PathItems")
|
||||
}
|
||||
|
||||
/// `typename` of the paths of a document that is still open.
|
||||
fn items_typename(h: &super::Host, a: &[Data]) -> Answer {
|
||||
if super::layers::is_scoped(a, "PathItems") {
|
||||
return super::layers::scoped_typename(h, a);
|
||||
}
|
||||
items_doc(h, a)?;
|
||||
items_scope(h, a)?;
|
||||
Ok(Data::String("PathItems".into()))
|
||||
}
|
||||
|
||||
fn items_length(h: &super::Host, a: &[Data]) -> Answer {
|
||||
if super::layers::is_scoped(a, "PathItems") {
|
||||
return super::layers::scoped_length(h, a);
|
||||
}
|
||||
let doc = items_doc(h, a)?;
|
||||
Ok(num(float(with_doc(h, doc, |_, st| path_items(h, st).map(|ids| ids.len()))? as u64)))
|
||||
let (doc, c) = items_scope(h, a)?;
|
||||
Ok(num(float(with_doc(h, doc, |_, st| path_items(h, st, c).map(|l| l.len()))? as u64)))
|
||||
}
|
||||
|
||||
fn items_parent(h: &super::Host, a: &[Data]) -> Answer {
|
||||
if super::layers::is_scoped(a, "PathItems") {
|
||||
return super::layers::scoped_parent(h, a);
|
||||
}
|
||||
let doc = items_doc(h, a)?;
|
||||
Ok(host_ref("Document", &[float(h.run), float(doc.uid)]))
|
||||
let (doc, c) = items_scope(h, a)?;
|
||||
Ok(match c {
|
||||
None => host_ref("Document", &[float(h.run), float(doc.uid)]),
|
||||
Some(c) => with_doc(h, doc, |_, st| {
|
||||
if st.doc.node(c).is_some_and(crate::doc::Node::is_layer) { super::layers::layer_ref(h, st.uid, c) } else { super::item_ref(h, st, c) }
|
||||
}),
|
||||
})
|
||||
}
|
||||
|
||||
/// `pathItems[i]`, and `pathItems["name"]` as `getByName` reads it. A key that is the text of a
|
||||
/// number but not an array index, such as `-1` or `1.5`, reaches the indexer as a number and is
|
||||
/// looked up as that name, giving `undefined` when no path has it.
|
||||
fn items_at(h: &super::Host, a: &[Data]) -> Answer {
|
||||
if super::layers::is_scoped(a, "PathItems") {
|
||||
return super::layers::scoped_at(h, a);
|
||||
}
|
||||
let doc = items_doc(h, a)?;
|
||||
let (doc, c) = items_scope(h, a)?;
|
||||
match arg(a, 1) {
|
||||
Data::String(_) => match items_by_name(h, a) {
|
||||
Err(HostError::Error(e)) if e == NOT_FOUND && super::probing(a) => Ok(Data::Undefined),
|
||||
r => r,
|
||||
},
|
||||
Data::Number(n) => match super::position(*n) {
|
||||
Some(i) => item_at(h, doc, i),
|
||||
None => match items_named(h, doc, &vectorcraft_js::number_to_string(*n)) {
|
||||
Some(i) => item_at(h, doc, c, i),
|
||||
None => match items_named(h, doc, c, &vectorcraft_js::number_to_string(*n)) {
|
||||
Err(HostError::Error(e)) if e == NOT_FOUND => Ok(Data::Undefined),
|
||||
r => r,
|
||||
},
|
||||
@@ -645,23 +722,20 @@ fn items_at(h: &super::Host, a: &[Data]) -> Answer {
|
||||
}
|
||||
|
||||
/// The path at position `i` of `pathItems`, or `undefined` past the end.
|
||||
fn item_at(h: &super::Host, doc: Doc, i: usize) -> Answer {
|
||||
with_doc(h, doc, |_, st| Ok(path_items(h, st)?.get(i).map_or(Data::Undefined, |id| super::item_ref(h, st, *id))))
|
||||
fn item_at(h: &super::Host, doc: Doc, c: Option<NodeId>, i: usize) -> Answer {
|
||||
with_doc(h, doc, |_, st| Ok(path_items(h, st, c)?.get(i).map_or(Data::Undefined, |id| super::item_ref(h, st, *id))))
|
||||
}
|
||||
|
||||
fn items_by_name(h: &super::Host, a: &[Data]) -> Answer {
|
||||
if super::layers::is_scoped(a, "PathItems") {
|
||||
return super::layers::scoped_by_name(h, a);
|
||||
}
|
||||
let doc = items_doc(h, a)?;
|
||||
let (doc, c) = items_scope(h, a)?;
|
||||
let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) };
|
||||
items_named(h, doc, name)
|
||||
items_named(h, doc, c, name)
|
||||
}
|
||||
|
||||
/// The first path of `pathItems` named `name`, or `Not found`.
|
||||
fn items_named(h: &super::Host, doc: Doc, name: &str) -> Answer {
|
||||
fn items_named(h: &super::Host, doc: Doc, c: Option<NodeId>, name: &str) -> Answer {
|
||||
with_doc(h, doc, |_, st| {
|
||||
let ids = path_items(h, st)?;
|
||||
let ids = path_items(h, st, c)?;
|
||||
h.charge_call(ids.len() as u64)?;
|
||||
let id = ids.iter().find(|i| st.doc.node(**i).and_then(|n| n.name.as_deref()) == Some(name));
|
||||
id.map(|id| super::item_ref(h, st, *id)).ok_or_else(|| HostError::Error(NOT_FOUND.into()))
|
||||
@@ -669,14 +743,11 @@ fn items_named(h: &super::Host, doc: Doc, name: &str) -> Answer {
|
||||
}
|
||||
|
||||
fn items_index(h: &super::Host, a: &[Data]) -> Answer {
|
||||
if super::layers::is_scoped(a, "PathItems") {
|
||||
return super::layers::scoped_index(h, a);
|
||||
}
|
||||
match arg(a, 1) {
|
||||
Data::String(_) => items_by_name(h, a),
|
||||
Data::Number(n) => {
|
||||
let doc = items_doc(h, a)?;
|
||||
match whole(*n).and_then(|i| usize::try_from(i).ok()).map(|i| item_at(h, doc, i)).transpose()? {
|
||||
let (doc, c) = items_scope(h, a)?;
|
||||
match whole(*n).and_then(|i| usize::try_from(i).ok()).map(|i| item_at(h, doc, c, i)).transpose()? {
|
||||
Some(Data::Undefined) | None => Err(HostError::Error(NOT_FOUND.into())),
|
||||
Some(d) => Ok(d),
|
||||
}
|
||||
@@ -685,18 +756,17 @@ fn items_index(h: &super::Host, a: &[Data]) -> Answer {
|
||||
}
|
||||
}
|
||||
|
||||
/// `pathItems.removeAll()`: deletes every path of the document in one command. A hidden or locked
|
||||
/// path, one in a hidden or locked layer or group, or one on a locked artboard stops it before
|
||||
/// anything is deleted, as `PageItems.removeAll()` does. So does the clipping path of a group or
|
||||
/// layer that keeps other objects, or a compound path or group that clips one and would be left
|
||||
/// with no visible path or visible type that lays out glyphs to clip by.
|
||||
/// `pathItems.removeAll()`: deletes every path the collection lists in one command. A hidden or
|
||||
/// locked path, one in a hidden or locked layer or group, or one on a locked artboard stops it
|
||||
/// before anything is deleted, as `PageItems.removeAll()` does. A compound path's
|
||||
/// `pathItems.removeAll()` leaves the compound path, empty, as `remove()` of its last path does.
|
||||
/// It also throws and deletes nothing when it would delete the clipping path of a group or layer
|
||||
/// that keeps other objects, or leave a compound path or group that clips one with no visible path
|
||||
/// or visible type that lays out glyphs to clip by.
|
||||
fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer {
|
||||
if super::layers::is_scoped(a, "PathItems") {
|
||||
return super::layers::scoped_remove_all(h, a);
|
||||
}
|
||||
let doc = items_doc(h, a)?;
|
||||
let (ids, refused, on_locked, masks) = with_doc(h, doc, |_, st| {
|
||||
let ids = path_items(h, st)?;
|
||||
let (doc, c) = items_scope(h, a)?;
|
||||
let (ids, refused, on_locked, masks, tracing) = with_doc(h, doc, |_, st| {
|
||||
let ids = path_items(h, st, c)?;
|
||||
let d = &st.doc;
|
||||
if h.session.borrow().menu.guides_locked
|
||||
&& let Some(id) = ids.iter().find(|id| d.node(**id).is_some_and(|n| matches!(n.kind, NodeKind::Path { guide: true, .. })))
|
||||
@@ -738,8 +808,10 @@ fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer {
|
||||
let mut masks = Vec::new();
|
||||
for n in nodes.into_iter().rev() {
|
||||
let kids = n.children().map_or(&[][..], Vec::as_slice);
|
||||
// Clear removes compound paths emptied of direct members, but keeps empty groups.
|
||||
if matches!(n.kind, NodeKind::Compound { .. })
|
||||
// Without `keepEmpty`, clear removes compound paths emptied of direct members, but keeps
|
||||
// empty groups. A compound path's own `pathItems.removeAll()` keeps it, empty.
|
||||
if c.is_none()
|
||||
&& matches!(n.kind, NodeKind::Compound { .. })
|
||||
&& !kids.is_empty()
|
||||
&& kids.iter().all(|k| matches!(k.kind, NodeKind::Path { .. }) && going.contains(&k.id))
|
||||
{
|
||||
@@ -772,7 +844,10 @@ fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer {
|
||||
masks.push(mask.id.0);
|
||||
}
|
||||
}
|
||||
Ok::<_, HostError>((ids, refused, on_locked, masks))
|
||||
let going: Vec<NodeId> = going.into_iter().collect();
|
||||
// Deleting the objects above an image in an ordinary group named as a tracing would make it one.
|
||||
let tracing = super::removal_makes_tracing(d, &going);
|
||||
Ok::<_, HostError>((ids, refused, on_locked, masks, tracing))
|
||||
})?;
|
||||
if !refused.is_empty() {
|
||||
let list = refused.iter().map(u64::to_string).collect::<Vec<_>>().join(", ");
|
||||
@@ -782,14 +857,13 @@ fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer {
|
||||
let list = on_locked.iter().map(u64::to_string).collect::<Vec<_>>().join(", ");
|
||||
return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {list}")));
|
||||
}
|
||||
if !masks.is_empty() {
|
||||
let list = masks.iter().map(u64::to_string).collect::<Vec<_>>().join(", ");
|
||||
return Err(HostError::Error(format!(
|
||||
"cannot delete a clipping path while its group or layer keeps other objects; release the clipping mask first: {list}"
|
||||
)));
|
||||
super::layers::refuse_kept_clipping_paths(&masks)?;
|
||||
if tracing {
|
||||
return Err(HostError::Error(super::NOT_A_TRACING.into()));
|
||||
}
|
||||
if !ids.is_empty() {
|
||||
on_doc(h, doc.uid, true, |h| command(h, "edit.clear", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})))?;
|
||||
let params = json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "keepEmpty": c.is_some()});
|
||||
on_doc(h, doc.uid, true, |h| command(h, "edit.clear", ¶ms))?;
|
||||
}
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
@@ -800,13 +874,66 @@ fn made_id(r: &(Data, Value)) -> std::result::Result<NodeId, HostError> {
|
||||
r.1.get("id").and_then(Value::as_u64).map(NodeId).ok_or_else(|| HostError::Error("the path was not made".into()))
|
||||
}
|
||||
|
||||
/// Runs the command `id` that makes a path in `doc` on top of the active layer, the selection kept,
|
||||
/// and reverses the new path's direction when `reversed`. → the new path. Selecting the new path
|
||||
/// and putting the selection back load the selected objects' paint and stroke width into new art,
|
||||
/// so new art's paint from before, the defaults a script set included, is put back.
|
||||
fn make(h: &super::Host, doc: Doc, id: &str, params: &Value, reversed: bool) -> Answer {
|
||||
let made = keeping_paint(h, || {
|
||||
on_doc(h, doc.uid, true, |h| {
|
||||
/// The error of a path made in a layer or group that is hidden or locked, or that is in a hidden or
|
||||
/// locked layer or group.
|
||||
pub const CONTAINER_LOCKED: &str = "Cannot add a path to a hidden or locked layer or group";
|
||||
|
||||
/// The error of an object made in a Live Paint group, which would join the group's paths instead
|
||||
/// of staying in the group's own list.
|
||||
pub const LIVE_PAINT_CONTAINER: &str = "Cannot add an object to a Live Paint group";
|
||||
|
||||
/// Whether `id` is a Live Paint group, which takes no new objects from the object model.
|
||||
pub(super) fn is_live_paint_group(st: &DocState, id: NodeId) -> bool {
|
||||
st.doc.node(id).is_some_and(vectorcraft_tools::builder::is_live_paint)
|
||||
}
|
||||
|
||||
/// Runs `make`, which makes a path in `doc` on top of the current layer and gives its id, with the
|
||||
/// selection and the current layer kept. With a layer or group `container`, the container's layer
|
||||
/// is the current one while `make` runs (`layer.setCurrent`, not an undo step), and a path made
|
||||
/// outside the container then moves on top of its contents in the same step; a container that is
|
||||
/// hidden or locked, or that is in a hidden or locked layer or group, throws [`CONTAINER_LOCKED`]
|
||||
/// before anything is made, and a Live Paint group throws [`LIVE_PAINT_CONTAINER`]. → the new path.
|
||||
fn make_in(
|
||||
h: &super::Host,
|
||||
doc: Doc,
|
||||
container: Option<NodeId>,
|
||||
make: impl FnOnce(&super::Host) -> std::result::Result<NodeId, HostError>,
|
||||
) -> Answer {
|
||||
if let Some(c) = container {
|
||||
let (open, live) = with_doc(h, doc, |_, st| (editable(&st.doc, c), is_live_paint_group(st, c)));
|
||||
if !open {
|
||||
return Err(HostError::Error(CONTAINER_LOCKED.into()));
|
||||
}
|
||||
if live {
|
||||
return Err(HostError::Error(LIVE_PAINT_CONTAINER.into()));
|
||||
}
|
||||
}
|
||||
let made = match container {
|
||||
// Making a path can take more than one command (a stroke, a reversal): a failure of a later
|
||||
// one undoes the path too.
|
||||
None => super::atomically(h, |h| on_doc(h, doc.uid, true, make))?,
|
||||
Some(c) => super::atomically(h, |h| {
|
||||
let id = on_doc(h, doc.uid, true, |h| {
|
||||
command(h, "layer.setCurrent", &json!({"id": c.0, "keepRows": true}))?;
|
||||
make(h)
|
||||
})?;
|
||||
super::place(h, doc, id, &super::Destination { parent: c, beside: None, how: super::Placement::Top })?;
|
||||
Ok(id)
|
||||
})?,
|
||||
};
|
||||
let s = h.session.borrow();
|
||||
let st = s.documents().iter().find(|d| d.uid == doc.uid).ok_or_else(|| HostError::Error(super::STALE_DOCUMENT.into()))?;
|
||||
Ok(super::item_ref(h, st, made))
|
||||
}
|
||||
|
||||
/// Runs the command `id` that makes a path in `doc`, on top of the active layer or of `container`'s
|
||||
/// contents ([`make_in`]), and reverses the new path's direction when `reversed`. → the new path.
|
||||
/// Selecting the new path and putting the selection back load the selected objects' paint and
|
||||
/// stroke width into new art, so new art's paint from before, the defaults a script set included,
|
||||
/// is put back.
|
||||
fn make(h: &super::Host, doc: Doc, container: Option<NodeId>, id: &str, params: &Value, reversed: bool) -> Answer {
|
||||
keeping_paint(h, || {
|
||||
make_in(h, doc, container, |h| {
|
||||
let parent = with_doc(h, doc, |_, st| new_path_layer(st));
|
||||
let id = made_id(&drawing_normally(h, parent, id, params)?)?;
|
||||
if reversed {
|
||||
@@ -814,10 +941,7 @@ fn make(h: &super::Host, doc: Doc, id: &str, params: &Value, reversed: bool) ->
|
||||
}
|
||||
Ok(id)
|
||||
})
|
||||
})?;
|
||||
let s = h.session.borrow();
|
||||
let st = s.documents().iter().find(|d| d.uid == doc.uid).ok_or_else(|| HostError::Error(super::STALE_DOCUMENT.into()))?;
|
||||
Ok(super::item_ref(h, st, made))
|
||||
})
|
||||
}
|
||||
|
||||
/// Argument `i`, or `default` when it is left out.
|
||||
@@ -858,13 +982,13 @@ fn corner(h: &super::Host, doc: Doc, left: f64, top: f64) -> std::result::Result
|
||||
|
||||
/// `rectangle(top, left, width, height, reversed?)`.
|
||||
fn items_rectangle(h: &super::Host, a: &[Data]) -> Answer {
|
||||
let doc = items_doc(h, a)?;
|
||||
let (doc, into) = items_scope(h, a)?;
|
||||
let top = coordinate(arg(a, 1), "top")?;
|
||||
let left = coordinate(arg(a, 2), "left")?;
|
||||
let (w, ht) = (size(a, 3, None, "width")?, size(a, 4, None, "height")?);
|
||||
let reversed = flag(a, 5, "reversed")?;
|
||||
let p = corner(h, doc, left, top)?;
|
||||
make(h, doc, "shape.rectangle", &json!({"x": p.x, "y": p.y, "width": w, "height": ht}), reversed)
|
||||
make(h, doc, into, "shape.rectangle", &json!({"x": p.x, "y": p.y, "width": w, "height": ht}), reversed)
|
||||
}
|
||||
|
||||
/// The anchors of a rectangle `r` with elliptical corners of radii `rx` and `ry`, clockwise on the
|
||||
@@ -904,7 +1028,7 @@ fn rounded(r: Rect, rx: f64, ry: f64) -> Vec<Anchor> {
|
||||
/// `roundedRectangle(top, left, width, height, horizontalRadius = 15, verticalRadius = 20,
|
||||
/// reversed = false)`: a closed path with `path.create`.
|
||||
fn items_rounded_rectangle(h: &super::Host, a: &[Data]) -> Answer {
|
||||
let doc = items_doc(h, a)?;
|
||||
let (doc, into) = items_scope(h, a)?;
|
||||
let top = coordinate(arg(a, 1), "top")?;
|
||||
let left = coordinate(arg(a, 2), "left")?;
|
||||
let (w, ht) = (size(a, 3, None, "width")?, size(a, 4, None, "height")?);
|
||||
@@ -912,12 +1036,12 @@ fn items_rounded_rectangle(h: &super::Host, a: &[Data]) -> Answer {
|
||||
let reversed = flag(a, 7, "reversed")?;
|
||||
let p = corner(h, doc, left, top)?;
|
||||
let anchors: Vec<Value> = rounded(Rect::new(p.x, p.y, p.x + w, p.y + ht), rx, ry).iter().map(anchor_json).collect();
|
||||
make(h, doc, "path.create", &json!({"anchors": anchors, "closed": true}), reversed)
|
||||
make(h, doc, into, "path.create", &json!({"anchors": anchors, "closed": true}), reversed)
|
||||
}
|
||||
|
||||
/// `ellipse(top = 100, left = 100, width = 50, height = 100, reversed = false, inscribed)`.
|
||||
fn items_ellipse(h: &super::Host, a: &[Data]) -> Answer {
|
||||
let doc = items_doc(h, a)?;
|
||||
let (doc, into) = items_scope(h, a)?;
|
||||
let top = given(arg(a, 1)).map_or(Ok(100.0), |d| coordinate(d, "top"))?;
|
||||
let left = given(arg(a, 2)).map_or(Ok(100.0), |d| coordinate(d, "left"))?;
|
||||
let (w, ht) = (size(a, 3, Some(50.0), "width")?, size(a, 4, Some(100.0), "height")?);
|
||||
@@ -926,7 +1050,7 @@ fn items_ellipse(h: &super::Host, a: &[Data]) -> Answer {
|
||||
return Err(HostError::Error("ellipse with inscribed true is not available yet".into()));
|
||||
}
|
||||
let p = corner(h, doc, left, top)?;
|
||||
make(h, doc, "shape.ellipse", &json!({"x": p.x, "y": p.y, "width": w, "height": ht}), reversed)
|
||||
make(h, doc, into, "shape.ellipse", &json!({"x": p.x, "y": p.y, "width": w, "height": ht}), reversed)
|
||||
}
|
||||
|
||||
/// The center of a polygon or star, in document coordinates.
|
||||
@@ -938,37 +1062,38 @@ fn center(h: &super::Host, doc: Doc, a: &[Data]) -> std::result::Result<Point, H
|
||||
|
||||
/// `polygon(centerX = 200, centerY = 300, radius = 50, sides = 8, reversed = false)`.
|
||||
fn items_polygon(h: &super::Host, a: &[Data]) -> Answer {
|
||||
let doc = items_doc(h, a)?;
|
||||
let (doc, into) = items_scope(h, a)?;
|
||||
let c = center(h, doc, a)?;
|
||||
let r = size(a, 3, Some(50.0), "radius")?;
|
||||
let sides = count(a, 4, 8.0, 3.0, 1000.0, "sides")?;
|
||||
let reversed = flag(a, 5, "reversed")?;
|
||||
make(h, doc, "shape.polygon", &json!({"cx": c.x, "cy": c.y, "radius": r, "sides": sides}), reversed)
|
||||
make(h, doc, into, "shape.polygon", &json!({"cx": c.x, "cy": c.y, "radius": r, "sides": sides}), reversed)
|
||||
}
|
||||
|
||||
/// `star(centerX = 200, centerY = 300, radius = 50, innerRadius = 20, points = 5, reversed =
|
||||
/// false)`.
|
||||
fn items_star(h: &super::Host, a: &[Data]) -> Answer {
|
||||
let doc = items_doc(h, a)?;
|
||||
let (doc, into) = items_scope(h, a)?;
|
||||
let c = center(h, doc, a)?;
|
||||
let r1 = size(a, 3, Some(50.0), "radius")?;
|
||||
let r2 = size(a, 4, Some(20.0), "innerRadius")?;
|
||||
let points = count(a, 5, 5.0, 2.0, 1000.0, "points")?;
|
||||
let reversed = flag(a, 6, "reversed")?;
|
||||
make(h, doc, "shape.star", &json!({"cx": c.x, "cy": c.y, "radius1": r1, "radius2": r2, "points": points}), reversed)
|
||||
make(h, doc, into, "shape.star", &json!({"cx": c.x, "cy": c.y, "radius1": r1, "radius2": r2, "points": points}), reversed)
|
||||
}
|
||||
|
||||
/// `pathItems.add()`: a path with no points on top of the active layer, from `path.create` with
|
||||
/// empty path data, painted as new art. When new art has no fill and no stroke, the black stroke `path.create` gives an open
|
||||
/// path is set back to none in the same step, and new art keeps the paint it had before.
|
||||
/// `pathItems.add()`: a path with no points on top of the active layer, or of the layer's or
|
||||
/// group's contents ([`make_in`]), from `path.create` with empty path data, painted as new art.
|
||||
/// When new art has no fill and no stroke, the black stroke `path.create` gives an open path is set
|
||||
/// back to none in the same step, and new art keeps the paint it had before.
|
||||
fn items_add(h: &super::Host, a: &[Data]) -> Answer {
|
||||
let doc = items_doc(h, a)?;
|
||||
let (doc, into) = items_scope(h, a)?;
|
||||
// New art's paint is read with the document active, since activating a document can load its
|
||||
// selection's appearance into new art. Selecting the new path loads its temporary stroke into
|
||||
// new art, and putting the selection back does not undo that, so new art's paint from before
|
||||
// the path is put back.
|
||||
let made = keeping_paint(h, || {
|
||||
on_doc(h, doc.uid, true, |h| {
|
||||
keeping_paint(h, || {
|
||||
make_in(h, doc, into, |h| {
|
||||
let unpainted = {
|
||||
let ap = h.session.borrow().new_art();
|
||||
ap.fill_paint().is_none() && ap.stroke_paint().is_none()
|
||||
@@ -980,10 +1105,7 @@ fn items_add(h: &super::Host, a: &[Data]) -> Answer {
|
||||
}
|
||||
Ok(id)
|
||||
})
|
||||
})?;
|
||||
let s = h.session.borrow();
|
||||
let st = s.documents().iter().find(|d| d.uid == doc.uid).ok_or_else(|| HostError::Error(super::STALE_DOCUMENT.into()))?;
|
||||
Ok(super::item_ref(h, st, made))
|
||||
})
|
||||
}
|
||||
|
||||
// ---- PathItem geometry ----
|
||||
@@ -1009,13 +1131,13 @@ fn path_closed(h: &super::Host, a: &[Data]) -> Answer {
|
||||
fn path_set_closed(h: &super::Host, a: &[Data]) -> Answer {
|
||||
let closed = boolean(arg(a, 1), "closed")?;
|
||||
let item = this_path(h, a)?;
|
||||
edit_points(h, item, |subs| {
|
||||
if subs.is_empty() && closed {
|
||||
subs.push(SubPath::new(Vec::new(), closed));
|
||||
} else {
|
||||
subs.iter_mut().for_each(|sp| sp.closed = closed);
|
||||
}
|
||||
})?;
|
||||
// A path with no subpath gets an empty closed one to keep the value in; any other change keeps
|
||||
// the number of points, so the kept starts of the waiting changes stay valid.
|
||||
if closed && read_points(h, item, |subs| subs.is_empty())? {
|
||||
edit_points(h, item, |subs| subs.push(SubPath::new(Vec::new(), closed)))?;
|
||||
} else {
|
||||
edit_points_keeping(h, item, true, |subs| subs.iter_mut().for_each(|sp| sp.closed = closed))?;
|
||||
}
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
@@ -2270,6 +2392,7 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
|
||||
("index", point_method(l, points_index), returns("PathPoint", &[("itemKey", "*")])),
|
||||
("add", point_method(l, points_add), returns("PathPoint", &[])),
|
||||
("removeAll", point_method(l, points_remove_all), returns("undefined", &[])),
|
||||
("toString", class_text("PathPoints"), returns("string", &[])),
|
||||
]),
|
||||
Some(super::point_function(l, points_at)),
|
||||
),
|
||||
@@ -2289,6 +2412,7 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
|
||||
typed("PathPointSelection"),
|
||||
),
|
||||
("remove", point_method(l, pt_remove), returns("undefined", &[])),
|
||||
("toString", class_text("PathPoint"), returns("string", &[])),
|
||||
]),
|
||||
None,
|
||||
),
|
||||
|
||||
@@ -2711,11 +2711,10 @@ impl Session {
|
||||
RunError { kind: RunErrorKind::Limit(kind), message: format!("limit reached: {kind:?}"), line: 0, column: 0, authored: false };
|
||||
return Some(self.script_failed(job, &e));
|
||||
}
|
||||
// One more allowance may still leave the growth past it: the person is asked again
|
||||
// while they may be, and past that the run ends unkept.
|
||||
if let Err(HostError::Abort(message)) = job.host.charge_growth(0, 0) {
|
||||
let e = RunError { kind: RunErrorKind::Limit(LimitKind::Host), message, line: 0, column: 0, authored: false };
|
||||
return Some(self.script_failed(job, &e));
|
||||
// What the script added must fit the allowance the last answer gave: past it, the
|
||||
// person is asked again, as a running script is at its next charge.
|
||||
if let Err(e) = job.host.charge_growth(0, 0) {
|
||||
return Some(self.script_failed(job, &end_flush_error(e)));
|
||||
}
|
||||
if job.host.waiting.get() {
|
||||
JOBS.with(|jobs| jobs.borrow_mut().insert(key.id, job));
|
||||
@@ -2749,14 +2748,24 @@ impl Session {
|
||||
self.script_key = Some(key);
|
||||
None
|
||||
}
|
||||
// The point changes written as the script ended went past the growth allowance.
|
||||
Ok(Ok(Progress::Done(_))) if job.host.waiting.get() => {
|
||||
job.finished = true;
|
||||
JOBS.with(|jobs| jobs.borrow_mut().insert(key.id, job));
|
||||
self.script_key = Some(key);
|
||||
None
|
||||
Ok(Ok(Progress::Done(_))) => {
|
||||
// What the script added must fit the allowance the last answer gave, which one
|
||||
// answer can leave short of what the script had already added.
|
||||
if !job.host.waiting.get()
|
||||
&& let Err(e) = job.host.charge_growth(0, 0)
|
||||
{
|
||||
return Some(self.script_failed(job, &end_flush_error(e)));
|
||||
}
|
||||
// The point changes written as the script ended, or what it added before, went past
|
||||
// the growth allowance.
|
||||
if job.host.waiting.get() {
|
||||
job.finished = true;
|
||||
JOBS.with(|jobs| jobs.borrow_mut().insert(key.id, job));
|
||||
self.script_key = Some(key);
|
||||
return None;
|
||||
}
|
||||
Some(self.script_ended(job))
|
||||
}
|
||||
Ok(Ok(Progress::Done(_))) => Some(self.script_ended(job)),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -14,3 +14,6 @@ mod documents;
|
||||
mod edit;
|
||||
mod execute;
|
||||
mod undo;
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) use edit::previews_run;
|
||||
@@ -165,6 +165,8 @@ impl Session {
|
||||
liquify_stroke: None,
|
||||
plane_widget_press: false,
|
||||
pointer_held: false,
|
||||
holds_previews: false,
|
||||
sampled_preview: None,
|
||||
press_options: None,
|
||||
press_options_stored: false,
|
||||
press_type_selection: None,
|
||||
|
||||
@@ -4,6 +4,18 @@ use super::{
|
||||
};
|
||||
use crate::doc_state::{kept_from, objects_only};
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// How many times [`Session::preview`] ran on this thread.
|
||||
static PREVIEWS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// How many times [`Session::preview`] has run on this thread.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn previews_run() -> usize {
|
||||
PREVIEWS.get()
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// Takes committed swatch renames as (document uid, old name, new name) in execution order and leaves the record empty.
|
||||
/// The uid identifies the originating document through [`crate::DocState::uid`].
|
||||
@@ -583,6 +595,8 @@ impl Session {
|
||||
|
||||
/// Re-apply `cmd` on top of the interaction snapshot (replacing the previous preview).
|
||||
pub fn preview(&mut self, cmd: &str, params: &Value) -> Result<Value> {
|
||||
#[cfg(test)]
|
||||
PREVIEWS.set(PREVIEWS.get() + 1);
|
||||
self.put_back_interaction();
|
||||
if self.script_running() {
|
||||
return Err(EngineError::Busy);
|
||||
|
||||
@@ -320,6 +320,192 @@ fn pencil_continues_selected_open_path() {
|
||||
assert_eq!(p.subpaths[0].anchors[0].p, Point::new(100.0, 100.0));
|
||||
}
|
||||
|
||||
/// The document without its creation time, the selection and the new-art paints.
|
||||
type Drawn = (vectorcraft_doc::Document, vectorcraft_doc::Selection, vectorcraft_tools::PaintDefaults);
|
||||
|
||||
fn drawn(s: &Session) -> Drawn {
|
||||
let st = s.doc().unwrap();
|
||||
let mut doc = (*st.doc).clone();
|
||||
// `file.new` stamps the time in seconds, which differs between two sessions made a second apart.
|
||||
doc.metadata.created = None;
|
||||
(doc, st.selection.clone(), s.paint.clone())
|
||||
}
|
||||
|
||||
/// Draws `pts` with the Pencil in a session that `setup` prepared, handing the drag's samples and the release to the
|
||||
/// session in groups of 4, the release in the last group: through [`Session::pointer_samples`] with `by_frame`, else
|
||||
/// one at a time through [`Session::pointer`]. What [`drawn`] gives after each group, the previews each group ran,
|
||||
/// and the previews a group runs when its drags preview once: one for its drags and one for its release.
|
||||
fn pencil_in_frames(setup: &dyn Fn(&mut Session), pts: &[(f64, f64)], by_frame: bool) -> (Vec<Drawn>, Vec<usize>, Vec<usize>) {
|
||||
let mut s = session();
|
||||
setup(&mut s);
|
||||
let v = view();
|
||||
s.select_tool("pencil", v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, pts[0].0, pts[0].1), v).unwrap();
|
||||
let mut samples: Vec<PointerEvent> = pts[1..].iter().map(|&(x, y)| PointerEvent::new(PointerKind::Drag, x, y)).collect();
|
||||
let l = pts[pts.len() - 1];
|
||||
samples.push(PointerEvent::new(PointerKind::Up, l.0, l.1));
|
||||
let (mut states, mut previews, mut once) = (vec![], vec![], vec![]);
|
||||
for group in samples.rchunks(4).rev() {
|
||||
let has = |kind| usize::from(group.iter().any(|ev| ev.kind == kind));
|
||||
once.push(has(PointerKind::Drag) + has(PointerKind::Up));
|
||||
let before = crate::session::previews_run();
|
||||
if by_frame {
|
||||
let (fed, r) = s.pointer_samples(group, v);
|
||||
r.unwrap();
|
||||
assert_eq!(fed, group.len(), "every sample fed");
|
||||
} else {
|
||||
for ev in group {
|
||||
s.pointer(ev, v).unwrap();
|
||||
}
|
||||
}
|
||||
previews.push(crate::session::previews_run() - before);
|
||||
states.push(drawn(&s));
|
||||
}
|
||||
(states, previews, once)
|
||||
}
|
||||
|
||||
/// The drag samples of a frame of up to 4 Pencil samples run one preview, the last sample's, before the release when
|
||||
/// the frame ends with it, and leave the document, the selection and the new-art paints as handing the samples over one
|
||||
/// by one does, after every frame: for a new stroke, for strokes that continue a selected path at its end and at its
|
||||
/// start, and with New Art Has Basic Appearance off and an empty starting selection. Every sample is previewed when
|
||||
/// inheriting a selected gradient, with two selected paths in a group, during a Global Edit, or with Objects on Path selected.
|
||||
#[test]
|
||||
fn pencil_samples_of_one_frame_run_one_preview() {
|
||||
let none = |_: &mut Session| {};
|
||||
let selected_line = |s: &mut Session| {
|
||||
line(s, 100.0, 100.0, 200.0, 100.0);
|
||||
};
|
||||
let not_basic = |s: &mut Session| {
|
||||
rect(s, 400.0, 400.0, 50.0, 50.0);
|
||||
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
|
||||
s.execute("appearance.setNewArtBasic", &json!({"on": false})).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
};
|
||||
let selected_gradient = |s: &mut Session| {
|
||||
rect(s, 400.0, 400.0, 50.0, 50.0);
|
||||
s.execute("paint.setFill", &json!({"gradient": {"kind": "linear", "start": [400, 400], "end": [400, 450]}})).unwrap();
|
||||
s.execute("appearance.setNewArtBasic", &json!({"on": false})).unwrap();
|
||||
s.select_tool("pencil", view()).unwrap();
|
||||
s.set_tool_option("fill", &json!(true));
|
||||
s.set_tool_option("keepSelected", &json!(true));
|
||||
};
|
||||
let grouped_paths = |s: &mut Session| {
|
||||
let a = line(s, 100.0, 100.0, 200.0, 100.0);
|
||||
let b = line(s, 400.0, 200.0, 420.0, 200.0);
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
s.execute("object.group", &json!({})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
};
|
||||
let new_stroke = wave(100.0, 180.0, 300.0);
|
||||
let wavy =
|
||||
|x0: f64, step: f64| -> Vec<(f64, f64)> { (0..=40).map(|i| (x0 + step * f64::from(i), 101.0 + 10.0 * (f64::from(i) / 6.0).sin())).collect() };
|
||||
let (past_end, before_start) = (wavy(202.0, 2.0), wavy(99.0, -2.0));
|
||||
// A Global Edit preview also changes the other members, which the tool reads for its next sample.
|
||||
let global_edit = |s: &mut Session| {
|
||||
let a = line(s, 100.0, 100.0, 200.0, 100.0);
|
||||
line(s, 100.0, 140.0, 200.0, 140.0);
|
||||
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
|
||||
assert_eq!(s.execute("select.globalEdit", &json!({})).unwrap()["active"], true);
|
||||
};
|
||||
// Continuing the spine of an Objects on Path group moves the attached art, so every sample is previewed.
|
||||
let objects_on_path = |s: &mut Session| {
|
||||
let spine = line(s, 100.0, 100.0, 200.0, 100.0);
|
||||
let attached = line(s, 400.0, 200.0, 420.0, 200.0);
|
||||
s.execute("object.objectsOnPath.attach", &json!({"path": spine.0, "ids": [attached.0]})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [spine.0]})).unwrap();
|
||||
};
|
||||
// The name, the setup, the stroke, the paths after the release, and whether a frame previews once.
|
||||
type Case<'a> = (&'a str, &'a dyn Fn(&mut Session), &'a [(f64, f64)], usize, bool);
|
||||
let cases: [Case; 8] = [
|
||||
("new stroke", &none, &new_stroke, 1, true),
|
||||
("continues the end", &selected_line, &past_end, 1, true),
|
||||
("continues the start", &selected_line, &before_start, 1, true),
|
||||
("basic appearance off", ¬_basic, &new_stroke, 2, true),
|
||||
(
|
||||
"inherits a selected gradient",
|
||||
&selected_gradient,
|
||||
&[(100.0, 180.0), (120.0, 180.0), (140.0, 180.0), (160.0, 200.0), (180.0, 220.0), (200.0, 230.0)],
|
||||
2,
|
||||
false,
|
||||
),
|
||||
("two selected paths in a group", &grouped_paths, &past_end, 2, false),
|
||||
("global edit", &global_edit, &past_end, 2, false),
|
||||
("objects on path", &objects_on_path, &past_end, 2, false),
|
||||
];
|
||||
for (name, setup, pts, path_count, once) in cases {
|
||||
let (one_by_one, each, _) = pencil_in_frames(setup, pts, false);
|
||||
let (by_frames, previews, expected) = pencil_in_frames(setup, pts, true);
|
||||
if once {
|
||||
assert_eq!(previews, expected, "{name}: one preview for the drags of a frame, and one for its release");
|
||||
} else {
|
||||
assert_eq!(previews, each, "{name}: a preview per sample");
|
||||
}
|
||||
assert_eq!(by_frames.len(), one_by_one.len(), "{name}");
|
||||
for (k, (a, b)) in by_frames.iter().zip(&one_by_one).enumerate() {
|
||||
assert!(a == b, "{name}: state {k} differs from handing the samples over one by one");
|
||||
}
|
||||
let mut paths = 0;
|
||||
by_frames[by_frames.len() - 1].0.walk(|n| paths += usize::from(matches!(n.kind, NodeKind::Path { .. })));
|
||||
assert_eq!(paths, path_count, "{name}: paths after the release");
|
||||
}
|
||||
}
|
||||
|
||||
/// One call that carries a Pencil release and the next stroke's press and drags previews every drag of the second
|
||||
/// stroke when that stroke begins with the first one selected and New Art Has Basic Appearance off, and leaves the
|
||||
/// document, the selection and the new-art paints as handing the events over one by one does.
|
||||
#[test]
|
||||
fn pencil_samples_spanning_two_strokes_decide_again_after_the_press() {
|
||||
let v = view();
|
||||
let setup = || {
|
||||
let mut s = session();
|
||||
rect(&mut s, 400.0, 400.0, 50.0, 50.0);
|
||||
s.execute("paint.setFill", &json!({"gradient": {"kind": "linear", "start": [400, 400], "end": [400, 450]}})).unwrap();
|
||||
s.execute("appearance.setNewArtBasic", &json!({"on": false})).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
s.select_tool("pencil", v).unwrap();
|
||||
s.set_tool_option("fill", &json!(true));
|
||||
s.set_tool_option("keepSelected", &json!(true));
|
||||
assert!(s.doc().unwrap().selection.is_empty());
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 100.0), v).unwrap();
|
||||
for (x, y) in [(120.0, 100.0), (140.0, 120.0), (160.0, 130.0)] {
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, x, y), v).unwrap();
|
||||
}
|
||||
s
|
||||
};
|
||||
let mut batched = setup();
|
||||
let mut individual = setup();
|
||||
let mut samples = vec![PointerEvent::new(PointerKind::Up, 160.0, 130.0), PointerEvent::new(PointerKind::Down, 100.0, 220.0)];
|
||||
let drags = [
|
||||
(120.0, 220.0),
|
||||
(140.0, 220.0),
|
||||
(160.0, 220.0),
|
||||
(180.0, 220.0),
|
||||
(200.0, 220.0),
|
||||
(220.0, 240.0),
|
||||
(240.0, 260.0),
|
||||
(260.0, 280.0),
|
||||
(280.0, 290.0),
|
||||
(300.0, 300.0),
|
||||
];
|
||||
samples.extend(drags.iter().map(|&(x, y)| PointerEvent::new(PointerKind::Drag, x, y)));
|
||||
let before = crate::session::previews_run();
|
||||
let (fed, result) = batched.pointer_samples(&samples, v);
|
||||
result.unwrap();
|
||||
let batched_previews = crate::session::previews_run() - before;
|
||||
assert_eq!(fed, samples.len(), "every sample fed");
|
||||
let before = crate::session::previews_run();
|
||||
individual.pointer(&samples[0], v).unwrap();
|
||||
let release_previews = crate::session::previews_run() - before;
|
||||
assert!(!individual.doc().unwrap().selection.is_empty());
|
||||
for ev in &samples[1..] {
|
||||
individual.pointer(ev, v).unwrap();
|
||||
}
|
||||
let individual_previews = crate::session::previews_run() - before;
|
||||
assert_eq!(individual_previews, drags.len() + release_previews, "each drag runs a preview");
|
||||
assert_eq!(batched_previews, individual_previews, "the batch runs every preview");
|
||||
assert!(drawn(&batched) == drawn(&individual), "document, selection and new-art paints match");
|
||||
}
|
||||
|
||||
/// Connect two paths: with two open paths selected, a Pencil stroke from an end of one to an end
|
||||
/// of the other joins them into one path, the first one's, in one undo step. A path that is not
|
||||
/// selected is not joined.
|
||||
|
||||
@@ -443,6 +443,55 @@ fn alt_drag_of_30000_objects_takes_few_tree_walks() {
|
||||
undo_gives_back(&mut s, &before);
|
||||
}
|
||||
|
||||
/// A Pencil stroke of 100 moves over 20,000 squares previews the path at every move. Each preview
|
||||
/// starts again from the document as it was at the press, whose lookup cache does not hold the new
|
||||
/// path; the first preview finds the path by walking the tree, and the later ones find it at the
|
||||
/// place that walk found. The release leaves one new path, selected, as one undo step; Group puts it
|
||||
/// in a group, and Undo puts it back and then removes it. A stroke canceled part way leaves no path.
|
||||
#[test]
|
||||
fn pencil_previews_find_the_new_path_without_walking_the_tree() {
|
||||
let mut s = session(20_000, square);
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let first = before.peek_next_id();
|
||||
let v = ViewInfo { smart_guides: false, ..ViewInfo::default() };
|
||||
s.select_tool("pencil", v).unwrap();
|
||||
let at = |kind, i: usize| PointerEvent::new(kind, 10.0 + 3.0 * i as f64, 50.0 + 20.0 * (i as f64 / 10.0).sin());
|
||||
s.pointer(&at(PointerKind::Down, 0), v).unwrap();
|
||||
s.pointer(&at(PointerKind::Drag, 1), v).unwrap();
|
||||
let (walks, revision) = (vectorcraft_doc::tree_walks(), s.doc().unwrap().revision);
|
||||
for i in 2..=100 {
|
||||
s.pointer(&at(PointerKind::Drag, i), v).unwrap();
|
||||
}
|
||||
let (walks, previews) = (vectorcraft_doc::tree_walks() - walks, (s.doc().unwrap().revision - revision) / 2);
|
||||
assert!(previews >= 99, "{previews} previews for 99 moves");
|
||||
assert!(walks <= 2, "{previews} previews walked the tree {walks} times");
|
||||
s.pointer(&at(PointerKind::Up, 100), v).unwrap();
|
||||
let path = NodeId(first);
|
||||
assert_eq!(layer(&s, 0).len(), 20_001);
|
||||
assert!(s.doc().unwrap().doc.node(path).is_some_and(|n| matches!(n.kind, NodeKind::Path { .. })));
|
||||
assert!(selected(&s, &[path]));
|
||||
let layer_id = before.layers[0].id;
|
||||
let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
assert_eq!(s.doc().unwrap().doc.ancestry(path), Some(vec![layer_id, group, path]));
|
||||
assert_eq!(children(&s, group), [path]);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.ancestry(path), Some(vec![layer_id, path]));
|
||||
assert!(s.doc().unwrap().doc.node(group).is_none());
|
||||
undo_gives_back(&mut s, &before);
|
||||
assert!(s.doc().unwrap().doc.node(path).is_none());
|
||||
|
||||
// The same stroke, canceled after 50 moves.
|
||||
s.pointer(&at(PointerKind::Down, 0), v).unwrap();
|
||||
for i in 1..=50 {
|
||||
s.pointer(&at(PointerKind::Drag, i), v).unwrap();
|
||||
}
|
||||
assert!(s.doc().unwrap().doc.node(path).is_some(), "the preview holds the path");
|
||||
s.cancel_interaction().unwrap();
|
||||
assert!(*s.doc().unwrap().doc == *before, "Cancel gives back the document");
|
||||
assert!(s.doc().unwrap().doc.node(path).is_none() && s.doc().unwrap().doc.index_path(path).is_none());
|
||||
}
|
||||
|
||||
/// The ids under `n`: a child that can hold children is a list of its id and theirs.
|
||||
fn outline(n: &Node) -> Value {
|
||||
let ids = n.children().into_iter().flatten().map(|c| match c.children() {
|
||||
|
||||
@@ -76,6 +76,27 @@ fn missing_link_markers_follow_files_relink_update_and_embed() {
|
||||
assert!(marked(&mut s).is_empty());
|
||||
}
|
||||
|
||||
/// A caller confined to other folders sees a linked file outside them as missing, but its answer
|
||||
/// does not replace the markers drawn on the canvas.
|
||||
#[test]
|
||||
fn a_confined_marked_query_leaves_the_canvas_markers_alone() {
|
||||
let dir = Folder::new("marker-confined");
|
||||
let path = dir.file("art.png");
|
||||
write(&path, &png(40, 40, RED));
|
||||
let other = dir.0.join("other");
|
||||
std::fs::create_dir_all(&other).unwrap();
|
||||
let mut s = session();
|
||||
let id = place(&mut s, &path);
|
||||
s.execute("view.showMissingLinks", &json!({"on": true})).unwrap();
|
||||
assert!(marked(&mut s).is_empty());
|
||||
let roots = crate::file_access::AutomationRoots::new(&[other.as_path()], &[]).unwrap();
|
||||
assert_eq!(crate::file_access::confine(roots.as_ref(), || marked(&mut s)), vec![id.0], "the caller cannot read the file");
|
||||
assert!(s.doc().unwrap().marked_missing_links().is_empty(), "the canvas keeps no marker for a file that is there");
|
||||
std::fs::remove_file(&path).unwrap();
|
||||
assert_eq!(marked(&mut s), vec![id.0]);
|
||||
assert_eq!(s.doc().unwrap().marked_missing_links(), vec![id]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_link_worker_refreshes_without_the_panel_and_ignores_old_art() {
|
||||
for mode in ["automatically", "askWhenModified", "manually"] {
|
||||
|
||||
@@ -558,6 +558,22 @@ fn align_new_objects_to_pixel_grid_follows_the_preset() {
|
||||
assert!(!align(&old));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn saved_rows_past_the_limit_read_as_the_limit_and_others_stay() {
|
||||
let mut s = Session::new();
|
||||
let saved = json!({"newDocPresets": [
|
||||
{"name": "Many", "width": 100, "height": 100, "artboards": 2, "layout": "gridByColumn", "rows": 1001},
|
||||
{"name": "Four", "width": 100, "height": 100, "artboards": 2, "layout": "gridByColumn", "rows": 4},
|
||||
]});
|
||||
s.apply_prefs(serde_json::from_value(saved).unwrap());
|
||||
for (name, rows) in [("Many", 1000), ("Four", 4)] {
|
||||
let layout = presets(&mut s, "Saved").iter().find(|p| p["name"] == name).unwrap()["artboardLayout"].clone();
|
||||
assert_eq!(layout["rows"], json!(rows), "{name}");
|
||||
// `file.new` takes the layout `file.newPresets` lists.
|
||||
s.execute("file.new", &json!({"preset": name, "artboardLayout": layout})).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rearrange_keeps_its_grid() {
|
||||
let mut s = new_doc(json!({"width": 100, "height": 50, "artboards": 3}));
|
||||
|
||||
@@ -1136,6 +1136,30 @@ fn new_art_on_a_locked_artboard_stays_editable_until_the_selection_leaves_it() {
|
||||
batches_and_isolation_keep_new_art_protected(&mut s, pasted);
|
||||
}
|
||||
|
||||
/// A compound path pasted onto a locked artboard takes a path through node.move while it is still
|
||||
/// selected, and is refused as a destination once the selection leaves it out.
|
||||
#[test]
|
||||
fn node_move_into_new_compound_path_on_a_locked_artboard() {
|
||||
let mut s = session();
|
||||
let p = rect(&mut s);
|
||||
let q = NodeId(s.execute("shape.rectangle", &json!({"x": 10, "y": 200, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap());
|
||||
let c = NodeId(s.execute("shape.rectangle", &json!({"x": 300, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap());
|
||||
let e = NodeId(s.execute("shape.rectangle", &json!({"x": 340, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("select.set", &json!({"ids": [c.0, e.0]})).unwrap();
|
||||
s.execute("edit.copy", &json!({})).unwrap();
|
||||
s.execute("artboard.new", &json!({"x": 1000, "y": 0, "width": 400, "height": 400})).unwrap();
|
||||
s.execute("artboard.setProps", &json!({"index": 1, "locked": true})).unwrap();
|
||||
let pasted = ids(&s.execute("edit.paste", &json!({"center": [1200, 200]})).unwrap()["ids"]);
|
||||
assert_eq!(pasted.len(), 2);
|
||||
let compound = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap();
|
||||
assert_eq!(s.doc().unwrap().selection.objects.iter().map(|id| id.0).collect::<Vec<_>>(), [compound], "the new compound path is selected");
|
||||
s.execute("node.move", &json!({"id": p.0, "parent": compound, "index": 0})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(p), Some(NodeId(compound)), "new art takes the path");
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
assert!(s.execute("node.move", &json!({"id": q.0, "parent": compound, "index": 0})).is_err(), "no longer new art");
|
||||
assert_ne!(s.doc().unwrap().doc.parent_of(q), Some(NodeId(compound)));
|
||||
}
|
||||
|
||||
/// The batch, isolation and group cases of [`new_art_on_a_locked_artboard_stays_editable_until_the_selection_leaves_it`],
|
||||
/// with the pasted art `pasted` selected.
|
||||
fn batches_and_isolation_keep_new_art_protected(s: &mut Session, pasted: Vec<u64>) {
|
||||
|
||||
@@ -1878,6 +1878,32 @@ fn a_page_item_with_a_large_id_keeps_its_id() {
|
||||
assert!(s.active().unwrap().doc.node(a).is_none());
|
||||
}
|
||||
|
||||
/// A path the script makes keeps its id when the id is past 2^53, where the script's numbers round.
|
||||
#[test]
|
||||
fn a_path_made_with_a_large_id_keeps_its_id() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
let big = (1u64 << 53) + 1;
|
||||
s.active_mut().unwrap().change_unsaved(|d| std::sync::Arc::make_mut(d).raise_next_id(big));
|
||||
let out = log(&mut s, "var p = app.activeDocument.pathItems.rectangle(10, 10, 20, 20); p.name = 'big'; vc.log(p.name);");
|
||||
assert_eq!(out, vec![json!("big")]);
|
||||
let d = &s.active().unwrap().doc;
|
||||
assert_eq!(d.node(NodeId(big)).and_then(|n| n.name.clone()).as_deref(), Some("big"));
|
||||
}
|
||||
|
||||
/// Assigning `undefined` to the selection, as a lookup past the end of a list gives, throws and
|
||||
/// leaves the selection as it was; `null` still clears it.
|
||||
#[test]
|
||||
fn assigning_undefined_to_the_selection_throws() {
|
||||
let (mut s, a, _) = doc();
|
||||
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
|
||||
let e = failure(&mut s, "var d = app.activeDocument; d.selection = d.pageItems[99];");
|
||||
assert!(e.contains("TypeError") || e.contains("not undefined"), "{e}");
|
||||
assert_eq!(s.active().unwrap().selection.objects, vec![a]);
|
||||
log(&mut s, "app.activeDocument.selection = null;");
|
||||
assert!(s.active().unwrap().selection.objects.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_class_constructors_construct() {
|
||||
let (mut s, _, _) = doc();
|
||||
@@ -2023,14 +2049,41 @@ fn note_is_the_attributes_note() {
|
||||
assert!(failure(&mut s, "app.activeDocument.pageItems[0].note = new Array(5000).join('n');").contains("too long"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn add_document_starts_from_the_built_in_preset_when_a_saved_one_has_its_name() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.newPresets.save", &json!({"name": "Letter", "width": 100, "height": 50, "colorMode": "rgb"})).unwrap();
|
||||
let out = log(&mut s, "var d = app.documents.addDocument('Print'); vc.log([d.width, d.height, d.documentColorSpace]);");
|
||||
assert_eq!(out[0], json!([612, 792, "DocumentColorSpace.CMYK"]));
|
||||
// Recent keeps the built-in preset's name, as it does when no saved preset has it.
|
||||
assert_eq!(s.prefs.recent_new_docs[0].name, "Letter");
|
||||
let out = log(&mut s, "var p = new DocumentPreset(); p.width = 300; var e = app.documents.addDocument('Print', p); vc.log([e.width, e.height]);");
|
||||
assert_eq!(out[0], json!([300, 792]));
|
||||
assert_eq!(s.prefs.recent_new_docs[0].name, "Custom");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_profile_starts_from_its_built_in_preset_and_not_a_saved_one_of_the_same_name() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.newPresets.save", &json!({"name": "Letter", "width": 100, "height": 50, "units": "Millimeters", "colorMode": "rgb"})).unwrap();
|
||||
s.execute(
|
||||
"file.newPresets.save",
|
||||
&json!({"name": "Letter", "width": 100, "height": 50, "units": "Millimeters", "colorMode": "rgb", "artboardLayout": "row"}),
|
||||
)
|
||||
.unwrap();
|
||||
let out = log(&mut s, "var d = app.documents.addDocument('Print'); vc.log([d.width, d.height, d.documentColorSpace]);");
|
||||
assert_eq!(out, vec![json!([612, 792, "DocumentColorSpace.CMYK"])]);
|
||||
let out = log(&mut s, "var p = new DocumentPreset(); p.width = 300; var d = app.documents.addDocument('Print', p); vc.log([d.width, d.height]);");
|
||||
assert_eq!(out, vec![json!([300, 792])], "presetSettings goes over the built-in preset");
|
||||
// Several artboards are laid out as the built-in preset lays them out when no saved preset
|
||||
// has its name, and the title is kept.
|
||||
let three = "var p = new DocumentPreset(); p.numArtboards = 3; p.title = 'Three';\
|
||||
p.artboardLayout = undefined; p.artboardRowsOrCols = undefined; p.artboardSpacing = undefined; var d = app.documents.addDocument('Print', p);\
|
||||
var r = []; for (var i = 0; i < d.artboards.length; i++) r.push(d.artboards[i].artboardRect); vc.log([d.name, r]);";
|
||||
let out = log(&mut s, three);
|
||||
let unshadowed = log(&mut Session::new(), three);
|
||||
assert_eq!(out[0][0], json!("Three"));
|
||||
assert_eq!(out[0][1].as_array().map(Vec::len), Some(3), "{out:?}");
|
||||
assert_eq!(out, unshadowed, "the saved preset changes nothing");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -2511,6 +2564,57 @@ fn wrappers_go_stale_after_revert() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A layer's collections read before File › Revert do not list the loaded document's art, even
|
||||
/// where the loaded layer has the same id.
|
||||
#[test]
|
||||
fn a_layers_collections_read_before_a_revert_are_stale() {
|
||||
let (mut s, ..) = doc();
|
||||
let folder = vectorcraft_testkit::TempDir::new("script-dom-revert-lists");
|
||||
let path = folder.join("saved.vectorcraft");
|
||||
s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap();
|
||||
for list in ["pathItems", "pageItems", "groupItems", "compoundPathItems", "layers"] {
|
||||
let source = format!(
|
||||
"var d = app.activeDocument, c = d.layers[0].{list}; vc.log(c.length >= 0); d.pageItems[0].name = 'changed'; vc.run('file.revert');\
|
||||
try {{ c.length; vc.log('ran'); }} catch (e) {{ vc.log('stale'); }} vc.log(d.layers[0].{list}.length >= 0);"
|
||||
);
|
||||
assert_eq!(log(&mut s, &source), vec![json!(true), json!("stale"), json!(true)], "{list}");
|
||||
}
|
||||
}
|
||||
|
||||
/// An artboard read before File › Revert is stale, even though the loaded artboard has the same
|
||||
/// id; the document's `artboards` read before it lists the loaded ones.
|
||||
#[test]
|
||||
fn an_artboard_read_before_a_revert_is_stale() {
|
||||
let (mut s, ..) = doc();
|
||||
let folder = vectorcraft_testkit::TempDir::new("script-dom-revert-artboard");
|
||||
let path = folder.join("saved.vectorcraft");
|
||||
s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var d = app.activeDocument, bs = d.artboards, b = bs[0], saved = b.name; b.name = 'changed'; vc.run('file.revert');\
|
||||
try { b.name = 'wrong'; vc.log('ran'); } catch (e) { vc.log(e.message); } vc.log(bs[0].name == saved);",
|
||||
);
|
||||
assert_eq!(out, vec![json!("Stale artboard"), json!(true)]);
|
||||
}
|
||||
|
||||
/// A key that is the text of a number but not an array index reaches an indexer as a number, and
|
||||
/// a layer's collections and `artboards` look it up as a name, as the document's `pageItems` does.
|
||||
/// `index()` still takes a number as a position.
|
||||
#[test]
|
||||
fn scoped_collections_find_names_that_are_numbers() {
|
||||
let (mut s, ..) = doc();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var d = app.activeDocument, l = d.layers[0], i = l.pageItems[0]; i.name = '-1'; l.layers.add().name = '1.5';\
|
||||
d.artboards[0].name = '-1';\
|
||||
vc.log(l.pageItems['-1'] === i); vc.log(l.pathItems['-1'] === i); vc.log(l.layers['1.5'].name);\
|
||||
vc.log(d.artboards['-1'].name); vc.log(l.pageItems['-2'] === undefined); vc.log(l.pageItems.index(0) === i);\
|
||||
try { l.pageItems.index(-1); vc.log('ran'); } catch (e) { vc.log(e.message); }\
|
||||
try { d.artboards.index(-1); vc.log('ran'); } catch (e) { vc.log(e.message); }",
|
||||
);
|
||||
assert_eq!(out, vec![json!(true), json!(true), json!("1.5"), json!("-1"), json!(true), json!(true), json!("Not found"), json!("Not found")]);
|
||||
}
|
||||
|
||||
/// A layer's or group's `pageItems` reads a name, `index` and `toString` as the document's does.
|
||||
#[test]
|
||||
fn a_layers_page_items_read_names_as_the_documents_do() {
|
||||
@@ -2697,6 +2801,9 @@ fn scoped_remove_all_refuses_art_on_a_locked_artboard() {
|
||||
"app.activeDocument.groupItems.getByName('locked').pageItems",
|
||||
"app.activeDocument.layers[0].compoundPathItems",
|
||||
"app.activeDocument.compoundPathItems",
|
||||
"app.activeDocument.pathItems",
|
||||
"app.activeDocument.groupItems.getByName('locked').pathItems",
|
||||
"app.activeDocument.compoundPathItems[0].pathItems",
|
||||
] {
|
||||
// The error is caught, so the run keeps whatever `removeAll()` did before it threw.
|
||||
let out = log(&mut s, &format!("var m = ''; try {{ {scope}.removeAll(); }} catch (e) {{ m = e.message; }} vc.log(m);"));
|
||||
@@ -3021,6 +3128,18 @@ fn an_unknown_menu_command_throws_and_names_it() {
|
||||
assert!(failure(&mut s, "app.executeMenuCommand('acmeNoSuchMenu');").contains("acmeNoSuchMenu"));
|
||||
}
|
||||
|
||||
/// `getIsFileOpen` folds `\` into `/` and letter case only by Windows' rules: on macOS and Linux a
|
||||
/// `\` is part of a file name, so `a\b.svg` is not the file `b.svg` in the folder `a`.
|
||||
#[test]
|
||||
fn get_is_file_open_compares_paths_by_the_platform_s_rules() {
|
||||
use crate::script::dom::path_key_on;
|
||||
assert_ne!(path_key_on("/tmp/work/a\\b.svg", false), path_key_on("/tmp/work/a/b.svg", false));
|
||||
assert_ne!(path_key_on("/tmp/work/A.svg", false), path_key_on("/tmp/work/a.svg", false));
|
||||
assert_eq!(path_key_on("/tmp/work/", false), path_key_on("/tmp/work", false));
|
||||
assert_eq!(path_key_on("C:\\Work\\A.svg", true), path_key_on("c:/work/a.svg", true));
|
||||
assert_eq!(path_key_on("C:\\Work\\", true), path_key_on("c:/work", true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_dom_values_do_not_reenter_or_exceed_limits() {
|
||||
let (mut s, _, _) = doc();
|
||||
@@ -3312,6 +3431,202 @@ fn a_layers_and_a_groups_lists_give_the_topmost_object_first() {
|
||||
assert_eq!(out, [json!("GroupItem"), json!("CompoundPathItem"), json!(70), json!(50), json!("E"), json!("E"), json!(30)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_layers_and_a_groups_path_items_list_only_the_paths_directly_in_them_topmost_first() {
|
||||
let (mut s, _, b) = doc();
|
||||
let c = rect(&mut s, 200.0, 100.0, 70.0, 20.0);
|
||||
s.execute("select.set", &json!({"ids": [b.0, c.0]})).unwrap();
|
||||
s.execute("object.group", &json!({})).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
// The layer holds `a` (30 pt wide) and a group of `b` (50 pt wide) and `c` (70 pt wide); the
|
||||
// document's list holds all three, the layer's only `a`, and a sublayer's path is its own.
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var d = app.activeDocument, L = d.layers[0], g = L.groupItems[0], P = L.pathItems, G = g.pathItems;\
|
||||
vc.log(P.length); vc.log(P[0].width); vc.log(P.typename); vc.log(P.parent.typename);\
|
||||
vc.log(G.length); vc.log(G[0].width); vc.log(G[1].width); vc.log(G.parent.typename); vc.log(d.pathItems.length);\
|
||||
var sub = L.layers.add(); sub.pathItems.rectangle(10, 10, 5, 5); vc.log(L.pathItems.length); vc.log(sub.pathItems.length);\
|
||||
sub.pathItems[0].name = 'B'; P[0].name = 'B'; G[1].name = 'B'; G[0].name = 'B';\
|
||||
vc.log(G.getByName('B') === G[0]); vc.log(G.index('B') === G[0]); vc.log(P.getByName('B') === P[0]); vc.log(P[1] === undefined);",
|
||||
);
|
||||
let expected =
|
||||
[json!(1), json!(30), json!("PathItems"), json!("Layer"), json!(2), json!(70), json!(50), json!("GroupItem"), json!(3), json!(1), json!(1)];
|
||||
assert_eq!(out[..11], expected);
|
||||
// With the sublayer's path above the group, the layer's own path and both of the group's paths
|
||||
// named `B`, each collection's named lookups give its own topmost path.
|
||||
assert_eq!(out[11..], [json!(true), json!(true), json!(true), json!(true)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_loop_over_a_groups_path_items_builds_the_list_once() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
let ids: Vec<u64> = (0..1000).map(|i| rect(&mut s, f64::from(i % 40) * 10.0, 10.0, 5.0, 5.0).0).collect();
|
||||
s.execute("select.set", &json!({"ids": ids})).unwrap();
|
||||
s.execute("object.group", &json!({})).unwrap();
|
||||
// Reading `length` and `[i]` 1,000 times each stays within 512 KiB of data only when the list
|
||||
// of 1,000 paths is not built again for each read.
|
||||
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(1 << 19)));
|
||||
let r = run(&mut s, "var P = app.activeDocument.groupItems[0].pathItems, n = 0; for (var i = 0; i < P.length; i++) if (P[i]) n++; vc.log(n);");
|
||||
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None));
|
||||
assert_eq!(r.unwrap()["log"], json!([1000]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_layers_path_items_make_their_paths_on_top_of_that_layer() {
|
||||
let (mut s, ..) = doc();
|
||||
let bottom = s.active().unwrap().doc.layers[0].id;
|
||||
let selected = s.active().unwrap().selection.clone();
|
||||
let steps = undo_steps(&s);
|
||||
// A new layer becomes the current one; each creator of the first layer's `pathItems` still
|
||||
// puts its path on top of that layer.
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var d = app.activeDocument, top = d.layers.add(), L = d.layers[1], P = L.pathItems;\
|
||||
var make = [function () { return P.rectangle(100, 100, 20, 10); }, function () { return P.roundedRectangle(100, 100, 20, 10); },\
|
||||
function () { return P.ellipse(); }, function () { return P.polygon(); }, function () { return P.star(); }, function () { return P.add(); }];\
|
||||
for (var i = 0; i < make.length; i++) { var p = make[i](); p.name = 'm' + i; vc.log(p.layer.name === L.name); vc.log(L.pageItems[0].name); }\
|
||||
vc.log(d.activeLayer.name === top.name); vc.log(top.pageItems.length); vc.log(P.length);",
|
||||
);
|
||||
let mut expected = Vec::new();
|
||||
for i in 0..6 {
|
||||
expected.extend([json!(true), json!(format!("m{i}"))]);
|
||||
}
|
||||
expected.extend([json!(true), json!(0), json!(8)]);
|
||||
assert_eq!(out, expected);
|
||||
assert_eq!(undo_steps(&s), steps + 1);
|
||||
let st = s.active().unwrap();
|
||||
let kids = st.doc.node(bottom).unwrap().children().unwrap();
|
||||
assert_eq!(kids.last().unwrap().name.as_deref(), Some("m5"));
|
||||
assert!(st.selection == selected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_groups_path_items_add_puts_the_path_in_the_group() {
|
||||
let (mut s, a, b) = doc();
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
let gid = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let steps = undo_steps(&s);
|
||||
let before = format!("{:?}", s.active().unwrap().doc.layers);
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var g = app.activeDocument.groupItems[0], n = g.pathItems.add(); n.name = 'N';\
|
||||
vc.log(n.parent.typename); vc.log(g.pageItems[0].name); vc.log(n.pathPoints.length);\
|
||||
var r = g.pathItems.rectangle(50, 50, 10, 10); r.name = 'R'; vc.log(g.pathItems[0].name); vc.log(g.pathItems.length);",
|
||||
);
|
||||
assert_eq!(out, [json!("GroupItem"), json!("N"), json!(0), json!("R"), json!(4)]);
|
||||
assert_eq!(undo_steps(&s), steps + 1);
|
||||
let d = &s.active().unwrap().doc;
|
||||
let top: Vec<Option<&str>> = d.node(gid).unwrap().children().unwrap().iter().rev().take(2).map(|n| n.name.as_deref()).collect();
|
||||
assert_eq!(top, [Some("R"), Some("N")]);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn path_items_of_a_hidden_or_locked_layer_or_group_make_no_path() {
|
||||
const REFUSED: &str = "Cannot add a path to a hidden or locked layer or group";
|
||||
let (mut s, a, b) = doc();
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
let gid = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let lid = s.active().unwrap().doc.layers[0].id;
|
||||
let before = format!("{:?}", s.active().unwrap().doc.layers);
|
||||
s.execute("layer.setProps", &json!({"id": lid.0, "locked": true})).unwrap();
|
||||
let locked = format!("{:?}", s.active().unwrap().doc.layers);
|
||||
for src in ["app.activeDocument.layers[0].pathItems.rectangle(10, 10, 5, 5);", "app.activeDocument.layers[0].pathItems.add();"] {
|
||||
assert!(failure(&mut s, src).contains(REFUSED), "{src}");
|
||||
assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), locked);
|
||||
}
|
||||
// Caught inside the script, each refusal leaves both collections as they were, and the group,
|
||||
// shown and unlocked itself, is refused for its locked layer.
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var L = app.activeDocument.layers[0], g = app.activeDocument.groupItems[0], m = [];\
|
||||
var n = [L.pathItems.length, g.pathItems.length];\
|
||||
try { L.pathItems.rectangle(10, 10, 5, 5); } catch (e) { m.push(e.message); }\
|
||||
try { g.pathItems.add(); } catch (e) { m.push(e.message); }\
|
||||
try { g.pathItems.ellipse(); } catch (e) { m.push(e.message); }\
|
||||
vc.log(m); vc.log([L.pathItems.length, g.pathItems.length]); vc.log(n);",
|
||||
);
|
||||
let refused: Vec<&str> = out[0].as_array().unwrap().iter().filter_map(Value::as_str).collect();
|
||||
assert_eq!(refused.len(), 3, "{out:?}");
|
||||
assert!(refused.iter().all(|m| m.contains(REFUSED)), "{out:?}");
|
||||
assert_eq!(out[1], out[2], "the collections are unchanged inside the script");
|
||||
assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), locked);
|
||||
s.execute("layer.setProps", &json!({"id": lid.0, "locked": false})).unwrap();
|
||||
s.execute("layer.setProps", &json!({"id": gid.0, "visible": false})).unwrap();
|
||||
let hidden = format!("{:?}", s.active().unwrap().doc.layers);
|
||||
assert!(failure(&mut s, "app.activeDocument.groupItems[0].pathItems.ellipse();").contains(REFUSED));
|
||||
assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), hidden);
|
||||
s.execute("layer.setProps", &json!({"id": gid.0, "visible": true})).unwrap();
|
||||
assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before);
|
||||
// A group's `pathItems` read after the group is gone throw.
|
||||
let msg = failure(&mut s, "var g = app.activeDocument.groupItems[0], P = g.pathItems; g.remove(); P.length;");
|
||||
assert!(msg.contains("Stale page item"), "{msg}");
|
||||
}
|
||||
|
||||
/// A collection read with a name gives what its `getByName` gives, in a layer's or a group's
|
||||
/// collections as in the document's, and a name nothing has is not `in` it.
|
||||
#[test]
|
||||
fn collections_read_with_a_name_give_the_named_object() {
|
||||
let (mut s, a, b) = doc();
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
s.execute("object.group", &json!({})).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var d = app.activeDocument, g = d.groupItems[0], r = g.pageItems[0]; r.name = 'Logo'; g.name = 'G';\
|
||||
vc.log([g.pageItems['Logo'] === r, g.pathItems['Logo'] === r, d.pathItems['Logo'] === r, d.groupItems['G'] === g,\
|
||||
d.layers[0].groupItems['G'] === g, d.layers['Layer 1'] === d.layers[0], d.artboards[d.artboards[0].name] === d.artboards[0]]);\
|
||||
vc.log(['Logo' in g.pageItems, 'missing' in g.pageItems, 'missing' in g.pathItems, 'missing' in d.layers, 'missing' in d.artboards]);\
|
||||
var m = ''; try { g.pageItems['missing']; } catch (e) { m = e.message; } vc.log(m);",
|
||||
);
|
||||
assert_eq!(out[0], json!([true, true, true, true, true, true, true]), "{out:?}");
|
||||
assert_eq!(out[1], json!([true, false, false, false, false]), "{out:?}");
|
||||
assert_eq!(out[2], json!("Not found"), "{out:?}");
|
||||
}
|
||||
|
||||
/// A compound path's `pathItems.removeAll()` leaves it, empty, as `remove()` of its last path
|
||||
/// does.
|
||||
#[test]
|
||||
fn clearing_the_paths_of_a_compound_path_keeps_the_compound_path() {
|
||||
let (mut s, a, b) = doc();
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
s.execute("object.compoundPath.make", &json!({})).unwrap();
|
||||
let compound = layer_order(&s)[0];
|
||||
let out = log(&mut s, "var c = app.activeDocument.compoundPathItems[0]; c.pathItems.removeAll(); vc.log([c.typename, c.pathItems.length]);");
|
||||
assert_eq!(out, vec![json!(["CompoundPathItem", 0])]);
|
||||
let d = &s.active().unwrap().doc;
|
||||
assert!(d.node(compound).is_some_and(|n| n.children().is_some_and(|c| c.is_empty())), "the compound path stays, empty");
|
||||
}
|
||||
|
||||
/// A Live Paint group's collections make nothing in it: what they made would join the group's
|
||||
/// paths instead of being one of its objects.
|
||||
#[test]
|
||||
fn collections_of_a_live_paint_group_make_nothing() {
|
||||
const REFUSED: &str = "Cannot add an object to a Live Paint group";
|
||||
let (mut s, a, b) = doc();
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
s.execute("livePaint.make", &json!({})).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let before = format!("{:?}", s.active().unwrap().doc.layers);
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var g = app.activeDocument.pageItems[0], m = [];\
|
||||
try { g.pathItems.rectangle(10, 10, 5, 5); } catch (e) { m.push(e.message); }\
|
||||
try { g.pathItems.add(); } catch (e) { m.push(e.message); }\
|
||||
try { g.groupItems.add(); } catch (e) { m.push(e.message); }\
|
||||
try { g.compoundPathItems.add(); } catch (e) { m.push(e.message); }\
|
||||
vc.log(m);",
|
||||
);
|
||||
let refused: Vec<&str> = out[0].as_array().unwrap().iter().filter_map(Value::as_str).collect();
|
||||
assert_eq!(refused.len(), 4, "{out:?}");
|
||||
assert!(refused.iter().all(|m| m.contains(REFUSED)), "{out:?}");
|
||||
assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compound_path_items_add_makes_an_empty_compound_path_that_takes_paths() {
|
||||
let (mut s, a, b) = doc();
|
||||
@@ -3353,6 +3668,18 @@ fn compound_path_items_add_makes_an_empty_compound_path_that_takes_paths() {
|
||||
assert!(failure(&mut s, src).contains("only paths"), "{src}");
|
||||
}
|
||||
assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before);
|
||||
// Caught inside the run, the refused move leaves the object where it was and the compound
|
||||
// path's members as they were.
|
||||
for (make, to) in
|
||||
[("d.groupItems.add()", "C"), ("d.groupItems.add()", "C.pathItems[0], ElementPlacement.PLACEBEFORE"), ("d.compoundPathItems.add()", "C")]
|
||||
{
|
||||
let src = format!(
|
||||
"var d = app.activeDocument, C = d.compoundPathItems.getByName('C'), o = {make};\
|
||||
try {{ o.move({to}); vc.log('moved'); }} catch (e) {{ vc.log(String(e).indexOf('only paths') >= 0); }}\
|
||||
vc.log(o.parent.typename); vc.log(C.pathItems.length); vc.log(C.pathItems[0].parent.typename);"
|
||||
);
|
||||
assert_eq!(log(&mut s, &src), [json!(true), json!("Layer"), json!(2), json!("CompoundPathItem")], "{src}");
|
||||
}
|
||||
assert!(s.execute("object.newGroup", &json!({"compound": 1})).unwrap_err().to_string().contains("true or false"));
|
||||
}
|
||||
|
||||
@@ -4143,6 +4470,29 @@ fn a_path_moved_between_compound_paths_keeps_its_pixel_alignment() {
|
||||
assert!(!d.node(a).unwrap().extras().pixel_aligned);
|
||||
}
|
||||
|
||||
/// A pixel-aligned compound path snaps a path that was not aligned when it takes it in.
|
||||
#[test]
|
||||
fn a_pixel_aligned_compound_path_snaps_a_path_moved_into_it() {
|
||||
let (mut s, a, _) = doc();
|
||||
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
|
||||
s.execute("object.compoundPath.make", &json!({})).unwrap();
|
||||
s.execute("object.setPixelAligned", &json!({"on": true})).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let cid = s.active().unwrap().doc.parent_of(a).unwrap();
|
||||
let loose = rect(&mut s, 200.25, 20.5, 30.0, 40.0);
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
assert!(!s.active().unwrap().doc.node(loose).unwrap().extras().pixel_aligned);
|
||||
s.execute("node.move", &json!({"id": loose.0, "parent": cid.0, "index": 0})).unwrap();
|
||||
let d = &s.active().unwrap().doc;
|
||||
assert_eq!(d.parent_of(loose), Some(cid));
|
||||
// Both paths have a 1 pt stroke, so the grid puts their edges where it put the aligned path's.
|
||||
let (b, at) = (d.node(loose).unwrap().geometric_bounds().unwrap(), d.node(a).unwrap().geometric_bounds().unwrap());
|
||||
assert_ne!(b.x0, 200.25);
|
||||
for (v, w) in [(b.x0, at.x0), (b.y0, at.y0), (b.x1, at.x1), (b.y1, at.y1)] {
|
||||
assert_eq!(v.fract(), w.fract(), "{b:?} is on the pixel grid as {at:?} is");
|
||||
}
|
||||
}
|
||||
|
||||
/// A path off the pixel grid that moves into a pixel-aligned compound path is snapped to the grid
|
||||
/// with the compound path's other paths.
|
||||
#[test]
|
||||
@@ -4186,18 +4536,39 @@ fn a_compound_paths_path_items_are_page_items() {
|
||||
out,
|
||||
[json!("PathItems"), json!(2), json!("PathItem"), json!("PageItems"), json!(true), json!(false), json!(true), json!(true), json!(true)]
|
||||
);
|
||||
for call in ["add()", "rectangle(100, 100, 10, 10)", "roundedRectangle(100, 100, 10, 10)", "ellipse(100, 100, 10, 10)", "polygon()", "star()"] {
|
||||
// The path creation methods make the new path inside the compound path.
|
||||
for (made, call) in
|
||||
["add()", "rectangle(100, 100, 10, 10)", "roundedRectangle(100, 100, 10, 10)", "ellipse(100, 100, 10, 10)", "polygon()", "star()"]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
{
|
||||
let source = format!(
|
||||
"var p = app.activeDocument.compoundPathItems[0].pathItems; try {{ p.{call}; vc.log('made'); }} catch (e) {{ vc.log(e.message); }} vc.log(p.length);"
|
||||
);
|
||||
let out = log(&mut s, &source);
|
||||
assert!(out[0].as_str().unwrap().contains("not available yet"), "{call}: {out:?}");
|
||||
assert_eq!(out[1], json!(2));
|
||||
assert_eq!(out, [json!("made"), json!(made + 3)], "{call}");
|
||||
}
|
||||
run(&mut s, "var c = app.activeDocument.compoundPathItems[0]; c.pathItems.removeAll(); vc.log(c.pathItems.length);").unwrap();
|
||||
assert!(s.active().unwrap().doc.node(a).is_none() && s.active().unwrap().doc.node(b).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_compound_paths_path_items_add_makes_the_path_inside_it() {
|
||||
let (mut s, _, _) = doc();
|
||||
let steps = undo_steps(&s);
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var c = app.activeDocument.layers[0].compoundPathItems.add(); var p = c.pathItems.add(); p.setEntirePath([[0, 0], [10, 0], [10, 10]]);\
|
||||
var r = c.pathItems.rectangle(50, 20, 10, 10); vc.log(c.pathItems.length); vc.log(p.parent.typename); vc.log(r.parent.typename);\
|
||||
vc.log(c.pathItems[0].width);",
|
||||
);
|
||||
assert_eq!(out, [json!(2), json!("CompoundPathItem"), json!("CompoundPathItem"), json!(10)]);
|
||||
let d = &s.active().unwrap().doc;
|
||||
let compound = d.layers[0].children().unwrap().iter().find(|n| matches!(n.kind, NodeKind::Compound { .. })).unwrap();
|
||||
assert_eq!(compound.children().unwrap().len(), 2);
|
||||
assert_eq!(undo_steps(&s), steps + 1, "the run is one undo step");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn art_collections_follow_edits_between_reads() {
|
||||
let (mut s, _, _) = doc();
|
||||
@@ -4343,6 +4714,18 @@ fn has_selected_artwork_keeps_selected_objects_in_other_layers() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn layer_lists_follow_edits_between_reads() {
|
||||
let (mut s, _, _) = doc();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var L = app.activeDocument.layers, n = L.length; for (var i = 0; i < L.length; i++) L[i];\
|
||||
var made = L.add(); made.name = 'Top'; vc.log(L.length - n); vc.log(L[0].name); vc.log(L.getByName('Top').name);\
|
||||
made.remove(); vc.log(L.length - n);",
|
||||
);
|
||||
assert_eq!(out, [json!(1), json!("Top"), json!("Top"), json!(0)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_items_remove_all_refuses_locked_groups() {
|
||||
let (mut s, a, b) = doc();
|
||||
|
||||
@@ -282,6 +282,43 @@ fn path_items_remove_all_refuses_paths_on_a_locked_artboard() {
|
||||
assert_eq!(log(&mut s, "vc.log(app.activeDocument.pathItems.length);"), vec![json!(0)]);
|
||||
}
|
||||
|
||||
/// A clipping group's `pathItems` lists only its clipping path when its other art is a group:
|
||||
/// `removeAll()` throws and deletes nothing, as `pageItems.removeAll()` does, so the group does not
|
||||
/// become the clipping path.
|
||||
#[test]
|
||||
fn path_items_remove_all_refuses_a_clipping_path_whose_group_keeps_other_objects() {
|
||||
let (mut s, a, b) = doc();
|
||||
s.execute("object.group", &json!({"ids": [b.0]})).unwrap();
|
||||
let inner = s.active().unwrap().doc.parent_of(b).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [a.0, inner.0]})).unwrap();
|
||||
s.execute("object.clippingMask.make", &json!({})).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let clip = s.active().unwrap().doc.parent_of(a).unwrap();
|
||||
s.execute("object.setProps", &json!({"ids": [clip.0], "name": "clip"})).unwrap();
|
||||
let (before, steps) = (art(&s), undo_steps(&s));
|
||||
let e = failure(&mut s, "app.activeDocument.groupItems.getByName('clip').pathItems.removeAll();");
|
||||
assert!(e.contains("cannot delete a clipping path") && e.contains(&a.0.to_string()), "{e}");
|
||||
assert_eq!(art(&s), before);
|
||||
assert_eq!(undo_steps(&s), steps);
|
||||
}
|
||||
|
||||
/// The document's `pathItems.removeAll()` deletes a compound path whose paths it all lists, so a
|
||||
/// clipping group that holds only its clipping path and that compound path is left with nothing
|
||||
/// and is not refused.
|
||||
#[test]
|
||||
fn path_items_remove_all_counts_compound_paths_it_empties() {
|
||||
let (mut s, a, b) = doc();
|
||||
s.execute("select.set", &json!({"ids": [b.0]})).unwrap();
|
||||
s.execute("object.compoundPath.make", &json!({})).unwrap();
|
||||
let compound = s.active().unwrap().doc.parent_of(b).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [a.0, compound.0]})).unwrap();
|
||||
s.execute("object.clippingMask.make", &json!({})).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
log(&mut s, "app.activeDocument.pathItems.removeAll();");
|
||||
let d = &s.active().unwrap().doc;
|
||||
assert!(d.node(a).is_none() && d.node(b).is_none() && d.node(compound).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shape_creators_use_documented_defaults_and_y_up() {
|
||||
let mut s = Session::new();
|
||||
@@ -339,6 +376,76 @@ fn shape_creators_reject_bad_sizes_without_change() {
|
||||
assert_eq!(undo_steps(&s), steps);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn removing_a_point_deselects_a_path_with_direct_selected_anchors() {
|
||||
// `pathItems[1]` is `b`.
|
||||
let (mut s, a, b) = doc();
|
||||
s.execute("select.anchors", &json!({"id": b.0, "anchors": [[0, 1]], "mode": "set"})).unwrap();
|
||||
s.execute("select.add", &json!({"ids": [a.0]})).unwrap();
|
||||
log(&mut s, "app.activeDocument.pathItems[1].pathPoints[0].remove();");
|
||||
let st = s.active().unwrap();
|
||||
assert_eq!(st.doc.node(b).and_then(|n| n.path_data()).map(|p| p.anchors().count()), Some(3));
|
||||
let sel = &st.selection;
|
||||
// A removal renumbers the direct selection: the selected anchor after the removed one moves
|
||||
// down one place.
|
||||
assert_eq!(sel.anchors.get(&b).map(|g| g.iter().copied().collect::<Vec<_>>()), Some(vec![(0, 0)]), "{sel:?}");
|
||||
assert!(sel.objects.contains(&a));
|
||||
// Moving a point keeps the anchors selected.
|
||||
s.execute("select.anchors", &json!({"id": b.0, "anchors": [[0, 1]], "mode": "set"})).unwrap();
|
||||
log(&mut s, "var p = app.activeDocument.pathItems[1].pathPoints[0]; p.anchor = [p.anchor[0] + 1, p.anchor[1]];");
|
||||
assert_eq!(s.active().unwrap().selection.anchors[&b].len(), 1);
|
||||
}
|
||||
|
||||
/// Points are found by their index across subpaths, through changes that wait to be written and
|
||||
/// removals that change how many points a subpath has or remove a subpath.
|
||||
#[test]
|
||||
fn points_are_found_across_subpaths_as_their_counts_change() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
let a = rect(&mut s, 10.0, 20.0, 30.0, 40.0);
|
||||
let pt = |x: f64| json!({"x": x, "y": 0, "in": [x, 0], "out": [x, 0], "smooth": false});
|
||||
let subs = json!([
|
||||
{"anchors": [pt(0.0), pt(1.0)], "closed": false},
|
||||
{"anchors": [pt(2.0)], "closed": false},
|
||||
{"anchors": [pt(3.0), pt(4.0), pt(5.0)], "closed": false},
|
||||
]);
|
||||
s.execute("path.setAnchors", &json!({"id": a.0, "subpaths": subs})).unwrap();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var q = app.activeDocument.pathItems[0].pathPoints; vc.log(q.length);\
|
||||
for (var i = 0; i < q.length; i++) q[i].anchor = [i * 10, 7];\
|
||||
vc.log(q[2].anchor); vc.log(q[5].anchor);\
|
||||
q[1].remove(); vc.log(q.length); vc.log(q[1].anchor); vc.log(q[4].anchor);\
|
||||
q[0].remove(); vc.log(q.length); vc.log(q[0].anchor); vc.log(q[3].anchor); vc.log(q[4] === undefined);",
|
||||
);
|
||||
let want =
|
||||
[json!(6), json!([20, 7]), json!([50, 7]), json!(5), json!([20, 7]), json!([50, 7]), json!(4), json!([20, 7]), json!([50, 7]), json!(true)];
|
||||
assert_eq!(out, want);
|
||||
let n = node(&s, a);
|
||||
let counts: Vec<usize> = n.path_data().unwrap().subpaths.iter().map(|sp| sp.anchors.len()).collect();
|
||||
assert_eq!(counts, vec![1, 3]);
|
||||
}
|
||||
|
||||
/// Moving every point of a path, one at a time, keeps the index of where its subpaths' points
|
||||
/// start: the index is built again only when a change adds or removes points.
|
||||
#[test]
|
||||
fn moving_each_point_keeps_the_index_of_the_subpaths() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
let a = rect(&mut s, 10.0, 20.0, 30.0, 40.0);
|
||||
let subs: Vec<Value> =
|
||||
(0..50).map(|i| json!({"anchors": [{"x": i, "y": 0, "in": [i, 0], "out": [i, 0], "smooth": false}], "closed": false})).collect();
|
||||
s.execute("path.setAnchors", &json!({"id": a.0, "subpaths": subs})).unwrap();
|
||||
let before = crate::script::dom::index_builds();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var q = app.activeDocument.pathItems[0].pathPoints; for (var i = 0; i < q.length; i++) q[i].anchor = [i, 7]; vc.log(q[49].anchor);",
|
||||
);
|
||||
assert_eq!(out, vec![json!([49, 7])]);
|
||||
let built = crate::script::dom::index_builds() - before;
|
||||
assert!(built <= 3, "the index was built {built} times");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_entire_path_replaces_points_and_keeps_closed() {
|
||||
let (mut s, a, _) = doc();
|
||||
@@ -358,6 +465,34 @@ fn set_entire_path_replaces_points_and_keeps_closed() {
|
||||
assert!(pd.subpaths[0].anchors.iter().all(|an| an.h_in == an.p && an.h_out == an.p && an.kind == AnchorKind::Corner));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn control_bounds_take_in_direction_handles() {
|
||||
let (mut s, _, _) = doc();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var r = app.activeDocument.pathItems[0]; vc.log(r.controlBounds); vc.log(r.visibleBounds);\
|
||||
var n = app.activeDocument.pathItems.add(); n.setEntirePath([[0, 0], [100, 0]]);\
|
||||
n.pathPoints[0].rightDirection = [50, 80]; vc.log(n.controlBounds); vc.log(n.visibleBounds);",
|
||||
);
|
||||
assert_eq!(out[0], out[1], "a rectangle has no handles outside its visible bounds");
|
||||
let edges = |v: &Value| (0..4).map(|i| v[i].as_f64().unwrap()).collect::<Vec<_>>();
|
||||
let (control, visible) = (edges(&out[2]), edges(&out[3]));
|
||||
assert!(control[1].max(control[3]) >= 80.0 - 1e-9, "{control:?}");
|
||||
assert!(visible[1].max(visible[3]) < 80.0, "{visible:?}");
|
||||
assert!(control[0] <= visible[0] && control[2] >= visible[2], "{control:?} holds {visible:?}");
|
||||
}
|
||||
|
||||
/// A clipping group's control bounds are its clipping path's: art outside the clip is left out, as
|
||||
/// it is from the visible bounds.
|
||||
#[test]
|
||||
fn a_clipping_groups_control_bounds_leave_out_the_clipped_art() {
|
||||
let (mut s, a, b) = doc();
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
s.execute("object.clippingMask.make", &json!({})).unwrap();
|
||||
let out = log(&mut s, "var g = app.activeDocument.groupItems[0]; vc.log(g.controlBounds); vc.log(g.visibleBounds);");
|
||||
assert_eq!(out[0], out[1]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_set_entire_path_input_is_bounded() {
|
||||
let (mut s, _, _) = doc();
|
||||
@@ -1225,6 +1360,29 @@ fn identity_transforms_of_an_empty_path_do_nothing() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn turning_or_scaling_an_empty_path_changes_nothing() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
log(&mut s, "var n = app.activeDocument.pathItems.add(); n.rotate(90); n.resize(50, 50);");
|
||||
assert_eq!(undo_steps(&s), 1, "only the path is added");
|
||||
}
|
||||
|
||||
/// Scaling stroke weights and effects by the scale itself without moving the object is refused for
|
||||
/// a path with no anchors as it is for one with bounds, and the stroke weight stays.
|
||||
#[test]
|
||||
fn scaling_line_widths_alone_is_refused_for_an_empty_path() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
log(&mut s, "var n = app.activeDocument.pathItems.add(); n.stroked = true; n.strokeWidth = 4;");
|
||||
let (before, steps) = (art(&s), undo_steps(&s));
|
||||
let e = failure(&mut s, "app.activeDocument.pathItems[0].resize(50, 50, false, false, false, false, 50);");
|
||||
assert!(e.contains("changeLineWidths other than 100 with changePositions false"), "{e}");
|
||||
assert_eq!(art(&s), before);
|
||||
assert_eq!(undo_steps(&s), steps);
|
||||
assert_eq!(log(&mut s, "vc.log(app.activeDocument.pathItems[0].strokeWidth);"), vec![json!(4)]);
|
||||
}
|
||||
|
||||
/// The paint of the fill (`fill`) or stroke of `id`.
|
||||
fn paint_of(s: &Session, id: NodeId, fill: bool) -> Paint {
|
||||
let n = node(s, id);
|
||||
@@ -1356,14 +1514,14 @@ fn paint_and_point_edits_keep_the_list_of_paths() {
|
||||
rect(&mut s, f64::from(i % 10) * 10.0, f64::from(i / 10) * 10.0, 5.0, 5.0);
|
||||
}
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let start = crate::script::dom::PATH_LISTS.with(|n| n.get());
|
||||
let start = crate::script::dom::PATH_LIST_BUILDS.with(|n| n.get());
|
||||
log(
|
||||
&mut s,
|
||||
"var ps = app.activeDocument.pathItems;\
|
||||
for (var i = 0; i < ps.length; i++) { var c = new RGBColor(); c.red = i; ps[i].fillColor = c; ps[i].strokeWidth = 2;\
|
||||
ps[i].fillOverprint = true; var q = ps[i].pathPoints[0]; q.anchor = [q.anchor[0] + 1, q.anchor[1]]; }",
|
||||
);
|
||||
let built = crate::script::dom::PATH_LISTS.with(|n| n.get()) - start;
|
||||
let built = crate::script::dom::PATH_LIST_BUILDS.with(|n| n.get()) - start;
|
||||
assert_eq!(built, 1, "the paths are listed once for 50 paint and point edits");
|
||||
let out = log(&mut s, "var ps = app.activeDocument.pathItems; var n = ps.length; ps.rectangle(0, 0, 1, 1); vc.log([n, ps.length]);");
|
||||
assert_eq!(out, vec![json!([50, 51])], "a new path is listed");
|
||||
@@ -2088,6 +2246,39 @@ fn filled_and_stroked_true_give_the_new_art_paint() {
|
||||
}
|
||||
}
|
||||
|
||||
/// The pattern of a path with no anchors turns and scales about the origin, as a path without
|
||||
/// points takes any transformation; each call is one undo step.
|
||||
#[test]
|
||||
fn transforming_the_pattern_of_an_empty_path_turns_it() {
|
||||
for source in [
|
||||
"app.activeDocument.pathItems[0].rotate(90, true, true, true, true);",
|
||||
"app.activeDocument.pathItems[0].resize(50, 50, true, true, true, true);",
|
||||
"app.activeDocument.pathItems[0].resize(50, 50, false, true, false, true);",
|
||||
] {
|
||||
let (mut s, _) = doc_with_paints();
|
||||
s.execute("paint.setFill", &json!({"swatch": "Dots"})).unwrap();
|
||||
log(&mut s, "var n = app.activeDocument.pathItems.add(); n.stroked = true; n.strokeWidth = 4;");
|
||||
assert_eq!(log(&mut s, "vc.log(app.activeDocument.pathItems[0].fillColor.typename);"), vec![json!("PatternColor")]);
|
||||
let (before, steps) = (art(&s), undo_steps(&s));
|
||||
log(&mut s, source);
|
||||
assert_ne!(art(&s), before, "{source}: the pattern transforms");
|
||||
assert_eq!(undo_steps(&s), steps + 1, "{source}: one undo step");
|
||||
}
|
||||
}
|
||||
|
||||
/// Scaling a path with no anchors with its stroke weights scales its own stroke weight.
|
||||
#[test]
|
||||
fn scaling_an_empty_path_with_line_widths_scales_its_stroke() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
log(&mut s, "var n = app.activeDocument.pathItems.add(); n.stroked = true; n.strokeWidth = 10; n.strokeDashes = [3, 4];");
|
||||
let steps = undo_steps(&s);
|
||||
log(&mut s, "app.activeDocument.pathItems[0].resize(200, 200, true, false, true, false, 200);");
|
||||
assert_eq!(log(&mut s, "vc.log(app.activeDocument.pathItems[0].strokeWidth);"), vec![json!(20)]);
|
||||
assert_eq!(log(&mut s, "vc.log(app.activeDocument.pathItems[0].strokeDashes);"), vec![json!([6, 8])], "the dashes scale too");
|
||||
assert_eq!(undo_steps(&s), steps + 1, "one undo step");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn filled_true_throws_for_a_new_art_pattern_it_cannot_give() {
|
||||
let placed = vectorcraft_color::Paint::Pattern { pattern: "Dots".into(), xf: vectorcraft_geom::Affine::scale(2.0) };
|
||||
|
||||
@@ -1164,6 +1164,28 @@ fn the_source_image_cannot_leave_its_tracing() {
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// A tracing's shown source image cannot be removed, which would leave the tracing without it, and
|
||||
/// the refused remove leaves the document as it was.
|
||||
#[test]
|
||||
fn a_shown_source_image_cannot_be_removed() {
|
||||
let base = folder("source-removed");
|
||||
let (mut s, _) = session(&base, false);
|
||||
log(&mut s, &base, "app.activeDocument.rasterItems[0].trace().tracing.sourceArt.hidden = false;");
|
||||
let saved = vectorcraft_format::save(&s.active().unwrap().doc, false);
|
||||
let steps = undo_steps(&s);
|
||||
let out = log(
|
||||
&mut s,
|
||||
&base,
|
||||
"var d = app.activeDocument, p = d.pageItems[0], m = 'none';\
|
||||
try { p.tracing.sourceArt.remove(); } catch (e) { m = e.message; }\
|
||||
vc.log(m); vc.log(p.isTracing);",
|
||||
);
|
||||
assert_eq!(out, [json!("a tracing's source image cannot leave its tracing"), json!(true)]);
|
||||
assert_eq!(vectorcraft_format::save(&s.active().unwrap().doc, false), saved);
|
||||
assert_eq!(undo_steps(&s), steps);
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trace_source_art_is_not_listed_with_the_images() {
|
||||
let base = folder("lists");
|
||||
|
||||
@@ -1493,6 +1493,93 @@ fn point_changes_written_as_the_script_ends_wait_for_the_growth_answer() {
|
||||
assert_eq!(state(&s), before);
|
||||
}
|
||||
|
||||
/// A script that ends past the allowance the person's last answer gave is asked again before its
|
||||
/// changes are kept.
|
||||
#[test]
|
||||
fn a_finished_run_past_its_last_allowance_asks_again() {
|
||||
let draw = "vc.run('shape.rectangle', {x:1,y:1,width:1,height:1}); vc.run('shape.rectangle', {x:2,y:1,width:1,height:1});";
|
||||
let point = "var P = app.activeDocument.pathItems, q = P[0];\
|
||||
for (var k = 1; k < P.length; k++) if (P[k].pathPoints.length > q.pathPoints.length) q = P[k];\
|
||||
var p = q.pathPoints; for (var i = 0; i < p.length; i++) p[i].anchor = [i * 3, -4 - i];";
|
||||
// The path the script moves has 600 anchors, so its point changes weigh more than the
|
||||
// rectangles do.
|
||||
let two_docs = || {
|
||||
let mut s = two_docs();
|
||||
let id = s.documents()[1].doc.layers[0].children().unwrap()[0].id;
|
||||
let anchors: Vec<Value> = (0..600)
|
||||
.map(|i| json!({"x": f64::from(i), "y": f64::from(i % 7), "in": [f64::from(i), 0.0], "out": [f64::from(i), 0.0], "smooth": false}))
|
||||
.collect();
|
||||
s.execute("path.setAnchors", &json!({"id": id.0, "subpaths": [{"anchors": anchors, "closed": false}]})).unwrap();
|
||||
s
|
||||
};
|
||||
let added = |source: &str| {
|
||||
let mut s = two_docs();
|
||||
let start = s.documents()[1].doc.clone();
|
||||
assert_eq!(run(&mut s, source).unwrap()["ok"], true);
|
||||
start.retained_bytes_each(&s.documents()[1].doc).1 as u64
|
||||
};
|
||||
let whole = format!("{draw} {point}");
|
||||
let (m, p) = (added(draw), added(&whole) - added(draw));
|
||||
// The rectangles go past one object, which asks once, and stay within twice the bytes; the
|
||||
// point changes, written as the script ends, then go past the second allowance and also past
|
||||
// the third.
|
||||
let b = (m + p - 1) / 3;
|
||||
assert!(m <= 2 * b && 3 * b < m + p && m + p <= 4 * b, "m {m}, p {p}, b {b}");
|
||||
TEST_GROWTH.with(|g| g.set(Some(1)));
|
||||
TEST_GROWTH_BYTES.with(|g| g.set(Some(b)));
|
||||
let mut s = two_docs();
|
||||
s.script_frames = true;
|
||||
run(&mut s, &whole).unwrap();
|
||||
let mut questions = 0;
|
||||
let done = loop {
|
||||
assert!(questions < 10);
|
||||
if s.script_waiting() {
|
||||
questions += 1;
|
||||
s.script_continue();
|
||||
}
|
||||
if let Some(r) = s.script_pump() {
|
||||
break r;
|
||||
}
|
||||
};
|
||||
TEST_GROWTH.with(|g| g.set(None));
|
||||
TEST_GROWTH_BYTES.with(|g| g.set(None));
|
||||
assert_eq!(done.unwrap()["ok"], true);
|
||||
assert_eq!(questions, 3, "asked mid-run, as the script ended, and again for the third allowance");
|
||||
}
|
||||
|
||||
/// A script that ends with nothing left to write, past the allowance the person's last answer
|
||||
/// gave, is asked again before its changes are kept.
|
||||
#[test]
|
||||
fn a_run_that_ends_past_its_last_allowance_with_nothing_to_write_asks_again() {
|
||||
TEST_GROWTH.with(|g| g.set(Some(20)));
|
||||
// 21 rectangles go past the first allowance, and the 45 the document opens go past the
|
||||
// second and stay within twice it, which leaves them past the third.
|
||||
let rects: String = (0..45).map(|i| format!(r#"<rect x="{i}" y="0" width="1" height="1"/>"#)).collect();
|
||||
let svg = format!(r#"<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100">{rects}</svg>"#);
|
||||
let data = vectorcraft_format::base64_encode(svg.as_bytes());
|
||||
let source = format!(
|
||||
"for (var i = 0; i < 21; i++) vc.run('shape.rectangle', {{x:i,y:1,width:1,height:1}});\
|
||||
vc.run('document.open', {{name: 'a.svg', dataBase64: '{data}'}});"
|
||||
);
|
||||
let mut s = two_docs();
|
||||
s.script_frames = true;
|
||||
run(&mut s, &source).unwrap();
|
||||
let mut questions = 0;
|
||||
let done = loop {
|
||||
assert!(questions < 10);
|
||||
if s.script_waiting() {
|
||||
questions += 1;
|
||||
s.script_continue();
|
||||
}
|
||||
if let Some(r) = s.script_pump() {
|
||||
break r;
|
||||
}
|
||||
};
|
||||
TEST_GROWTH.with(|g| g.set(None));
|
||||
assert_eq!(done.unwrap()["ok"], true);
|
||||
assert_eq!(questions, 3, "asked for the rectangles, for the document, and again as the script ended");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_run_waiting_to_grow_stops_at_the_next_slice_once_its_work_is_canceled() {
|
||||
TEST_GROWTH.with(|g| g.set(Some(20)));
|
||||
|
||||
+124
-10
@@ -753,6 +753,94 @@ impl Session {
|
||||
r
|
||||
}
|
||||
|
||||
/// [`Self::pointer`] for each of `evs`, the samples one frame delivers to a tool that builds its
|
||||
/// stroke from every position the pointer passed ([`Self::tool_wants_samples`]), and the release
|
||||
/// when it comes in that frame. The tool gets every sample, but of a run of previews of one
|
||||
/// command only the last is applied, since each preview replaces the one before it. Every other
|
||||
/// action of the tool runs in its order, after the preview held before it. The held preview is
|
||||
/// applied before the release or any other event that is not a drag, since the release reads the
|
||||
/// document as the drag's preview left it. Every preview is applied during a Global Edit, with
|
||||
/// Objects on Path selected, or with multiple objects selected, since a preview can change other
|
||||
/// paths or their eligibility for joins. Every preview is also applied with New Art Has Basic
|
||||
/// Appearance off when the interaction began with a selection, since previews then carry the
|
||||
/// inherited new-art paints forward. The decision is made again after each event that is not a drag.
|
||||
/// Feeding stops after a sample that fails, that asks the frontend for more than a status
|
||||
/// message, or that leaves the tool computing an edit on another thread, so the frontend acts
|
||||
/// on it before the samples after it.
|
||||
/// Returns how many of `evs` were fed (at least one unless `evs` is empty) and what they ask of
|
||||
/// the frontend.
|
||||
pub fn pointer_samples(&mut self, evs: &[PointerEvent], view: ViewInfo) -> (usize, Result<Vec<UiRequest>>) {
|
||||
let mut ui = vec![];
|
||||
let mut failed = None;
|
||||
let mut fed = 0;
|
||||
let mut holds = self.holds_previews || !self.preview_affects_later_samples();
|
||||
let outer = std::mem::replace(&mut self.holds_previews, holds);
|
||||
for ev in evs {
|
||||
fed += 1;
|
||||
if ev.kind != PointerKind::Drag && !outer {
|
||||
self.holds_previews = false;
|
||||
match self.apply_sampled_preview() {
|
||||
Ok(asks) => ui.extend(asks),
|
||||
Err(e) => {
|
||||
failed.get_or_insert(e);
|
||||
}
|
||||
}
|
||||
self.holds_previews = holds;
|
||||
}
|
||||
let result = self.pointer(ev, view);
|
||||
if ev.kind != PointerKind::Drag {
|
||||
holds = outer || !self.preview_affects_later_samples();
|
||||
self.holds_previews = holds;
|
||||
}
|
||||
match result {
|
||||
Ok(asks) => {
|
||||
let stop = asks.iter().any(|a| !matches!(a, UiRequest::Status(_)));
|
||||
ui.extend(asks);
|
||||
if stop || self.tool_edit_pending() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
failed = Some(e);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
self.holds_previews = outer;
|
||||
let held = if outer { Ok(vec![]) } else { self.apply_sampled_preview() };
|
||||
let r = match (failed, held) {
|
||||
(Some(e), _) | (None, Err(e)) => Err(e),
|
||||
(None, Ok(more)) => {
|
||||
ui.extend(more);
|
||||
Ok(ui)
|
||||
}
|
||||
};
|
||||
(fed, r)
|
||||
}
|
||||
|
||||
/// Whether each preview must run because it can change other paths, their eligibility for joins,
|
||||
/// or the new-art paints inherited by later previews: with more than one object selected now or
|
||||
/// when the interaction began, since the tool reads the other selected paths for joins. Before an
|
||||
/// interaction opens, its starting selection is the active document's current selection.
|
||||
fn preview_affects_later_samples(&self) -> bool {
|
||||
self.active().is_some_and(|st| {
|
||||
let selection = st.interaction.as_ref().map_or(&st.selection, |it| it.selection.as_ref());
|
||||
(!self.prefs.new_art_basic && !selection.is_empty())
|
||||
|| selection.objects.len() > 1
|
||||
|| st.selection.objects.len() > 1
|
||||
|| st.global_edit.is_some()
|
||||
|| !crate::cmd::objects_on_path::groups_of(&st.doc, &st.selection.objects).is_empty()
|
||||
})
|
||||
}
|
||||
|
||||
/// Applies the preview [`Self::pointer_samples`] held, if any, as the tool's own action.
|
||||
fn apply_sampled_preview(&mut self) -> Result<Vec<UiRequest>> {
|
||||
match self.sampled_preview.take() {
|
||||
Some((cmd, p)) => self.apply_actions(vec![Action::Preview(cmd, p)]),
|
||||
None => Ok(vec![]),
|
||||
}
|
||||
}
|
||||
|
||||
/// The number of the next pointer or key event handed to the session.
|
||||
fn next_input(&mut self) -> u64 {
|
||||
let n = self.input_count;
|
||||
@@ -1868,9 +1956,23 @@ impl Session {
|
||||
r
|
||||
}
|
||||
|
||||
/// [`Self::run_tool_actions`], holding the previews while [`Self::pointer_samples`] runs. Actions
|
||||
/// that these actions lead to run with nothing held.
|
||||
fn apply_tool_actions(&mut self, acts: Vec<Action>) -> Result<Vec<UiRequest>> {
|
||||
let holds = std::mem::take(&mut self.holds_previews);
|
||||
let r = self.run_tool_actions(acts, holds);
|
||||
self.holds_previews = holds;
|
||||
r
|
||||
}
|
||||
|
||||
/// Runs the tool's actions in order. With `holds`, a preview is kept in [`Self::sampled_preview`]
|
||||
/// in place of the one kept before it, and the kept preview is applied before any other action.
|
||||
fn run_tool_actions(&mut self, acts: Vec<Action>, holds: bool) -> Result<Vec<UiRequest>> {
|
||||
let mut ui = vec![];
|
||||
for a in acts {
|
||||
if let Some((cmd, p)) = self.sampled_preview.take_if(|(held, _)| !matches!(&a, Action::Preview(cmd, _) if *cmd == *held)) {
|
||||
self.run_preview(&cmd, &p, &mut ui);
|
||||
}
|
||||
match a {
|
||||
Action::Begin(label) => {
|
||||
// The snapshot of the interaction open before, which the tool's drag then joins.
|
||||
@@ -1896,17 +1998,13 @@ impl Session {
|
||||
}
|
||||
continue;
|
||||
}
|
||||
self.clear_deferred_overlay_cache();
|
||||
match self.preview(&cmd, &p) {
|
||||
Ok(v) => {
|
||||
if let Some(w) = v.get("warning").and_then(Value::as_str)
|
||||
&& !ui.iter().any(|r| matches!(r, UiRequest::Status(s) if s == w))
|
||||
{
|
||||
ui.push(UiRequest::Status(w.to_string()));
|
||||
}
|
||||
}
|
||||
Err(e) => log::warn!("preview {cmd}: {e}"),
|
||||
if holds {
|
||||
self.sampled_preview = Some((cmd, p));
|
||||
continue;
|
||||
}
|
||||
// This preview replaces a held preview of the same command.
|
||||
self.sampled_preview = None;
|
||||
self.run_preview(&cmd, &p, &mut ui);
|
||||
}
|
||||
// The drag is over: the dabs of a Liquify stroke have no further use.
|
||||
Action::Commit => {
|
||||
@@ -1968,6 +2066,22 @@ impl Session {
|
||||
Ok(ui)
|
||||
}
|
||||
|
||||
/// Applies the tool's preview of `cmd` with `p`. Its warning goes to `ui` once; a failed preview
|
||||
/// is logged and leaves the interaction open.
|
||||
fn run_preview(&mut self, cmd: &str, p: &Value, ui: &mut Vec<UiRequest>) {
|
||||
self.clear_deferred_overlay_cache();
|
||||
match self.preview(cmd, p) {
|
||||
Ok(v) => {
|
||||
if let Some(w) = v.get("warning").and_then(Value::as_str)
|
||||
&& !ui.iter().any(|r| matches!(r, UiRequest::Status(s) if s == w))
|
||||
{
|
||||
ui.push(UiRequest::Status(w.to_string()));
|
||||
}
|
||||
}
|
||||
Err(e) => log::warn!("preview {cmd}: {e}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// With Real-time Drawing off, the selection's transform box ([`Session::transform_box`]) as the
|
||||
/// pending preview of a handle resize or of a shape being drawn leaves it, measured once per
|
||||
/// preview step, with the layer color of the first object it measures; `None` when no such
|
||||
|
||||
@@ -153,7 +153,7 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
"Layer.prototype.",
|
||||
"artworkKnockout artworkKnockout= blendingMode blendingMode= color color= compoundPathItems constructor \
|
||||
dimPlacedImages dimPlacedImages= groupItems hasSelectedArtwork hasSelectedArtwork= isIsolated layers locked \
|
||||
locked= move name name= opacity opacity= pageItems parent pathItems pathItems= placedItems placedItems= preview \
|
||||
locked= move name name= opacity opacity= pageItems parent pathItems placedItems placedItems= preview \
|
||||
preview= printable printable= rasterItems rasterItems= remove sliced sliced= symbolItems symbolItems= textFrames \
|
||||
toString typename visible visible= zOrder zOrderPosition",
|
||||
),
|
||||
@@ -162,7 +162,7 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
("GroupItem.", "prototype"),
|
||||
(
|
||||
"GroupItem.prototype.",
|
||||
"clipped clipped= compoundPathItems constructor groupItems pageItems pathItems pathItems= placedItems placedItems= \
|
||||
"clipped clipped= compoundPathItems constructor groupItems pageItems pathItems placedItems placedItems= \
|
||||
rasterItems rasterItems= symbolItems symbolItems= textFrames",
|
||||
),
|
||||
("GroupItems.", "prototype"),
|
||||
@@ -241,12 +241,12 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
strokeWidth strokeWidth= stroked stroked=",
|
||||
),
|
||||
("PathPoints.", "prototype"),
|
||||
("PathPoints.prototype.", "add constructor index length parent removeAll typename"),
|
||||
("PathPoints.prototype.", "add constructor index length parent removeAll toString typename"),
|
||||
("PathPoint.", "prototype"),
|
||||
(
|
||||
"PathPoint.prototype.",
|
||||
"anchor anchor= constructor leftDirection leftDirection= parent pointType pointType= remove rightDirection \
|
||||
rightDirection= selected selected= typename",
|
||||
rightDirection= selected selected= toString typename",
|
||||
),
|
||||
("Swatches.", "prototype"),
|
||||
("Swatches.prototype.", "add constructor getByName getSelected getSelected= index length parent removeAll typename"),
|
||||
|
||||
@@ -1057,6 +1057,33 @@ fn native_source_without_composites_ignores_front_font_meaning() {
|
||||
// The file's undefined family is not given a new alias or post-adoption policy by this query test.
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn placed_family_undefined_in_its_source_keeps_its_measured_size_beside_a_destination_composite() {
|
||||
let _context = FontContext::hold();
|
||||
let dir = TempDir::new("native-undefined-family-placed");
|
||||
let path = dir.join("undefined-family.vectorcraft");
|
||||
let font = CompositeFont::new("NativePlacedUndefinedFamily", "Source Sans 3", "Regular");
|
||||
let mut source = font_document(&font);
|
||||
source.composite_fonts = Vec::new().into();
|
||||
write_native(&path, &source);
|
||||
let mut larger = font.clone();
|
||||
larger.parts.roman.size = 125.0;
|
||||
let mut placed = Vec::new();
|
||||
for front_fonts in [Vec::new(), vec![larger]] {
|
||||
let mut session = destination(&front_fonts);
|
||||
let reply = session.execute("file.place", &json!({"path": path, "link": false, "crop": "bounding", "at": [30, 25]})).unwrap();
|
||||
let id = NodeId(reply["ids"][0].as_u64().unwrap());
|
||||
let again = place(&mut session, &path, false);
|
||||
assert_eq!(placed_family(&session, again), placed_family(&session, id), "placing the same art again gives its family the same name");
|
||||
// Opening the saved result measures its type again in the fonts it draws with.
|
||||
let bytes = vectorcraft_format::save_with(document(&session), &vectorcraft_format::SaveOptions::default()).unwrap();
|
||||
session.add_document(vectorcraft_format::load(&bytes).unwrap(), None);
|
||||
let doc = document(&session);
|
||||
placed.push(doc.node(id).unwrap().geometric_bounds_with(&doc.symbol_boxes()).unwrap());
|
||||
}
|
||||
assert_eq!(placed[0], placed[1], "placed type keeps the size it was measured at, whatever composite the destination gives its family name");
|
||||
}
|
||||
|
||||
fn native_mapping_source(path: &Path, incoming: &CompositeFont, location: usize, classic: bool, mixed: bool) -> (Session, Document) {
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, Effect};
|
||||
|
||||
@@ -589,7 +589,8 @@ fn install_checked(
|
||||
let v = i.write_hosted(d)?;
|
||||
undo.define_global(i, &name, Prop::Data { value: v, flags: 0 })?;
|
||||
}
|
||||
Ok(())
|
||||
// The prototypes, constructors and members are made without a reservation of their own.
|
||||
i.reserve_heap(0)
|
||||
}
|
||||
|
||||
/// Adds the global properties `globals`, each read with its getter and assigned with its setter as
|
||||
|
||||
@@ -886,6 +886,31 @@ fn with_thing(r: &mut Realm, make: Option<HostFunction>) {
|
||||
r.define_host_classes(vec![class], vec![("thing".into(), host_ref("Thing", &[1.0]))]).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn host_classes_that_do_not_fit_the_heap_end_with_the_heap_limit() {
|
||||
let mut r = realm(1_000_000);
|
||||
let interp = r.interp();
|
||||
interp.collect_garbage();
|
||||
interp.limits.heap_bytes = interp.heap.bytes;
|
||||
let class = HostClass { name: "Empty".into(), parent: None, members: Vec::new(), info: Vec::new(), index: None, construct: None };
|
||||
let e = r.define_host_classes(vec![class], Vec::new()).unwrap_err();
|
||||
assert_eq!(e.kind, RunErrorKind::Limit(LimitKind::Heap));
|
||||
}
|
||||
|
||||
/// A new object of a host class adds its handle to the heap's total as well as itself, so objects
|
||||
/// made one after another count each other's handles before a collection does.
|
||||
#[test]
|
||||
fn an_object_of_a_host_class_counts_its_handle_toward_the_heap() {
|
||||
let mut r = realm(1_000_000);
|
||||
with_thing(&mut r, None);
|
||||
let interp = r.interp();
|
||||
let handle: Vec<f64> = (0..64).map(f64::from).collect();
|
||||
let before = interp.heap.bytes;
|
||||
interp.write_host_ref(&host_ref("Thing", &handle)).unwrap();
|
||||
let added = interp.heap.bytes - before;
|
||||
assert!(added >= crate::heap::OBJECT_BYTES + crate::host_classes::handle_bytes(handle.len()), "{added}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_answer_to_a_waiting_member_of_a_host_class_is_an_object_of_its_class() {
|
||||
let mut r = realm(1_000_000);
|
||||
|
||||
@@ -18,6 +18,7 @@ use std::io::{BufRead, BufReader, ErrorKind, Read, Write};
|
||||
use std::net::{SocketAddr, TcpStream};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::rc::Rc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, Mutex, PoisonError};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
@@ -284,7 +285,15 @@ impl LiveBackend {
|
||||
pub fn new(cfg: LiveConfig) -> Self {
|
||||
let LiveConfig { config_dir, read_settings, when_closed, read_roots, write_root, launch, launch_timeout, allowed, default_folder, headless } =
|
||||
cfg;
|
||||
let consent = move |dir: &Path| Consent::new(allowed(), read_settings(dir));
|
||||
// The router's own decision on the last lookup (it asks for consent, then makes the
|
||||
// headless session, under one lock), so the session's file access follows that decision.
|
||||
let agents_in = Arc::new(AtomicBool::new(false));
|
||||
let decided = Arc::clone(&agents_in);
|
||||
let consent = move |dir: &Path| {
|
||||
let consent = Consent::new(allowed(), read_settings(dir));
|
||||
decided.store(consent.allowed && consent.settings.allow_agent_control, Ordering::SeqCst);
|
||||
consent
|
||||
};
|
||||
let connect = |w: &shared::Window| -> Result<SharedWindow, String> {
|
||||
let mut window = Window::new(w.port, w.token.clone());
|
||||
window.connect()?;
|
||||
@@ -292,7 +301,9 @@ impl LiveBackend {
|
||||
};
|
||||
let make_headless = move |wanted: &HeadlessFolders| -> Result<SharedHeadless, String> {
|
||||
let roots = if wanted.read.is_empty() && wanted.write.is_none() {
|
||||
None
|
||||
// Agents the person let in are confined to the agent folders: when none can be
|
||||
// used (the default one can't be made), the session gets no file access.
|
||||
if agents_in.load(Ordering::SeqCst) { Some(AutomationRoots::none()) } else { None }
|
||||
} else {
|
||||
let read: Vec<&Path> = wanted.read.iter().map(PathBuf::as_path).collect();
|
||||
let write: Vec<&Path> = wanted.write.as_deref().into_iter().collect();
|
||||
@@ -329,6 +340,10 @@ impl Backend for LiveBackend {
|
||||
matches!(self.live.resolve(), Ok(Route::Window(_)))
|
||||
}
|
||||
|
||||
fn ui(&self) -> Result<bool, String> {
|
||||
Ok(matches!(self.live.resolve()?, Route::Window(_)))
|
||||
}
|
||||
|
||||
fn describe(&self) -> String {
|
||||
"the open VectorCraft window while AI agents may use it (ArtCraft Launcher › Settings › AI agents), otherwise a session without a window"
|
||||
.into()
|
||||
|
||||
@@ -13,6 +13,11 @@ pub trait Backend {
|
||||
fn call(&mut self, method: &str, params: Value) -> Result<Value, String>;
|
||||
/// True when a real UI is attached (`ui.*` methods like `ui.key` / `ui.inspect` work).
|
||||
fn has_ui(&self) -> bool;
|
||||
/// Whether a real UI is attached, as [`Self::has_ui`], or why the backend could not reach the
|
||||
/// window (a launch that timed out, a failed handshake).
|
||||
fn ui(&self) -> Result<bool, String> {
|
||||
Ok(self.has_ui())
|
||||
}
|
||||
/// Short human description ("headless", "remote 127.0.0.1:7979").
|
||||
fn describe(&self) -> String;
|
||||
}
|
||||
|
||||
@@ -132,6 +132,21 @@ fn a_window_that_cannot_prove_the_token_gets_nothing() {
|
||||
assert_eq!(served.load(Ordering::SeqCst), 0);
|
||||
}
|
||||
|
||||
// A tool that needs the window reports why the window could not be reached, not that it is closed.
|
||||
#[test]
|
||||
fn a_ui_tool_reports_why_the_window_could_not_be_reached() {
|
||||
let dir = TempFolder::new("agents-ui-bad-token");
|
||||
let (port, served) = fake_window("fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210");
|
||||
publish(&dir, port);
|
||||
let mut b = live(&dir, || true, settings_headless, dir.file("Agents"));
|
||||
let r = crate::tools::call_tool(&mut b, "inspect_ui", &json!({}));
|
||||
assert!(r.is_error);
|
||||
let text = r.content[0]["text"].as_str().unwrap_or_default();
|
||||
assert!(text.contains("could not prove"), "{text}");
|
||||
assert!(!text.contains(crate::agents::NEEDS_WINDOW), "{text}");
|
||||
assert_eq!(served.load(Ordering::SeqCst), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_connection_file_with_nothing_listening_follows_the_closed_app_choice() {
|
||||
let dir = TempFolder::new("agents-stale");
|
||||
@@ -151,6 +166,35 @@ fn a_connection_file_with_nothing_listening_follows_the_closed_app_choice() {
|
||||
assert!(e.contains("outside the read root"), "{e}");
|
||||
}
|
||||
|
||||
// The agent folder can't be made (its parent is a file): the headless session the person chose for
|
||||
// a closed app gets no file access, rather than access to everything.
|
||||
#[test]
|
||||
fn a_headless_agent_session_without_usable_folders_reads_and_writes_nothing() {
|
||||
let dir = TempFolder::new("agents-no-folder");
|
||||
std::fs::write(dir.file("blocker"), b"").unwrap();
|
||||
let mut b = live(&dir, || true, settings_headless, dir.file("blocker").join("Agents"));
|
||||
assert!(!b.has_ui());
|
||||
let folders = b.call(FOLDERS_METHOD, json!({})).unwrap();
|
||||
assert_ne!(folders["unrestricted"], true, "{folders}");
|
||||
let outside = dir.file("outside.svg");
|
||||
std::fs::write(&outside, r#"<svg xmlns="http://www.w3.org/2000/svg" width="4" height="3"/>"#).unwrap();
|
||||
let e = b.call("app.open", json!({"path": outside.to_string_lossy()})).unwrap_err();
|
||||
assert!(e.contains("read authority is absent"), "{e}");
|
||||
let saved = dir.file("saved.svg");
|
||||
let e = b.call("app.save", json!({"path": saved.to_string_lossy()})).unwrap_err();
|
||||
assert!(e.contains("write authority is absent"), "{e}");
|
||||
assert!(!saved.exists(), "the refused save must not write the file");
|
||||
|
||||
// With Allow Agent Control off, the session is the ordinary headless fallback, as before.
|
||||
fn control_off(dir: &Path) -> AgentSettings {
|
||||
let mut s = settings_headless(dir);
|
||||
s.allow_agent_control = false;
|
||||
s
|
||||
}
|
||||
let mut b = live(&dir, || true, control_off, dir.file("blocker").join("Agents"));
|
||||
assert_eq!(b.call(FOLDERS_METHOD, json!({})).unwrap()["unrestricted"], true);
|
||||
}
|
||||
|
||||
/// A canonical path as the automation roots show it: without Windows' `\\?\` prefix.
|
||||
fn shown(p: PathBuf) -> String {
|
||||
let s = p.to_string_lossy().into_owned();
|
||||
|
||||
@@ -25,7 +25,8 @@ pub(super) fn exec(b: &mut dyn Backend, cmd: &str, params: Value) -> Result<Valu
|
||||
}
|
||||
|
||||
pub(super) fn need_ui(b: &dyn Backend, tool: &str) -> Result<(), String> {
|
||||
if b.has_ui() { Ok(()) } else { Err(format!("`{tool}` {}", crate::agents::NEEDS_WINDOW)) }
|
||||
// A window that could not be reached says why, rather than that it isn't open.
|
||||
if b.ui()? { Ok(()) } else { Err(format!("`{tool}` {}", crate::agents::NEEDS_WINDOW)) }
|
||||
}
|
||||
|
||||
/// Paint argument → `paint.setFill` / `paint.setStroke` params.
|
||||
|
||||
@@ -223,7 +223,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"ui.shortcutImportDialog",
|
||||
"Import Shortcut Set…",
|
||||
"",
|
||||
"{path? | dataBase64?, name?} open Import Shortcut Set for a shortcut set another app saved as text (.kys; without a file, pick one): each entry matched to a tool, command or panel, and its key and modifier codes decoded (dialog `shortcutImport`: name, start: defaults|current, remember, rows: [{name, section, line, key, modifiers, target: entry id | \"\" (no equivalent) | null (not chosen), from, choices, on}], keys and mods: {code: {text, from, votes, names}}); Apply assigns the ready rows over Edit › Keyboard Shortcuts' working set, remembers the matches (importMatches.set) and shows Keyboard Shortcuts, whose OK keeps them. File › Open of a .kys opens it too",
|
||||
"{path? | dataBase64?, name?} open Import Shortcut Set for a shortcut set another app saved as text (.kys; without a file, pick one): each entry matched to a tool, command or panel, and its key and modifier codes decoded. The review opens inside Edit › Keyboard Shortcuts, which ui.inspect does not list in `dialogs` and ui.dialog.set does not reach; with a file the reply is {entries, unread}. Without the window, shortcutSet.read reads a file and matches its entries, and importMatches.set stores matches. Apply assigns the ready rows over Edit › Keyboard Shortcuts' working set, remembers the matches (importMatches.set) and shows Keyboard Shortcuts, whose OK keeps them. File › Open of a .kys opens it too",
|
||||
),
|
||||
("view.outline", "Outline", "Cmd+Y", "{} toggle Outline/Preview"),
|
||||
("view.pixelPreview", "Pixel Preview", "Cmd+Alt+Y", "{}"),
|
||||
@@ -1030,7 +1030,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"ui.paramDialog",
|
||||
"Command Dialog",
|
||||
"",
|
||||
"{command, label?, params?} open a parameter dialog for any command. A missing, empty, non-string or unknown command, a label that is neither a string nor null, or params that are neither an object nor null is an error, and no dialog opens. A null label or params is treated as omitted. A plug-in command that is not installed yet waits for the plug-ins still loading. For commands other than edit.findReplace, params.__doc may be an unsigned document uid: the dialog previews and confirms only while that document is active, and OK after a document switch closes it without running the command. An invalid __doc is an error; omitting it keeps the existing behavior. For edit.findReplace it opens Find and Replace (dialog `findReplace`), which stays open: fields find, replace, matchCase, wholeWord, backwards, hiddenLayers, lockedLayers, and action, which ui.dialog.confirm runs: find (the next match, edit.findNext, shown in the dialog with its place among the matches), replace (the match found, edit.replaceMatch), replaceFind (both), replaceAll (edit.findReplace) or done (close). An action whose button the open tab does not show is refused: find runs on the Find and Replace tabs, replace, replaceFind and replaceAll on the Replace tab, done on every tab. After each one action is find again. Replace and Replace & Find change a match that find reached with the find text and options as they are now, and find one otherwise. The dialog opens on the last search, with the fields params gives in its place (a null field gives none; a field of the wrong type is an error, and ui.dialog.confirm then runs no action), and Edit › Find Next goes on from it in the same document while the dialog is closed",
|
||||
"{command, label?, params?} open a parameter dialog for any command. A missing, empty, non-string or unknown command, a label that is neither a string nor null, or params that are neither an object nor null is an error, and no dialog opens. A null label or params is treated as omitted. A plug-in command that is not installed yet waits for the plug-ins still loading. For commands other than edit.findReplace, params.__doc may be an unsigned document uid: the dialog previews and confirms only while that document is active, and OK after a document switch closes it without running the command. An invalid __doc is an error; omitting it keeps the existing behavior. For edit.findReplace it opens Find and Replace (listed last in ui.inspect's `dialogs`, with key null), which stays open: fields find, replace, matchCase, wholeWord, backwards, hiddenLayers, lockedLayers, and action (it also lists tab, more, goToKind, goToTarget and the read-only message), which ui.dialog.confirm runs: find (the next match, edit.findNext, shown in the dialog with its place among the matches), replace (the match found, edit.replaceMatch), replaceFind (both), replaceAll (edit.findReplace) or done (close). An action whose button the open tab does not show is refused: find runs on the Find and Replace tabs, replace, replaceFind and replaceAll on the Replace tab, done on every tab. After each one action is find again. Replace and Replace & Find change a match that find reached with the find text and options as they are now, and find one otherwise. The dialog opens on the last search, with the fields params gives in its place (a null field gives none; a field of the wrong type is an error, and ui.dialog.confirm then runs no action), and Edit › Find Next goes on from it in the same document while the dialog is closed",
|
||||
),
|
||||
(
|
||||
"ui.recolorDialog",
|
||||
@@ -1555,7 +1555,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.commonTangents|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.type.numbers|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.arrange.markBounds|addon.color.applyNearestSwatch|addon.color.randomFill|addon.select.byArtboards|addon.select.editPointsOnly|addon.document.floodFillArtboards|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; addon.document.floodFillArtboards is refused, with the command's reason, while that command is disabled (for example with no document open); 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.type.numbers|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.arrange.artboardGuides|addon.arrange.markBounds|addon.color.applyNearestSwatch|addon.color.randomFill|addon.select.byArtboards|addon.select.editPointsOnly|addon.document.floodFillArtboards|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`); addon.arrange.artboardGuides fails when the document has no artboards; 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; addon.document.floodFillArtboards is refused, with the command's reason, while that command is disabled (for example with no document open); 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",
|
||||
@@ -2003,7 +2003,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"file.print",
|
||||
"Print…",
|
||||
"Cmd+P",
|
||||
"{} open the Print dialog (dialog `print`: the print.setup settings, preset (setting it loads that print preset; Save Preset… saves them as one), printer, toFile; on desktop, installed printers appear once the background lookup has returned and the dialog has applied the list; ui.dialog.set accepts a named printer once it appears in the list; PDF File is available at once; Print keeps the settings with the document and prints, Done (discard: true) only keeps them); with params {preset? (a print preset's name: its settings instead of the document's), settings? (over the document's or the preset's), printer? (print.printers name; \"\" the default), paper? (the printer driver's paper keyword, such as Letter or CR80: the queue is asked for that paper as the job's media on macOS and Linux; on Windows, with file output, with directPdf, or anything but a keyword it is an error; the Print dialog sends the driver's keyword for the Size chosen), toFile?, path?, format?: pdf|postscript, level?, flattenerPreset?, maxPages? (as engine file.print)} print without it: the print-ready PDF (engine file.print) goes to the printer → {pages, printer, printed: true, warnings}; with toFile, a path or no printing here (no print service) it is saved as a PDF at path (else a picked file, the web downloads it) → {path, pages, printed: false, warnings}; a PostScript file (format postscript, or a .ps path) is always saved that way; a job of more than maxPages pages is neither printed nor saved → {pages, format}",
|
||||
"{} open the Print dialog (listed last in ui.inspect's `dialogs`, with key null; fields: the print.setup settings, `preset` (setting it loads that print preset; Save Preset… saves them as one), `printer` (a print.printers name, or PDF File, with which Print saves the job as a PDF), `section` and `sheet`; on desktop, installed printers appear once the background lookup has returned and the dialog has applied the list; ui.dialog.set accepts a named printer once it appears in the list; PDF File is available at once; Print keeps the settings with the document and prints, Done (`choice`: done, then ui.dialog.confirm) only keeps them); with params {preset? (a print preset's name: its settings instead of the document's), settings? (over the document's or the preset's), printer? (print.printers name; \"\" the default), paper? (the printer driver's paper keyword, such as Letter or CR80: the queue is asked for that paper as the job's media on macOS and Linux; on Windows, with file output, with directPdf, or anything but a keyword it is an error; the Print dialog sends the driver's keyword for the Size chosen), toFile?, path?, format?: pdf|postscript, level?, flattenerPreset?, maxPages? (as engine file.print)} print without it: the print-ready PDF (engine file.print) goes to the printer → {pages, printer, printed: true, warnings}; with toFile, a path or no printing here (no print service) it is saved as a PDF at path (else a picked file, the web downloads it) → {path, pages, printed: false, warnings}; a PostScript file (format postscript, or a .ps path) is always saved that way; a job of more than maxPages pages is neither printed nor saved → {pages, format}",
|
||||
),
|
||||
(
|
||||
"print.printers",
|
||||
@@ -2022,7 +2022,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"ui.printPresetDialog",
|
||||
"Print Preset",
|
||||
"",
|
||||
"{name?: a saved preset to edit | preset?: the preset a new one starts from (default [Default])} open the preset editor (dialog `printPreset`: the Print dialog's settings fields plus `name`); OK runs print.presets.save and returns to Print Presets",
|
||||
"{name?: a saved preset to edit | preset?: the preset a new one starts from (default [Default])} open the preset editor (listed last in ui.inspect's `dialogs`, with key null; fields: the Print dialog's settings fields plus `name`); OK runs print.presets.save and returns to Print Presets",
|
||||
),
|
||||
(
|
||||
"plugin.dialog",
|
||||
@@ -2106,7 +2106,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"ui.checkScript",
|
||||
"Check Script…",
|
||||
"",
|
||||
"{path? | data? | dataBase64?, name?, includes?: true with a path} check a script written for the reference app without running it (script.check; with a path, the files its #include lines name are checked too) and show the report (dialog `scriptCheck`: `report`, script.check's result; Copy Report copies it as JSON); without a file pick one (the web opens the browser's file picker; File › Open of a .jsx, .jsxinc or .jsxbin file shows the report too)",
|
||||
"{path? | data? | dataBase64?, name?, includes?: true with a path} check a script written for the reference app without running it (script.check; with a path, the files its #include lines name are checked too) and show the report (listed last in ui.inspect's `dialogs`, with key null; fields `lines`, `notes` and `groups`); with a file the reply is script.check's result, and the report's Copy button copies the report as text; without a file pick one (the web opens the browser's file picker; File › Open of a .jsx, .jsxinc or .jsxbin file shows the report too)",
|
||||
),
|
||||
(
|
||||
"ui.perspectiveGridDialog",
|
||||
@@ -2234,6 +2234,11 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"",
|
||||
"{plane?: left|right|ground (default: the active plane)} open the plane's options, as double-clicking its plane widget does (dialog `perspectivePlane`: location (pt along the plane's normal), objects: none|move|copy): OK runs perspective.plane.move",
|
||||
),
|
||||
("ui.findAndReplace", "Find and Replace…", "", "{} open the Find and Replace dialog (Edit › Find and Replace…; dialog `findReplace`)"),
|
||||
(
|
||||
"ui.findAndReplace",
|
||||
"Find and Replace…",
|
||||
"",
|
||||
"{} open the Find and Replace dialog (Edit › Find and Replace…; listed last in ui.inspect's `dialogs`, with key null; fields and buttons as ui.paramDialog with edit.findReplace)",
|
||||
),
|
||||
("ui.retype", "Retype", "", "{} open the Retype panel (Window › Retype) or start Retype"),
|
||||
];
|
||||
@@ -563,7 +563,8 @@ impl Renderer {
|
||||
f.doc.setup.highlight_substituted_glyphs,
|
||||
o.highlight_alternate_glyphs,
|
||||
));
|
||||
(vectorcraft_text::layout_inputs(), crate::proof::overprints(f.opts), highlights).hash(&mut h);
|
||||
// Color bitmap glyphs are sampled as images are (`draw_glyph_image`).
|
||||
(vectorcraft_text::layout_inputs(), crate::proof::overprints(f.opts), highlights, o.smooth_images).hash(&mut h);
|
||||
}
|
||||
if reads.plugins || (doc.plugins && (reads.symbols || reads.patterns)) {
|
||||
(effects::plugin_revision(), doc.names, doc.patterns).hash(&mut h);
|
||||
|
||||
@@ -285,11 +285,14 @@ fn area_spans(from: usize, to: usize) -> Vec<Vec<(usize, f64)>> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A rendered image (premultiplied RGBA8, row-major).
|
||||
pub struct Rendered {
|
||||
/// A rendered image (premultiplied RGBA8, row-major). Its pixels are bytes, or, from
|
||||
/// [`crate::Renderer::render_words`], words of four bytes that hold each pixel's bytes in memory
|
||||
/// in the same order: a buffer aligned to four bytes, which a 4-byte pixel type can take over
|
||||
/// without a copy.
|
||||
pub struct Rendered<P = Vec<u8>> {
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
pub pixels: Vec<u8>,
|
||||
pub pixels: P,
|
||||
}
|
||||
|
||||
impl Rendered {
|
||||
|
||||
@@ -34,8 +34,8 @@ use crate::{Frame, RenderOptions, Rendered, Renderer};
|
||||
const MAX_TILE_PX: f64 = 2048.0;
|
||||
|
||||
/// What a tile is kept under: the pattern's name, the bits of its raster scale
|
||||
/// ([`raster_scale`]), ink plane and undecoded-image mark setting.
|
||||
type TileKey = (String, u64, Ink, bool);
|
||||
/// ([`raster_scale`]), ink plane, and the undecoded-image mark and image smoothing settings.
|
||||
type TileKey = (String, u64, Ink, (bool, bool));
|
||||
|
||||
/// What a tile was drawn from besides its pattern's own art, for art that shows more than itself:
|
||||
/// the art of every pattern and symbol and the pixels of every image in the document, the
|
||||
@@ -177,13 +177,13 @@ fn rasterize(
|
||||
region: Rect,
|
||||
size: (u16, u16),
|
||||
ink: Ink,
|
||||
mark_undecoded_images: bool,
|
||||
(mark_undecoded_images, smooth_images): (bool, bool),
|
||||
) -> (Pixmap, bool) {
|
||||
let (w, h) = (size.0.max(1), size.1.max(1));
|
||||
let mut ctx = crate::single_threaded_context(w, h);
|
||||
let view = Affine::scale_non_uniform(w as f64 / region.width().max(1e-9), h as f64 / region.height().max(1e-9))
|
||||
* Affine::translate(-region.origin().to_vec2());
|
||||
let opts = RenderOptions { mark_undecoded_images, ..Default::default() };
|
||||
let opts = RenderOptions { mark_undecoded_images, smooth_images, ..Default::default() };
|
||||
r.image_left_out = Some(false);
|
||||
let pattern_images_left_out = images_left_out();
|
||||
r.check_plugins(doc);
|
||||
@@ -268,7 +268,8 @@ pub(crate) fn set_pattern_paint(ctx: &mut RenderContext, name: &str, xf: Affine,
|
||||
let (pw, ph) = def.period();
|
||||
let scale = raster_scale(s, (pw, ph));
|
||||
let params = (def.tile, def.tile_type, def.overlap);
|
||||
let key = (name.to_string(), scale.to_bits(), ink, f.opts.mark_undecoded_images);
|
||||
let images = (f.opts.mark_undecoded_images, f.opts.smooth_images);
|
||||
let key = (name.to_string(), scale.to_bits(), ink, images);
|
||||
let cms = vectorcraft_color::cms::active();
|
||||
let hit = CACHE.with(|c| {
|
||||
let mut c = c.borrow_mut();
|
||||
@@ -297,9 +298,7 @@ pub(crate) fn set_pattern_paint(ctx: &mut RenderContext, name: &str, xf: Affine,
|
||||
let w = (pw * scale).ceil().clamp(1.0, 4096.0) as u16;
|
||||
let h = (ph * scale).ceil().clamp(1.0, 4096.0) as u16;
|
||||
let before = crate::paint::decode_failures();
|
||||
let Some((pm, image_left_out)) =
|
||||
with_tile_renderer(|r| rasterize(r, doc, def, Rect::new(0.0, 0.0, pw, ph), (w, h), ink, f.opts.mark_undecoded_images))
|
||||
else {
|
||||
let Some((pm, image_left_out)) = with_tile_renderer(|r| rasterize(r, doc, def, Rect::new(0.0, 0.0, pw, ph), (w, h), ink, images)) else {
|
||||
ctx.set_paint(missing());
|
||||
return true;
|
||||
};
|
||||
@@ -325,7 +324,9 @@ pub(crate) fn set_pattern_paint(ctx: &mut RenderContext, name: &str, xf: Affine,
|
||||
(pm, sx, sy)
|
||||
}
|
||||
};
|
||||
let sampler = ImageSampler { x_extend: Extend::Repeat, y_extend: Extend::Repeat, quality: ImageQuality::Medium, alpha: 1.0 };
|
||||
// With image smoothing off the tile is drawn with hard pixel edges, as its images were.
|
||||
let quality = if f.opts.smooth_images { ImageQuality::Medium } else { ImageQuality::Low };
|
||||
let sampler = ImageSampler { x_extend: Extend::Repeat, y_extend: Extend::Repeat, quality, alpha: 1.0 };
|
||||
ctx.set_paint(vello_cpu::Image { image: vello_cpu::ImageSource::Pixmap(pm), sampler });
|
||||
ctx.set_paint_transform(xf * Affine::scale_non_uniform(1.0 / sx, 1.0 / sy));
|
||||
true
|
||||
@@ -338,7 +339,7 @@ pub fn render_pattern_swatch(doc: &Document, name: &str, size: u32) -> Option<Re
|
||||
let side = w.max(h);
|
||||
let region = Rect::from_center_size((w / 2.0, h / 2.0), (side, side));
|
||||
let px = size.clamp(1, 1024) as u16;
|
||||
let (pm, _) = with_tile_renderer(|r| rasterize(r, doc, def, region, (px, px), Ink::Display, false))?;
|
||||
let (pm, _) = with_tile_renderer(|r| rasterize(r, doc, def, region, (px, px), Ink::Display, (false, true)))?;
|
||||
Some(Rendered { width: px as u32, height: px as u32, pixels: crate::group::into_bytes(pm) })
|
||||
}
|
||||
|
||||
|
||||
@@ -277,6 +277,34 @@ fn kept_tiles_count_the_images_they_could_not_decode() {
|
||||
assert_eq!(rasterized, 1, "the later frames draw from the tile kept");
|
||||
}
|
||||
|
||||
/// The images in a pattern's tile are drawn as the frame draws images (File Handling › Display
|
||||
/// Bitmaps as Anti-aliased Images, #10712): smoothed, a scaled-up 2×2 checker shows greys between
|
||||
/// its squares; not smoothed, every pixel is one of its own colors. Tiles drawn each way are kept
|
||||
/// apart.
|
||||
#[test]
|
||||
fn tiles_smooth_their_images_when_the_frame_does() {
|
||||
use vectorcraft_doc::{ImageBlob, ImageObject};
|
||||
let img = image::RgbaImage::from_fn(2, 2, |x, y| image::Rgba(if (x + y) % 2 == 0 { [0, 0, 0, 255] } else { [255, 255, 255, 255] }));
|
||||
let mut png = vec![];
|
||||
img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
|
||||
let mut d = doc_with_pattern(TileType::Grid);
|
||||
d.images.insert("checker".into(), ImageBlob::new("image/png", png));
|
||||
// The 2×2 image fills the 20×20 tile.
|
||||
let im =
|
||||
ImageObject { key: "checker".into(), width: 2, height: 2, xf: Affine::scale(10.0), link: None, placement: Default::default(), pixels: None };
|
||||
d.patterns[0].art = vec![Arc::new(Node::new(NodeId(901), NodeKind::Image(Box::new(im))))];
|
||||
let mut r = Renderer::new();
|
||||
let mut greys = |smooth_images: bool| {
|
||||
let opts = RenderOptions { background: Some([255, 255, 255, 255]), smooth_images, ..Default::default() };
|
||||
let out = r.render(&d, 80, 80, Affine::scale(4.0), &opts);
|
||||
// Across the first tile, 80 pixels wide at this zoom.
|
||||
(2..78).filter(|x| (16..240).contains(&out.pixel(*x, 20)[0])).count()
|
||||
};
|
||||
assert_eq!(greys(false), 0, "not smoothed: black, then white");
|
||||
assert!(greys(true) >= 4, "smoothed: a ramp from black to white");
|
||||
assert_eq!(greys(false), 0, "not smoothed again: the smoothed tile is not shown");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_pattern_is_grey() {
|
||||
let mut d = doc_with_pattern(TileType::Grid);
|
||||
|
||||
@@ -49,9 +49,14 @@ const MAX_BYTES: usize = 4 * BUDGET;
|
||||
/// The smallest zoom step (device pixels per point).
|
||||
const MIN_STEP: f64 = 1.0 / 64.0;
|
||||
|
||||
/// A bitmap's identity: the file shown (its key), the zoom step's bits, and whether images whose
|
||||
/// pixels can't be decoded are marked ([`crate::RenderOptions::mark_undecoded_images`]).
|
||||
type BitmapKey = (String, u64, bool);
|
||||
/// A bitmap's identity: the file shown (its key), the zoom step's bits, and how its images are
|
||||
/// drawn: whether images whose pixels can't be decoded are marked
|
||||
/// ([`crate::RenderOptions::mark_undecoded_images`]) and whether images are smoothed
|
||||
/// ([`crate::RenderOptions::smooth_images`]).
|
||||
type BitmapKey = (String, u64, Images);
|
||||
|
||||
/// How a bitmap's images are drawn: (marked when undecoded, smoothed).
|
||||
type Images = (bool, bool);
|
||||
|
||||
struct Bitmap {
|
||||
pm: Arc<Pixmap>,
|
||||
@@ -160,14 +165,16 @@ pub(crate) fn scheduled(key: &str) -> usize {
|
||||
#[cfg(test)]
|
||||
pub(crate) fn mark_unkept(key: &str, step: f64) {
|
||||
for mark in [false, true] {
|
||||
lock(&UNKEPT).insert((key.to_string(), step.to_bits(), mark));
|
||||
for smooth in [false, true] {
|
||||
lock(&UNKEPT).insert((key.to_string(), step.to_bits(), (mark, smooth)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `object`'s file (`blob`) as a bitmap of `step` device pixels per point, made here and now.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn bitmap(object: &PlacedDocument, blob: &ImageBlob, step: f64, mark_undecoded_images: bool) -> Option<Pixmap> {
|
||||
make(&mut Renderer::new(), object, blob, step, mark_undecoded_images)
|
||||
make(&mut Renderer::new(), object, blob, step, (mark_undecoded_images, true))
|
||||
}
|
||||
|
||||
/// The zoom step for `scale` device pixels per point: the power of two at or above it.
|
||||
@@ -184,9 +191,9 @@ impl Bitmaps {
|
||||
Some(b.pm.clone())
|
||||
}
|
||||
|
||||
/// The bitmap of another step of the same file, with the same marks on undecoded images, the
|
||||
/// The bitmap of another step of the same file, with its images drawn the same way, the
|
||||
/// nearest to `step`.
|
||||
fn nearest(&self, key: &str, step: f64, mark: bool) -> Option<(Arc<Pixmap>, f64)> {
|
||||
fn nearest(&self, key: &str, step: f64, mark: Images) -> Option<(Arc<Pixmap>, f64)> {
|
||||
self.map
|
||||
.iter()
|
||||
.filter(|((k, _, m), _)| k == key && *m == mark)
|
||||
@@ -368,11 +375,12 @@ pub(crate) fn enter_layer(n: &Node) -> Option<InMode> {
|
||||
/// Render `art` of a placed document's file (`doc`, its resources) into `w`×`h` transparent
|
||||
/// pixels through `view`, the placed documents inside it one level deeper.
|
||||
pub fn render_inside(r: &mut Renderer, doc: &vectorcraft_doc::Document, art: &Arc<Node>, w: u16, h: u16, view: Affine) -> Option<crate::Rendered> {
|
||||
render_inside_marked(r, doc, art, w, h, view, false)
|
||||
render_inside_marked(r, doc, art, w, h, view, (false, true))
|
||||
}
|
||||
|
||||
/// [`render_inside`], drawing images whose pixels can't be decoded as crossed boxes when
|
||||
/// `mark_undecoded_images` is set ([`crate::RenderOptions::mark_undecoded_images`]).
|
||||
/// `mark_undecoded_images` is set ([`crate::RenderOptions::mark_undecoded_images`]), and images
|
||||
/// smoothed when `smooth_images` is set ([`crate::RenderOptions::smooth_images`]).
|
||||
fn render_inside_marked(
|
||||
r: &mut Renderer,
|
||||
doc: &vectorcraft_doc::Document,
|
||||
@@ -380,18 +388,18 @@ fn render_inside_marked(
|
||||
w: u16,
|
||||
h: u16,
|
||||
view: Affine,
|
||||
mark_undecoded_images: bool,
|
||||
(mark_undecoded_images, smooth_images): Images,
|
||||
) -> Option<crate::Rendered> {
|
||||
let _inside = Inside::enter();
|
||||
let opts = crate::RenderOptions { mark_undecoded_images, ..Default::default() };
|
||||
let opts = crate::RenderOptions { mark_undecoded_images, smooth_images, ..Default::default() };
|
||||
r.render_node_with(doc, art, w, h, view, &opts)
|
||||
}
|
||||
|
||||
/// `object`'s file (`blob`) as a bitmap of `step` device pixels per point of its box: from its
|
||||
/// preview when that is all there is and is fine enough, else from the file (read again when
|
||||
/// needed; the preview when it can't be). Images whose pixels can't be decoded are drawn as
|
||||
/// crossed boxes when `mark_undecoded_images` is set.
|
||||
fn make(r: &mut Renderer, object: &PlacedDocument, blob: &ImageBlob, step: f64, mark_undecoded_images: bool) -> Option<Pixmap> {
|
||||
/// crossed boxes when its first flag is set, and images are smoothed when its second is.
|
||||
fn make(r: &mut Renderer, object: &PlacedDocument, blob: &ImageBlob, step: f64, images: Images) -> Option<Pixmap> {
|
||||
let (w, h) = (pixels(object.width * step), pixels(object.height * step));
|
||||
let preview = if blob.is_proxy() { Some(blob.bytes.clone()) } else { blob.proxy.clone() };
|
||||
let full = match blob.is_proxy() {
|
||||
@@ -404,7 +412,7 @@ fn make(r: &mut Renderer, object: &PlacedDocument, blob: &ImageBlob, step: f64,
|
||||
let f = e.frame;
|
||||
let (sx, sy) = (w as f64 / f.width(), h as f64 / f.height());
|
||||
let view = Affine::scale_non_uniform(sx, sy) * Affine::translate((-f.x0, -f.y0));
|
||||
let img = render_inside_marked(r, &e.doc, &e.art, w, h, view, mark_undecoded_images)?;
|
||||
let img = render_inside_marked(r, &e.doc, &e.art, w, h, view, images)?;
|
||||
let data = img.pixels.as_chunks::<4>().0.iter().map(|&[r, g, b, a]| vello_cpu::color::PremulRgba8 { r, g, b, a }).collect();
|
||||
Some(Pixmap::from_parts(data, w, h))
|
||||
}
|
||||
@@ -514,7 +522,7 @@ fn run_here(job: Job) {
|
||||
/// does where no worker starts, inside `scope`.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn make_here(object: &PlacedDocument, blob: ImageBlob, step: f64, scope: Scoped) {
|
||||
let key = (object.key.clone(), step.to_bits(), false);
|
||||
let key = (object.key.clone(), step.to_bits(), (false, true));
|
||||
lock(&PENDING).insert(key.clone());
|
||||
run_here(Job { key, object: object.clone(), blob, step, keep: 0, scope: Some(scope) });
|
||||
}
|
||||
@@ -608,7 +616,8 @@ impl Renderer {
|
||||
return false;
|
||||
}
|
||||
let Some(blob) = f.doc.images.get(&p.key).cloned() else { return true };
|
||||
let key = (p.key.clone(), step.to_bits(), f.opts.mark_undecoded_images);
|
||||
let images = (f.opts.mark_undecoded_images, f.opts.smooth_images);
|
||||
let key = (p.key.clone(), step.to_bits(), images);
|
||||
// Not kept past [`MAX_BYTES`]: drawn exactly.
|
||||
if lock(&UNKEPT).contains(&key) {
|
||||
return false;
|
||||
@@ -618,7 +627,7 @@ impl Renderer {
|
||||
// The clock when this frame first drew a placed document's bitmap.
|
||||
let keep = *self.placed_frame.get_or_insert(b.clock);
|
||||
let found = b.get(&key);
|
||||
let nearest = if found.is_none() { b.nearest(&p.key, step, f.opts.mark_undecoded_images) } else { None };
|
||||
let nearest = if found.is_none() { b.nearest(&p.key, step, images) } else { None };
|
||||
(found, nearest, keep)
|
||||
};
|
||||
let shown = match found {
|
||||
@@ -629,14 +638,18 @@ impl Renderer {
|
||||
schedule(Job { key, object: p.clone(), blob, step, keep, scope: SCOPE_CAPTURE.get().map(|capture| capture()) });
|
||||
// Made here and now (no threads) or meanwhile another step's.
|
||||
let mut b = lock(&BITMAPS);
|
||||
b.get(&(p.key.clone(), step.to_bits(), f.opts.mark_undecoded_images)).or(nearest.map(|n| n.0))
|
||||
b.get(&(p.key.clone(), step.to_bits(), images)).or(nearest.map(|n| n.0))
|
||||
}
|
||||
};
|
||||
let rect = Rect::new(0.0, 0.0, p.width, p.height);
|
||||
match shown {
|
||||
Some(pm) => {
|
||||
let (sx, sy) = (p.width / pm.width().max(1) as f64, p.height / pm.height().max(1) as f64);
|
||||
ctx.set_paint(vello_cpu::Image { image: vello_cpu::ImageSource::Pixmap(pm), sampler: peniko::ImageSampler::default() });
|
||||
// With image smoothing off a bitmap (or a saved preview standing in for the file)
|
||||
// keeps hard pixel edges when it is scaled.
|
||||
let quality = if f.opts.smooth_images { peniko::ImageQuality::Medium } else { peniko::ImageQuality::Low };
|
||||
let sampler = peniko::ImageSampler { quality, ..Default::default() };
|
||||
ctx.set_paint(vello_cpu::Image { image: vello_cpu::ImageSource::Pixmap(pm), sampler });
|
||||
ctx.set_transform(m);
|
||||
ctx.set_paint_transform(Affine::scale_non_uniform(sx, sy));
|
||||
ctx.fill_rect(&kurbo::Rect::new(rect.x0, rect.y0, rect.x1, rect.y1));
|
||||
@@ -675,7 +688,7 @@ mod tests {
|
||||
let mut b = Bitmaps::default();
|
||||
// 400 bytes each: a budget of 1,000 bytes and at most 2,000.
|
||||
let limits = (1000, 2000);
|
||||
let key = |name: &str| (name.to_string(), 1f64.to_bits(), false);
|
||||
let key = |name: &str| (name.to_string(), 1f64.to_bits(), (false, true));
|
||||
for name in ["a", "b", "c"] {
|
||||
assert!(b.insert(key(name), Pixmap::new(10, 10), 1.0, 0, limits));
|
||||
}
|
||||
@@ -696,15 +709,16 @@ mod tests {
|
||||
}
|
||||
|
||||
/// While a bitmap is made, another step's bitmap stands in only when it has the same marks on
|
||||
/// undecoded images.
|
||||
/// undecoded images and the same image smoothing.
|
||||
#[test]
|
||||
fn a_stand_in_bitmap_has_the_same_marks() {
|
||||
let mut b = Bitmaps::default();
|
||||
let limits = (BUDGET, MAX_BYTES);
|
||||
assert!(b.insert(("a".into(), 1f64.to_bits(), false), Pixmap::new(10, 10), 1.0, 0, limits));
|
||||
assert!(b.insert(("a".into(), 4f64.to_bits(), true), Pixmap::new(40, 40), 4.0, 0, limits));
|
||||
assert_eq!(b.nearest("a", 2.0, false).map(|n| n.1), Some(1.0));
|
||||
assert_eq!(b.nearest("a", 2.0, true).map(|n| n.1), Some(4.0));
|
||||
assert!(b.nearest("b", 2.0, false).is_none());
|
||||
assert!(b.insert(("a".into(), 1f64.to_bits(), (false, true)), Pixmap::new(10, 10), 1.0, 0, limits));
|
||||
assert!(b.insert(("a".into(), 4f64.to_bits(), (true, true)), Pixmap::new(40, 40), 4.0, 0, limits));
|
||||
assert_eq!(b.nearest("a", 2.0, (false, true)).map(|n| n.1), Some(1.0));
|
||||
assert_eq!(b.nearest("a", 2.0, (true, true)).map(|n| n.1), Some(4.0));
|
||||
assert!(b.nearest("b", 2.0, (false, true)).is_none());
|
||||
assert!(b.nearest("a", 2.0, (false, false)).is_none(), "smoothed bitmaps don't stand in for hard-edged ones");
|
||||
}
|
||||
}
|
||||
+121
-27
@@ -117,9 +117,32 @@ impl Renderer {
|
||||
self.render_document(doc, width, height, view, opts, None)
|
||||
}
|
||||
|
||||
/// [`Self::render`] with the pixels in words of four bytes ([`Rendered`]), rendered into
|
||||
/// that buffer.
|
||||
pub fn render_words(&mut self, doc: &Document, width: u32, height: u32, view: Affine, opts: &RenderOptions) -> Rendered<Vec<u32>> {
|
||||
self.render_document(doc, width, height, view, opts, None)
|
||||
}
|
||||
|
||||
/// Render a plain RGB canvas patch using a separate renderer. Raster effects and offscreen
|
||||
/// group compositing require the full render.
|
||||
pub fn render_plain_patch(&mut self, doc: &Document, width: u32, height: u32, view: Affine, opts: &RenderOptions) -> Option<Rendered> {
|
||||
self.plain_patch(doc, width, height, view, opts)
|
||||
}
|
||||
|
||||
/// [`Self::render_plain_patch`] with the pixels in words of four bytes, as
|
||||
/// [`Self::render_words`] returns them.
|
||||
pub fn render_plain_patch_words(
|
||||
&mut self,
|
||||
doc: &Document,
|
||||
width: u32,
|
||||
height: u32,
|
||||
view: Affine,
|
||||
opts: &RenderOptions,
|
||||
) -> Option<Rendered<Vec<u32>>> {
|
||||
self.plain_patch(doc, width, height, view, opts)
|
||||
}
|
||||
|
||||
fn plain_patch<P: FramePixels>(&mut self, doc: &Document, width: u32, height: u32, view: Affine, opts: &RenderOptions) -> Option<Rendered<P>> {
|
||||
if doc.color_mode != vectorcraft_doc::ColorMode::Rgb || opts.mask_view.is_some() || opts.supersample {
|
||||
return None;
|
||||
}
|
||||
@@ -128,7 +151,7 @@ impl Renderer {
|
||||
(!hit.get()).then_some(image)
|
||||
}
|
||||
|
||||
fn render_document(
|
||||
fn render_document<P: FramePixels>(
|
||||
&mut self,
|
||||
doc: &Document,
|
||||
width: u32,
|
||||
@@ -136,7 +159,7 @@ impl Renderer {
|
||||
view: Affine,
|
||||
opts: &RenderOptions,
|
||||
patch: Option<&std::cell::Cell<bool>>,
|
||||
) -> Rendered {
|
||||
) -> Rendered<P> {
|
||||
let _lent = vectorcraft_text::FontDb::global().lend_composite_fonts(&doc.composite_fonts);
|
||||
let _frame = vectorcraft_text::KeptLayoutsFrame::begin();
|
||||
self.render_as(doc, width, height, view, opts, false, 1, patch)
|
||||
@@ -147,7 +170,7 @@ impl Renderer {
|
||||
/// pixel of the output in pixels of this render: the supersampling factor while an export
|
||||
/// draws its art at several times its size, else 1 ([`Frame::output`]).
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn render_as(
|
||||
fn render_as<P: FramePixels>(
|
||||
&mut self,
|
||||
doc: &Document,
|
||||
width: u32,
|
||||
@@ -157,16 +180,18 @@ impl Renderer {
|
||||
inks: bool,
|
||||
cell: u32,
|
||||
patch: Option<&std::cell::Cell<bool>>,
|
||||
) -> Rendered {
|
||||
) -> Rendered<P> {
|
||||
let start = now();
|
||||
if opts.supersample && opts.anti_alias == AntiAlias::Art && opts.mask_view.is_none() {
|
||||
let (w, h) = (width.clamp(1, MAX_CONTEXT_SIDE), height.clamp(1, MAX_CONTEXT_SIDE));
|
||||
if let Some(k) = supersample_factor(w, h) {
|
||||
let hard = RenderOptions { anti_alias: AntiAlias::None, supersample: false, ..opts.clone() };
|
||||
let hairline = std::mem::replace(&mut self.hairline, f64::from(k));
|
||||
let big = self.render_as(doc, w * k, h * k, Affine::scale(f64::from(k)) * view, &hard, inks, k, patch);
|
||||
let big: Rendered = self.render_as(doc, w * k, h * k, Affine::scale(f64::from(k)) * view, &hard, inks, k, patch);
|
||||
self.hairline = hairline;
|
||||
let pixels = downsample(&big.pixels, big.width as usize, big.height as usize, k as usize);
|
||||
drop(big);
|
||||
let pixels = P::from_bytes(pixels);
|
||||
self.stats.micros = now().saturating_sub(start);
|
||||
return Rendered { width: w, height: h, pixels };
|
||||
}
|
||||
@@ -203,12 +228,13 @@ impl Renderer {
|
||||
self.begin_frame();
|
||||
// View Opacity Mask: the mask's coverage in greyscale instead of the artwork.
|
||||
if let Some(m) = opts.mask_view.and_then(|id| doc.node(id)).and_then(|n| n.extras().mask.as_deref()) {
|
||||
let pixels = self
|
||||
.mask_values(&frame, m, w, h)
|
||||
.unwrap_or_else(|| vec![0; w as usize * h as usize])
|
||||
.into_iter()
|
||||
.flat_map(|v| [v, v, v, 255])
|
||||
.collect();
|
||||
let pixels = P::from_bytes(
|
||||
self.mask_values(&frame, m, w, h)
|
||||
.unwrap_or_else(|| vec![0; w as usize * h as usize])
|
||||
.into_iter()
|
||||
.flat_map(|v| [v, v, v, 255])
|
||||
.collect(),
|
||||
);
|
||||
self.end_frame();
|
||||
self.stats.symbol_art = symbols.art_measured();
|
||||
self.stats.micros = now().saturating_sub(start);
|
||||
@@ -219,23 +245,26 @@ impl Renderer {
|
||||
// proof that preserves the numbers, when one is on: the planes hold the inks as they
|
||||
// are, images included).
|
||||
let planes = if proof::preserving(opts).is_some() { None } else { frame.plates };
|
||||
let cmy = self.draw_frame(&Frame { ink: Ink::Cmy, plates: planes, ..frame }, w, h);
|
||||
let cmy: Vec<u8> = self.draw_frame(&Frame { ink: Ink::Cmy, plates: planes, ..frame }, w, h);
|
||||
let stats = self.stats;
|
||||
let k = self.draw_frame(&Frame { ink: Ink::K, plates: planes, ..frame }, w, h);
|
||||
let k: Vec<u8> = self.draw_frame(&Frame { ink: Ink::K, plates: planes, ..frame }, w, h);
|
||||
self.stats = stats;
|
||||
if inks {
|
||||
let pixels = if inks {
|
||||
ink::amounts(&cmy, &k)
|
||||
} else {
|
||||
let (pixels, composed) = ink::compose(&cmy, &k, opts, threads);
|
||||
self.stats.ink_threads = composed;
|
||||
pixels
|
||||
}
|
||||
};
|
||||
drop((cmy, k));
|
||||
P::from_bytes(pixels)
|
||||
} else {
|
||||
self.draw_frame(&frame, w, h)
|
||||
};
|
||||
self.end_frame();
|
||||
if !inks && !pixels.is_empty() {
|
||||
proof::post(&mut pixels, opts);
|
||||
let bytes = pixels.bytes_mut();
|
||||
if !inks && !bytes.is_empty() {
|
||||
proof::post(bytes, opts);
|
||||
}
|
||||
self.stats.symbol_art = symbols.art_measured();
|
||||
self.stats.micros = now().saturating_sub(start);
|
||||
@@ -325,7 +354,7 @@ impl Renderer {
|
||||
/// Draw frame `f` (`w`×`h` pixels): the artboards and the page's art, then the background
|
||||
/// under them. The art blends only with itself, as it does on the canvas, where the paper is
|
||||
/// drawn apart from it: a Screen glow on the bare page stays visible on a white background (#6125).
|
||||
fn draw_frame(&mut self, f: &Frame, w: u16, h: u16) -> Vec<u8> {
|
||||
fn draw_frame<P: FramePixels>(&mut self, f: &Frame, w: u16, h: u16) -> P {
|
||||
let (threads, opts) = (self.threads, f.opts);
|
||||
let kept = self.contexts.iter().position(|(t, c)| *t == threads && c.width() == w && c.height() == h);
|
||||
let mut ctx = match kept.map(|i| self.contexts.remove(i)) {
|
||||
@@ -366,20 +395,19 @@ impl Renderer {
|
||||
} else {
|
||||
self.draw_page(&mut ctx, f);
|
||||
}
|
||||
let pm = if f.patch_rejected() {
|
||||
let pixels = if f.patch_rejected() {
|
||||
self.picture = None;
|
||||
None
|
||||
} else {
|
||||
Some(self.finish(&mut ctx, self.raster))
|
||||
Some(P::finish(self, &mut ctx))
|
||||
};
|
||||
self.contexts.push((threads, ctx));
|
||||
if self.contexts.len() > 2 {
|
||||
self.contexts.remove(0);
|
||||
}
|
||||
let Some(pm) = pm else { return Vec::new() };
|
||||
let mut pixels = group::into_bytes(pm);
|
||||
let Some(mut pixels) = pixels else { return P::from_bytes(Vec::new()) };
|
||||
if let Some(bg) = opts.background {
|
||||
over_background(&mut pixels, f.ink.fixed8(screen_under_art(f, bg)));
|
||||
over_background(pixels.bytes_mut(), f.ink.fixed8(screen_under_art(f, bg)));
|
||||
}
|
||||
pixels
|
||||
}
|
||||
@@ -413,15 +441,24 @@ impl Renderer {
|
||||
/// Render one artboard (or any document rect) at `scale` pixels per point, transparent or on white,
|
||||
/// as exported: template layers and guides are left out.
|
||||
pub fn render_region(&mut self, doc: &Document, region: Rect, scale: f64, white: bool) -> Rendered {
|
||||
let opts = RenderOptions { background: white.then_some([255, 255, 255, 255]), skip_templates: true, ..Default::default() };
|
||||
self.render_region_with(doc, region, scale, &opts)
|
||||
self.region(doc, region, scale, ®ion_options(white))
|
||||
}
|
||||
|
||||
/// [`Self::render_region`] with the pixels in words of four bytes, as [`Self::render_words`]
|
||||
/// returns them.
|
||||
pub fn render_region_words(&mut self, doc: &Document, region: Rect, scale: f64, white: bool) -> Rendered<Vec<u32>> {
|
||||
self.region(doc, region, scale, ®ion_options(white))
|
||||
}
|
||||
|
||||
/// Render a document rect at `scale` pixels per point with `opts`.
|
||||
pub fn render_region_with(&mut self, doc: &Document, region: Rect, scale: f64, opts: &RenderOptions) -> Rendered {
|
||||
self.region(doc, region, scale, opts)
|
||||
}
|
||||
|
||||
fn region<P: FramePixels>(&mut self, doc: &Document, region: Rect, scale: f64, opts: &RenderOptions) -> Rendered<P> {
|
||||
let (w, h) = region_pixels(region, scale);
|
||||
let view = Affine::scale(scale) * Affine::translate((-region.x0, -region.y0));
|
||||
self.render(doc, w, h, view, opts)
|
||||
self.render_document(doc, w, h, view, opts, None)
|
||||
}
|
||||
|
||||
/// `region` of `doc` as ink amounts in the working CMYK space, 4 bytes a pixel (0 = no ink):
|
||||
@@ -433,7 +470,7 @@ impl Renderer {
|
||||
let view = Affine::scale(scale) * Affine::translate((-region.x0, -region.y0));
|
||||
let _lent = vectorcraft_text::FontDb::global().lend_composite_fonts(&doc.composite_fonts);
|
||||
let _frame = vectorcraft_text::KeptLayoutsFrame::begin();
|
||||
self.render_as(doc, w, h, view, opts, true, 1, None).pixels
|
||||
self.render_as::<Vec<u8>>(doc, w, h, view, opts, true, 1, None).pixels
|
||||
}
|
||||
|
||||
/// Render a single node (thumbnails, previews) fitted into `size`×`size` pixels.
|
||||
@@ -544,6 +581,11 @@ impl Renderer {
|
||||
}
|
||||
}
|
||||
|
||||
/// The options of [`Renderer::render_region`]: as exported, transparent or on white.
|
||||
fn region_options(white: bool) -> RenderOptions {
|
||||
RenderOptions { background: white.then_some([255, 255, 255, 255]), skip_templates: true, ..Default::default() }
|
||||
}
|
||||
|
||||
/// The rasterizer settings for `opts`: the quality render mode when [`RenderOptions::precise`] is set.
|
||||
fn raster_settings(opts: &RenderOptions) -> vello_cpu::RasterizerSettings {
|
||||
let render_mode = if opts.precise { vello_cpu::RenderMode::OptimizeQuality } else { vello_cpu::RenderMode::OptimizeSpeed };
|
||||
@@ -557,6 +599,58 @@ fn screen_under_art(f: &Frame, rgba: [u8; 4]) -> [u8; 4] {
|
||||
if matches!(f.ink.base(), Ink::Cmy | Ink::K) { rgba } else { proof::under_art(f.opts, rgba) }
|
||||
}
|
||||
|
||||
/// The buffer a frame's premultiplied RGBA pixels are returned in ([`Rendered::pixels`]).
|
||||
pub(crate) trait FramePixels: Sized {
|
||||
/// The pixels `ctx` holds, rendered by [`Renderer::finish`]'s rules.
|
||||
fn finish(r: &mut Renderer, ctx: &mut RenderContext) -> Self;
|
||||
/// The pixels in `bytes` (four a pixel).
|
||||
fn from_bytes(bytes: Vec<u8>) -> Self;
|
||||
/// The pixels as bytes, four a pixel.
|
||||
fn bytes_mut(&mut self) -> &mut [u8];
|
||||
}
|
||||
|
||||
impl FramePixels for Vec<u8> {
|
||||
fn finish(r: &mut Renderer, ctx: &mut RenderContext) -> Self {
|
||||
group::into_bytes(r.finish(ctx, r.raster))
|
||||
}
|
||||
|
||||
fn from_bytes(bytes: Vec<u8>) -> Self {
|
||||
bytes
|
||||
}
|
||||
|
||||
fn bytes_mut(&mut self) -> &mut [u8] {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// Each word holds a pixel's four bytes in memory in the order a byte buffer holds them.
|
||||
impl FramePixels for Vec<u32> {
|
||||
/// Over transparency, `ctx` renders straight into the words. Over a picture
|
||||
/// ([`Renderer::finish`]), the rendered pixmap is copied into them.
|
||||
fn finish(r: &mut Renderer, ctx: &mut RenderContext) -> Self {
|
||||
if r.picture.is_none() {
|
||||
ctx.flush();
|
||||
let (w, h) = (ctx.width(), ctx.height());
|
||||
let mut words = vec![0u32; usize::from(w) * usize::from(h)];
|
||||
if let Some(target) = vello_cpu::PixmapMut::new(w, h, bytemuck::cast_slice_mut(&mut words)) {
|
||||
ctx.render_with(target, &mut r.resources, r.raster);
|
||||
#[cfg(test)]
|
||||
group::FINISHED.with(|p| p.set(words.as_ptr() as usize));
|
||||
return words;
|
||||
}
|
||||
}
|
||||
Self::from_bytes(group::into_bytes(r.finish(ctx, r.raster)))
|
||||
}
|
||||
|
||||
fn from_bytes(bytes: Vec<u8>) -> Self {
|
||||
bytes.as_chunks::<4>().0.iter().map(|p| u32::from_ne_bytes(*p)).collect()
|
||||
}
|
||||
|
||||
fn bytes_mut(&mut self) -> &mut [u8] {
|
||||
bytemuck::cast_slice_mut(self)
|
||||
}
|
||||
}
|
||||
|
||||
/// Premultiplied RGBA `pixels` drawn over the solid color `background` (`[r, g, b, a]`, straight).
|
||||
pub(crate) fn over_background(pixels: &mut [u8], [r, g, b, a]: [u8; 4]) {
|
||||
let alpha = u32::from(a);
|
||||
|
||||
@@ -41,6 +41,7 @@ mod tileedge;
|
||||
mod typeedges;
|
||||
mod viewraster;
|
||||
mod widthzoom;
|
||||
mod words;
|
||||
|
||||
fn rect_node(d: &mut Document, r: Rect, fill: Paint, stroke: Paint, w: f64) -> Node {
|
||||
let id = d.alloc_id();
|
||||
|
||||
@@ -74,6 +74,41 @@ fn bitmap_glyphs_go_with_type_that_a_geometry_effect_reshapes() {
|
||||
assert_eq!(img.pixel(50, 80), [255, 255, 255, 255], "not where it was");
|
||||
}
|
||||
|
||||
/// Bitmap glyphs are sampled as images are (File Handling › Display Bitmaps as Anti-aliased Images,
|
||||
/// #10712), so a raster kept for type, such as a blur's, is made again when image smoothing changes.
|
||||
#[test]
|
||||
fn rasters_of_type_follow_image_smoothing() {
|
||||
let _adding = crate::tests_fontchange::adding_fonts();
|
||||
vectorcraft_text::FontDb::global().add_font(colour_bitmap_font(false).unwrap());
|
||||
let mut d = Document::new(160.0, 160.0);
|
||||
let st = CharStyle { font_family: colour_bitmap_family(false).into(), size: 100.0, ..Default::default() };
|
||||
let n = Node::new(d.alloc_id(), NodeKind::Text(Box::new(TextObject::point(Point::new(20.0, 120.0), &COLOUR_CHAR.to_string(), st))));
|
||||
let l = d.layers[0].id;
|
||||
d.insert(Some(l), 0, n.clone()).unwrap();
|
||||
let symbols = d.symbol_boxes().quick();
|
||||
let mut r = Renderer::new();
|
||||
let mut inputs = |smooth_images: bool| {
|
||||
let opts = RenderOptions { smooth_images, ..Default::default() };
|
||||
let f = Frame {
|
||||
mt: false,
|
||||
patch: None,
|
||||
doc: &d,
|
||||
symbols: &symbols,
|
||||
view: Affine::IDENTITY,
|
||||
visible: vectorcraft_geom::Rect::new(0.0, 0.0, 160.0, 160.0),
|
||||
px: 1.0,
|
||||
opts: &opts,
|
||||
ink: crate::ink::Ink::Display,
|
||||
output: Affine::IDENTITY,
|
||||
plates: None,
|
||||
};
|
||||
r.raster_inputs(&f, &n, crate::fx::Reads::of(&n))
|
||||
};
|
||||
let smoothed = inputs(true);
|
||||
assert!(inputs(true) == smoothed, "the same settings: the same inputs");
|
||||
assert!(inputs(false) != smoothed, "image smoothing changed: the raster is made again");
|
||||
}
|
||||
|
||||
/// A colour adjustment leaves the emoji of reshaped type in their colours, as it does those of
|
||||
/// type, and as exports and Expand Appearance draw them.
|
||||
#[test]
|
||||
|
||||
@@ -10,8 +10,9 @@ use crate::*;
|
||||
/// Every file reads as a 40×20 artboard filled blue; a file whose bytes start with `loop` also
|
||||
/// places itself (the same key) in its middle, one whose bytes start with `cut` also shows an
|
||||
/// image whose pixels can't be decoded over its left half, one whose bytes start with `pict` also
|
||||
/// shows a linked red image over its left half (its own Show Images in Outline Mode off), and one
|
||||
/// whose bytes start with `bad` can't be read.
|
||||
/// shows a linked red image over its left half (its own Show Images in Outline Mode off), one
|
||||
/// whose bytes start with `checker` also shows a 2×2 black and white checker image over all of it,
|
||||
/// and one whose bytes start with `bad` can't be read.
|
||||
fn blue_page(p: &PlacedDocument, bytes: &[u8]) -> Option<(Document, Node, Rect)> {
|
||||
if bytes.starts_with(b"bad") {
|
||||
return None;
|
||||
@@ -49,6 +50,23 @@ fn blue_page(p: &PlacedDocument, bytes: &[u8]) -> Option<(Document, Node, Rect)>
|
||||
};
|
||||
children.push(Arc::new(Node::new(NodeId(4), NodeKind::Image(Box::new(im)))));
|
||||
}
|
||||
if bytes.starts_with(b"checker") {
|
||||
let raw: Vec<u8> = (0..4).flat_map(|i| if i == 0 || i == 3 { [0, 0, 0, 255] } else { [255, 255, 255, 255] }).collect();
|
||||
let checker =
|
||||
craft_image_codecs::Image::from_raw(2, 2, craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, raw).ok()?;
|
||||
let png = craft_image_codecs::encode(&checker, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok()?;
|
||||
d.images.insert("checker-image".into(), ImageBlob::new("image/png", png.to_vec()));
|
||||
let im = vectorcraft_doc::ImageObject {
|
||||
key: "checker-image".into(),
|
||||
width: 2,
|
||||
height: 2,
|
||||
xf: Affine::scale_non_uniform(20.0, 10.0),
|
||||
link: None,
|
||||
placement: Default::default(),
|
||||
pixels: None,
|
||||
};
|
||||
children.push(Arc::new(Node::new(NodeId(5), NodeKind::Image(Box::new(im)))));
|
||||
}
|
||||
if bytes.starts_with(b"loop") {
|
||||
d.images.insert(p.key.clone(), ImageBlob::new("application/json", bytes.to_vec()));
|
||||
let me = PlacedDocument { xf: Affine::translate((10.0, 5.0)) * Affine::scale(0.5), ..p.clone() };
|
||||
@@ -676,6 +694,28 @@ fn bitmaps_with_and_without_undecoded_marks_are_asked_for_apart() {
|
||||
assert_eq!(placed_document::scheduled("marks-1"), 2, "one for each");
|
||||
}
|
||||
|
||||
/// A placed file's bitmap draws its images as the frame does (File Handling › Display Bitmaps as
|
||||
/// Anti-aliased Images, #10712): smoothed, a scaled-up 2×2 checker shows greys between its
|
||||
/// squares; not smoothed, every pixel is one of its own colors. Frames with and without smoothing
|
||||
/// ask for bitmaps of their own.
|
||||
#[test]
|
||||
fn a_bitmap_smooths_its_images_when_the_frame_does() {
|
||||
let _serial = serial();
|
||||
let d = doc_with("checker-1", b"checker");
|
||||
let greys = |smooth_images: bool| {
|
||||
let opts = RenderOptions { background: Some([255, 255, 255, 255]), progressive_placed: true, smooth_images, ..Default::default() };
|
||||
Renderer::new().render(&d, 100, 100, Affine::IDENTITY, &opts);
|
||||
settle();
|
||||
let r = Renderer::new().render(&d, 100, 100, Affine::IDENTITY, &opts);
|
||||
// The placed box spans x 10 to 90; the checker's squares meet at x = 50.
|
||||
(12..88).filter(|x| (16..240).contains(&r.pixel(*x, 20)[0])).count()
|
||||
};
|
||||
assert_eq!(greys(false), 0, "not smoothed: black, then white");
|
||||
assert!(greys(true) >= 4, "smoothed: a ramp from black to white");
|
||||
assert_eq!(greys(false), 0, "not smoothed again: the smoothed bitmap is not shown");
|
||||
assert_eq!(placed_document::scheduled("checker-1"), 2, "one for each");
|
||||
}
|
||||
|
||||
/// Once bitmaps are ready, drawing again where [`placed_area`] says gives what drawing the whole
|
||||
/// frame again gives. The area of a file covers every object showing it (a group's member and
|
||||
/// an object with a drop shadow too) and no object showing another file; art of a brush or a
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
//! A frame rendered in words ([`Renderer::render_words`]): the bytes [`Renderer::render`] returns,
|
||||
//! rendered straight into the words.
|
||||
|
||||
use std::cell::Cell;
|
||||
|
||||
use vectorcraft_color::{BlendMode as Blend, Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, ColorMode, Node};
|
||||
use vectorcraft_geom::shapes;
|
||||
|
||||
use crate::group::FINISHED;
|
||||
use crate::*;
|
||||
|
||||
fn rect(d: &mut Document, r: Rect, c: Color) -> Node {
|
||||
Node::path(d.alloc_id(), shapes::rectangle(r), Appearance::basic(Paint::solid(c), Paint::None, 0.0))
|
||||
}
|
||||
|
||||
/// A 100 × 100 pt page in `mode` with a page-sized rectangle under the nodes `top` makes.
|
||||
fn page(mode: ColorMode, top: impl FnOnce(&mut Document) -> Vec<Node>) -> Document {
|
||||
let mut d = Document::new_with_mode(100.0, 100.0, mode);
|
||||
let below = rect(&mut d, Rect::new(0.0, 0.0, 100.0, 100.0), Color::rgb(0.8, 0.6, 0.2));
|
||||
let top = top(&mut d);
|
||||
let l = d.layers[0].id;
|
||||
d.insert(Some(l), usize::MAX, below).unwrap();
|
||||
for n in top {
|
||||
d.insert(Some(l), usize::MAX, n).unwrap();
|
||||
}
|
||||
d
|
||||
}
|
||||
|
||||
fn square(d: &mut Document) -> Node {
|
||||
rect(d, Rect::new(10.0, 20.0, 60.0, 45.0), Color::rgb(0.1, 0.4, 0.9))
|
||||
}
|
||||
|
||||
/// A half-opaque group that blends with the page under it: drawn offscreen over a copy of it.
|
||||
fn blending_group(d: &mut Document) -> Node {
|
||||
let mut child = rect(d, Rect::new(20.0, 20.0, 80.0, 80.0), Color::rgb(0.5, 0.5, 1.0));
|
||||
child.blend = Blend::Multiply;
|
||||
let mut g = Node::group(d.alloc_id(), vec![Arc::new(child)]);
|
||||
g.opacity = 0.5;
|
||||
g
|
||||
}
|
||||
|
||||
fn finished() -> usize {
|
||||
FINISHED.with(Cell::get)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_frame_in_words_holds_the_bytes_of_the_same_frame_in_bytes() {
|
||||
let rgb = |top: fn(&mut Document) -> Node| page(ColorMode::Rgb, |d| vec![top(d)]);
|
||||
let cases = [
|
||||
("a square", rgb(square), RenderOptions::default()),
|
||||
("over no background", rgb(square), RenderOptions { background: None, artboards: false, ..Default::default() }),
|
||||
("a blending group", rgb(blending_group), RenderOptions::default()),
|
||||
("CMYK blending", page(ColorMode::Cmyk, |d| vec![blending_group(d)]), RenderOptions::default()),
|
||||
("supersampled", rgb(square), RenderOptions { supersample: true, ..Default::default() }),
|
||||
("outline", rgb(square), RenderOptions { outline: true, ..Default::default() }),
|
||||
];
|
||||
for (what, d, opts) in cases {
|
||||
for (w, h, view) in [(100, 100, Affine::IDENTITY), (37, 61, Affine::scale(1.7) * Affine::translate((-5.0, -3.0)))] {
|
||||
let bytes = Renderer::new().render(&d, w, h, view, &opts);
|
||||
let words = Renderer::new().render_words(&d, w, h, view, &opts);
|
||||
assert_eq!((words.width, words.height), (bytes.width, bytes.height), "{what}: the frame's size");
|
||||
assert_eq!(words.pixels.len() * 4, bytes.pixels.len(), "{what}: a word a pixel");
|
||||
assert!(bytemuck::cast_slice::<u32, u8>(&words.pixels) == bytes.pixels.as_slice(), "{what} ({w} × {h}): the same bytes");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_frame_in_words_is_returned_in_the_buffer_it_rendered_into() {
|
||||
let d = page(ColorMode::Rgb, |d| vec![square(d)]);
|
||||
let mut r = Renderer::new();
|
||||
for background in [None, Some([255, 255, 255, 255])] {
|
||||
let opts = RenderOptions { background, ..Default::default() };
|
||||
let out = r.render_words(&d, 64, 48, Affine::IDENTITY, &opts);
|
||||
assert_eq!(out.pixels.len(), 64 * 48);
|
||||
assert_eq!(out.pixels.as_ptr() as usize, finished(), "background {background:?}: the words it rendered into are returned");
|
||||
}
|
||||
let patch = r.render_plain_patch_words(&d, 64, 48, Affine::IDENTITY, &RenderOptions::default()).expect("a plain page renders as a patch");
|
||||
assert_eq!(patch.pixels.as_ptr() as usize, finished(), "a patch's words are returned without a copy");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_region_in_words_holds_the_bytes_of_the_region_in_bytes() {
|
||||
let d = page(ColorMode::Rgb, |d| vec![square(d), blending_group(d)]);
|
||||
let region = Rect::new(5.0, 15.0, 70.0, 90.0);
|
||||
for white in [false, true] {
|
||||
let bytes = Renderer::new().render_region(&d, region, 1.3, white);
|
||||
let mut r = Renderer::new();
|
||||
let words = r.render_region_words(&d, region, 1.3, white);
|
||||
assert_eq!((words.width, words.height), (bytes.width, bytes.height), "white {white}: the region's size");
|
||||
assert!(bytemuck::cast_slice::<u32, u8>(&words.pixels) == bytes.pixels.as_slice(), "white {white}: the same bytes");
|
||||
}
|
||||
let plain = page(ColorMode::Rgb, |d| vec![square(d)]);
|
||||
let words = Renderer::new().render_region_words(&plain, region, 1.3, false);
|
||||
assert_eq!(words.pixels.as_ptr() as usize, finished(), "a region's words are returned without a copy");
|
||||
}
|
||||
@@ -1,7 +1,8 @@
|
||||
//! Arrange Tools in the interface: its submenu (Object › Plug-ins › Arrange Tools); the dialogs of
|
||||
//! Arrange in Grid, Offset Objects, Replace with Top Object, Set Size of Each, Match Objects, Group by Row, Randomize
|
||||
//! Opacity, Sort Objects and Mark Bounds of Each, which preview on the canvas and run their `addon.arrange.*` command
|
||||
//! on OK; Group Overlapping Objects; and Zoom to Selection ([`ZOOM`]), which fits the active view to the selection.
|
||||
//! Opacity, Sort Objects, Add Artboard Guides and Mark Bounds of Each, which preview on the canvas and run their
|
||||
//! `addon.arrange.*` command on OK; Group Overlapping Objects; and Zoom to Selection ([`ZOOM`]), which fits the active
|
||||
//! view to the selection.
|
||||
|
||||
use std::borrow::Cow;
|
||||
|
||||
@@ -29,9 +30,10 @@ const MATCH: &str = "addon.arrange.match";
|
||||
const ROWS: &str = "addon.arrange.groupRows";
|
||||
const OPACITY: &str = "addon.arrange.randomizeOpacity";
|
||||
const SORT: &str = "addon.arrange.sort";
|
||||
const GUIDES: &str = "addon.arrange.artboardGuides";
|
||||
const MARKS: &str = "addon.arrange.markBounds";
|
||||
/// Each dialog's command and heading.
|
||||
const DIALOGS: [(&str, &str); 9] = [
|
||||
const DIALOGS: [(&str, &str); 10] = [
|
||||
(GRID, "Arrange in Grid"),
|
||||
(OFFSET, "Offset Objects"),
|
||||
(REPLACE, "Replace with Top Object"),
|
||||
@@ -40,8 +42,11 @@ const DIALOGS: [(&str, &str); 9] = [
|
||||
(ROWS, "Group by Row"),
|
||||
(OPACITY, "Randomize Opacity"),
|
||||
(SORT, "Sort Objects"),
|
||||
(GUIDES, "Add Artboard Guides"),
|
||||
(MARKS, "Mark Bounds of Each"),
|
||||
];
|
||||
/// The artboards Add Artboard Guides puts guides around: `all` false or true.
|
||||
const SCOPES: [(&str, &str); 2] = [("active", "Active Artboard"), ("all", "All Artboards")];
|
||||
/// The mark lengths (pt) Mark Bounds of Each takes, and its stroke weights.
|
||||
const MARK_LENGTHS: std::ops::RangeInclusive<f64> = 0.001..=1e6;
|
||||
const WEIGHTS: std::ops::RangeInclusive<f64> = 0.01..=1000.0;
|
||||
@@ -77,6 +82,7 @@ pub fn menu() -> Vec<Node> {
|
||||
c("Group by Row…", ROWS),
|
||||
c("Randomize Opacity…", OPACITY),
|
||||
c("Sort Objects…", SORT),
|
||||
c("Add Artboard Guides…", GUIDES),
|
||||
c("Mark Bounds of Each…", MARKS),
|
||||
Sep,
|
||||
cp("Zoom to Selection", ZOOM, json!({})),
|
||||
@@ -91,6 +97,7 @@ static MATCH_SPEC: Spec = Spec { command: MATCH, params: match_params, found: No
|
||||
static ROWS_SPEC: Spec = Spec { command: ROWS, params: group_rows_params, found: None };
|
||||
static OPACITY_SPEC: Spec = Spec { command: OPACITY, params: opacity_params, found: None };
|
||||
static SORT_SPEC: Spec = Spec { command: SORT, params: sort_params, found: None };
|
||||
static GUIDES_SPEC: Spec = Spec { command: GUIDES, params: guides_params, found: None };
|
||||
static MARKS_SPEC: Spec = Spec { command: MARKS, params: marks_params, found: None };
|
||||
|
||||
/// The dialog over `rows`, titled by the heading of `command`.
|
||||
@@ -201,6 +208,11 @@ fn sort_rows() -> Vec<Param> {
|
||||
]
|
||||
}
|
||||
|
||||
fn guides_rows(lengths: LengthUnits) -> Vec<Param> {
|
||||
// More than 0 outside the artboard, less than 0 inside it.
|
||||
vec![length("offset", "Offset:", 0.0, GAPS, lengths), choice("scope", "Artboards:", &SCOPES, "active")]
|
||||
}
|
||||
|
||||
fn marks_rows(lengths: LengthUnits) -> Vec<Param> {
|
||||
let styles = [("corners", "Corner Marks"), ("rectangle", "Rectangle")];
|
||||
let bounds = [("geometric", "Geometric Bounds"), ("visual", "Visual Bounds")];
|
||||
@@ -258,10 +270,39 @@ fn sort_params(fields: &DialogFields) -> Value {
|
||||
Value::Object(form::json_of(&sort_rows(), fields))
|
||||
}
|
||||
|
||||
/// Add Artboard Guides' offset, and `all` for All Artboards, else the artboard active when the dialog opened.
|
||||
fn guides_params(fields: &DialogFields) -> Value {
|
||||
let mut params = form::json_of(&guides_rows(POINTS), fields);
|
||||
let all = fields.text("scope") == Some("all");
|
||||
params.remove("scope");
|
||||
if all {
|
||||
params.remove("artboardId");
|
||||
}
|
||||
params.insert("all".into(), json!(all));
|
||||
Value::Object(params)
|
||||
}
|
||||
|
||||
pub(super) fn resolve_guides_artboard(app: &VectorcraftApp, params: &mut Value) -> Result<(), String> {
|
||||
if params["all"] == true {
|
||||
return Ok(());
|
||||
}
|
||||
let id = params["artboardId"].as_u64();
|
||||
let index = app.session.active().and_then(|st| st.doc.artboards.iter().position(|a| Some(u64::from(a.id)) == id));
|
||||
let Some(index) = index else { return Err("The artboard no longer exists.".into()) };
|
||||
if let Some(params) = params.as_object_mut() {
|
||||
params.remove("artboardId");
|
||||
params.insert("artboard".into(), json!(index));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Opens the dialog of command `id` on the active document; `None` for another command and without a document.
|
||||
pub(crate) fn open(app: &mut VectorcraftApp, id: &str) -> Option<Result<Value, String>> {
|
||||
let &(command, _) = DIALOGS.iter().find(|(command, _)| *command == id)?;
|
||||
let st = app.session.active()?;
|
||||
if command == GUIDES && st.doc.artboards.is_empty() {
|
||||
return Some(Err("the document has no artboards".into()));
|
||||
}
|
||||
let strokes = app.session.prefs.scale_strokes;
|
||||
let key = st.selection.key.is_some();
|
||||
let lengths = general_lengths(app);
|
||||
@@ -295,6 +336,13 @@ pub(crate) fn open(app: &mut VectorcraftApp, id: &str) -> Option<Result<Value, S
|
||||
"by": "area", "apply": "stacking", "order": "ascending", "distribute": false, "seed": st.revision % SEEDS, "scaleStrokes": strokes,
|
||||
}),
|
||||
),
|
||||
GUIDES => (
|
||||
guides_rows(lengths),
|
||||
json!({
|
||||
"offset": 0, "scope": "active",
|
||||
"artboardId": st.doc.artboards.get(crate::panels::artboards::selected(app, st.doc.artboards.len())).map(|a| a.id),
|
||||
}),
|
||||
),
|
||||
MARKS => (marks_rows(lengths), json!({ "style": "corners", "bounds": "geometric", "length": 10, "weight": 1, "color": "#ff0000" })),
|
||||
// The first selected object's size, as the command measures it (a side it lacks: the least).
|
||||
_ => {
|
||||
@@ -328,6 +376,7 @@ pub(crate) fn open(app: &mut VectorcraftApp, id: &str) -> Option<Result<Value, S
|
||||
dialog(OPACITY, opacity_rows()).ok_enabled(min <= max).values(Bind::bound(fields))
|
||||
}),
|
||||
SORT => super::dialogs::open(app, &SORT_SPEC, fields, |fields| dialog(SORT, sort_rows()).values(Bind::bound(fields))),
|
||||
GUIDES => super::dialogs::open(app, &GUIDES_SPEC, fields, move |fields| dialog(GUIDES, guides_rows(lengths)).values(Bind::bound(fields))),
|
||||
MARKS => super::dialogs::open(app, &MARKS_SPEC, fields, move |fields| dialog(MARKS, marks_rows(lengths)).values(Bind::bound(fields))),
|
||||
_ => super::dialogs::open(app, &SIZE_SPEC, fields, move |fields| {
|
||||
let either = fields.bool("widthOn").unwrap_or(true) || fields.bool("heightOn").unwrap_or(true);
|
||||
|
||||
@@ -164,6 +164,182 @@ fn real_opacity_edits_drive_validation_confirmation_and_cancel() {
|
||||
assert!((opacity(&panel, a) - 0.8).abs() < 1e-6 && (opacity(&panel, b) - 0.8).abs() < 1e-6);
|
||||
}
|
||||
|
||||
/// The bounds of the guide paths on the top-level layer Artboard Guides, from the back.
|
||||
fn artboard_guides(app: &VectorcraftApp) -> Vec<vectorcraft_geom::Rect> {
|
||||
let d = &app.session.doc().unwrap().doc;
|
||||
let layer = d.layers.iter().find(|l| l.name.as_deref() == Some("Artboard Guides"));
|
||||
let guides = layer.and_then(|l| l.children()).into_iter().flatten();
|
||||
guides.filter(|n| matches!(n.kind, vectorcraft_doc::NodeKind::Path { guide: true, .. })).map(|n| n.geometric_bounds().unwrap()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn real_artboard_guide_edits_reach_the_preview_and_ok_adds_one_undo_step() {
|
||||
for cancel in [true, false] {
|
||||
let (app, _, _) = app();
|
||||
let board = app.session.doc().unwrap().doc.artboards[0].rect;
|
||||
let (original, undo) = (app.session.doc().unwrap().doc.clone(), app.session.doc().unwrap().history.undo.len());
|
||||
let mut panel = Harness::new(app, crate::tests::picks::dialogs);
|
||||
click(&mut panel.app(), "Add Artboard Guides…");
|
||||
panel.frame();
|
||||
type_number(&mut panel, "Offset", "-12");
|
||||
let id = host::dialog_id(&panel.app());
|
||||
assert_eq!(host::read(&panel.app(), id, |f| f.number("offset")), Some(-12.0));
|
||||
assert_eq!(artboard_guides(&panel.app()), vec![board.inflate(-12.0, -12.0)], "the preview insets the active artboard");
|
||||
panel.click_role("Preview", craft::ui::contract::Role::CHECK_BOX);
|
||||
panel.frame();
|
||||
assert!(artboard_guides(&panel.app()).is_empty(), "no guide with Preview off");
|
||||
panel.click_role("Preview", craft::ui::contract::Role::CHECK_BOX);
|
||||
panel.frame();
|
||||
assert_eq!(artboard_guides(&panel.app()), vec![board.inflate(-12.0, -12.0)]);
|
||||
assert_eq!(panel.app().session.doc().unwrap().history.undo.len(), undo, "a preview makes no step");
|
||||
panel.click(if cancel { "Cancel" } else { "OK" });
|
||||
panel.frame();
|
||||
let app = panel.app();
|
||||
assert!(!app.any_dialog_open());
|
||||
let state = app.session.doc().unwrap();
|
||||
if cancel {
|
||||
assert!(*state.doc == *original, "Cancel leaves the document as it was");
|
||||
assert_eq!(state.history.undo.len(), undo);
|
||||
} else {
|
||||
assert_eq!(artboard_guides(&app), vec![board.inflate(-12.0, -12.0)]);
|
||||
assert_eq!(state.history.undo.len(), undo + 1, "OK adds the guide as one undo step");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn add_artboard_guides_puts_one_around_every_artboard_and_refuses_too_large_an_inset() {
|
||||
let (mut app, _, _) = app();
|
||||
app.run("artboard.new", json!({"x": 600, "y": 0, "width": 200, "height": 100})).unwrap();
|
||||
let boards: Vec<_> = app.session.doc().unwrap().doc.artboards.iter().map(|a| a.rect).collect();
|
||||
click(&mut app, "Add Artboard Guides…");
|
||||
let id = host::dialog_id(&app);
|
||||
assert_eq!(host::read(&app, id, |f| (f.number("offset"), f.text("scope").map(str::to_owned))), (Some(0.0), Some("active".to_owned())));
|
||||
host::set(&app, id, "offset", json!(18));
|
||||
host::set(&app, id, "scope", json!("all"));
|
||||
assert!(host::confirm(&app, id));
|
||||
host::frame(&mut app);
|
||||
assert_eq!(artboard_guides(&app), boards.iter().map(|b| b.inflate(18.0, 18.0)).collect::<Vec<_>>());
|
||||
// The second artboard is 100 pt tall: an inset of 50 leaves it nothing, so OK adds nothing.
|
||||
let (before, undo) = (app.session.doc().unwrap().doc.clone(), app.session.doc().unwrap().history.undo.len());
|
||||
click(&mut app, "Add Artboard Guides…");
|
||||
let id = host::dialog_id(&app);
|
||||
host::set(&app, id, "offset", json!(-50));
|
||||
host::set(&app, id, "scope", json!("all"));
|
||||
assert!(host::confirm(&app, id));
|
||||
host::frame(&mut app);
|
||||
assert!(*app.session.doc().unwrap().doc == *before);
|
||||
assert_eq!(app.session.doc().unwrap().history.undo.len(), undo);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn add_artboard_guides_does_not_open_without_artboards() {
|
||||
let (mut app, _, _) = app();
|
||||
std::sync::Arc::make_mut(&mut app.session.active_mut().unwrap().doc).artboards.clear();
|
||||
let opened = crate::addons::dialogs::open_from_menu(&mut app, "addon.arrange.artboardGuides");
|
||||
assert!(matches!(opened, Some(Err(_))), "{opened:?}");
|
||||
assert!(!app.any_dialog_open());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn add_artboard_guides_keeps_the_opening_artboard_after_reordering() {
|
||||
for preview in [false, true] {
|
||||
let (mut app, _, _) = app();
|
||||
app.run("artboard.new", json!({"x": 600, "y": 0, "width": 200, "height": 100})).unwrap();
|
||||
app.view_mut().unwrap().artboard = 0;
|
||||
let board = app.session.doc().unwrap().doc.artboards[0].rect;
|
||||
click(&mut app, "Add Artboard Guides…");
|
||||
let id = host::dialog_id(&app);
|
||||
host::set(&app, id, "preview", json!(preview));
|
||||
if preview {
|
||||
host::frame(&mut app);
|
||||
app.session.cancel_interaction().unwrap();
|
||||
}
|
||||
app.run("artboard.reorder", json!({"index": 0, "to": 1})).unwrap();
|
||||
let n = steps(&app);
|
||||
if preview {
|
||||
host::frame(&mut app);
|
||||
assert_eq!(artboard_guides(&app), vec![board]);
|
||||
assert_eq!(steps(&app), n);
|
||||
}
|
||||
assert!(host::confirm(&app, id));
|
||||
host::frame(&mut app);
|
||||
assert_eq!(artboard_guides(&app), vec![board]);
|
||||
assert_eq!(steps(&app), n + 1);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn add_artboard_guides_does_not_replace_a_deleted_artboard_with_its_neighbor() {
|
||||
for preview in [false, true] {
|
||||
let (mut app, _, _) = app();
|
||||
app.run("artboard.new", json!({"x": 600, "y": 0, "width": 200, "height": 100})).unwrap();
|
||||
app.view_mut().unwrap().artboard = 0;
|
||||
click(&mut app, "Add Artboard Guides…");
|
||||
let id = host::dialog_id(&app);
|
||||
host::set(&app, id, "preview", json!(preview));
|
||||
if preview {
|
||||
host::frame(&mut app);
|
||||
app.session.cancel_interaction().unwrap();
|
||||
}
|
||||
app.run("artboard.delete", json!({"index": 0})).unwrap();
|
||||
let (before, n) = (app.session.doc().unwrap().doc.clone(), steps(&app));
|
||||
if preview {
|
||||
host::frame(&mut app);
|
||||
assert!(artboard_guides(&app).is_empty());
|
||||
assert_eq!(steps(&app), n);
|
||||
}
|
||||
assert!(host::confirm(&app, id));
|
||||
host::frame(&mut app);
|
||||
assert!(artboard_guides(&app).is_empty());
|
||||
assert_eq!(app.session.doc().unwrap().doc, before);
|
||||
assert_eq!(steps(&app), n);
|
||||
assert_eq!(app.ui.status, "The artboard no longer exists.");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn artboard_guides_menu_dialog_is_available_without_a_selection() {
|
||||
let (mut app, _, _) = app();
|
||||
app.run("select.none", json!({})).unwrap();
|
||||
assert!(menus::enabled(&app, "ui.menuDialog"));
|
||||
let guides = json!({"command": "addon.arrange.artboardGuides"});
|
||||
assert_eq!(menus::shown_state(&app, "ui.menuDialog", &guides).map(|s| s.0), Some(true));
|
||||
let transform = json!({"command": "object.move"});
|
||||
assert_eq!(menus::shown_state(&app, "ui.menuDialog", &transform).map(|s| s.0), Some(false));
|
||||
let grid = json!({"command": "addon.arrange.grid"});
|
||||
assert_eq!(menus::shown_state(&app, "ui.menuDialog", &grid).map(|s| s.0), Some(false));
|
||||
app.run("select.all", json!({})).unwrap();
|
||||
assert_eq!(menus::shown_state(&app, "ui.menuDialog", &transform).map(|s| s.0), Some(true));
|
||||
assert_eq!(menus::shown_state(&app, "ui.menuDialog", &grid).map(|s| s.0), Some(true));
|
||||
app.run("select.none", json!({})).unwrap();
|
||||
app.run("ui.menuDialog", guides).unwrap();
|
||||
let id = host::dialog_id(&app);
|
||||
assert!(host::confirm(&app, id));
|
||||
host::frame(&mut app);
|
||||
assert_eq!(artboard_guides(&app), vec![app.session.doc().unwrap().doc.artboards[0].rect]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn add_artboard_guides_uses_the_artboard_the_view_shows() {
|
||||
let (mut app, _, _) = app();
|
||||
app.run("artboard.new", json!({"x": 600, "y": 0, "width": 200, "height": 100})).unwrap();
|
||||
let second = app.session.doc().unwrap().doc.artboards[1].rect;
|
||||
// The view moves to the second artboard without a command that tells the document, which
|
||||
// still names the first.
|
||||
app.view_mut().unwrap().artboard = 1;
|
||||
let first = app.session.doc().unwrap().doc.artboards[0].id;
|
||||
app.session.active_mut().unwrap().active_artboard = Some(first);
|
||||
click(&mut app, "Add Artboard Guides…");
|
||||
let id = host::dialog_id(&app);
|
||||
host::set(&app, id, "offset", json!(6));
|
||||
host::frame(&mut app);
|
||||
assert_eq!(artboard_guides(&app), vec![second.inflate(6.0, 6.0)], "the preview");
|
||||
assert!(host::confirm(&app, id));
|
||||
host::frame(&mut app);
|
||||
assert_eq!(artboard_guides(&app), vec![second.inflate(6.0, 6.0)], "OK");
|
||||
}
|
||||
|
||||
/// The objects of the first layer, from the back.
|
||||
fn stacking(panel: &Harness) -> Vec<NodeId> {
|
||||
panel.app().session.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|n| n.id).collect()
|
||||
|
||||
@@ -29,6 +29,16 @@ pub(crate) struct Spec {
|
||||
pub found: Option<Found>,
|
||||
}
|
||||
|
||||
impl Spec {
|
||||
fn params(&self, app: &VectorcraftApp, fields: &DialogFields) -> Result<Value, String> {
|
||||
let mut params = (self.params)(fields);
|
||||
if self.command == "addon.arrange.artboardGuides" {
|
||||
super::arrange::resolve_guides_artboard(app, &mut params)?;
|
||||
}
|
||||
Ok(params)
|
||||
}
|
||||
}
|
||||
|
||||
/// The add-on dialog open now and the live preview it drives; one at a time, since a preview owns the document.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct AddonDialogs {
|
||||
@@ -141,11 +151,19 @@ fn pump_commit(app: &mut VectorcraftApp) {
|
||||
app.addon_dialogs.preview = LivePreview::default();
|
||||
app.addon_dialogs.preview_error = None;
|
||||
}
|
||||
let live = host.with(|h| h.get_mut_by_id::<HostedParamDialog>(id).map(|d| (d.is_previewing(), (spec.params)(d.fields()))));
|
||||
let live = host.with(|h| h.get_mut_by_id::<HostedParamDialog>(id).map(|d| (d.is_previewing(), spec.params(app, d.fields()))));
|
||||
if on_document && let Some((previewing, params)) = &live {
|
||||
let mut preview = mem::take(&mut app.addon_dialogs.preview);
|
||||
let label = vectorcraft_engine::find_command(spec.command).map_or(spec.command, |command| command.label);
|
||||
let answer = preview.run(app, *previewing, label, spec.command, params);
|
||||
let answer = match params {
|
||||
Ok(params) => preview.run(app, *previewing, label, spec.command, params),
|
||||
Err(error) => {
|
||||
preview.cancel(app);
|
||||
preview = LivePreview::default();
|
||||
app.status(error.clone());
|
||||
Some(Err(error.clone()))
|
||||
}
|
||||
};
|
||||
app.addon_dialogs.preview = preview;
|
||||
if spec.command == super::select::points_only::COMMAND {
|
||||
match &answer {
|
||||
@@ -172,11 +190,13 @@ fn pump_commit(app: &mut VectorcraftApp) {
|
||||
} else if !on_document {
|
||||
app.status("The add-on settings apply only to the drawing where the dialog opened.");
|
||||
} else {
|
||||
let params = (spec.params)(&result.fields);
|
||||
let answer = if spec.command == super::select::points_only::COMMAND {
|
||||
preview.commit_selection(app, spec.command, params)
|
||||
} else {
|
||||
preview.commit(app, spec.command, params)
|
||||
let answer = match spec.params(app, &result.fields) {
|
||||
Ok(params) if spec.command == super::select::points_only::COMMAND => preview.commit_selection(app, spec.command, params),
|
||||
Ok(params) => preview.commit(app, spec.command, params),
|
||||
Err(error) => {
|
||||
preview.cancel(app);
|
||||
Err(error)
|
||||
}
|
||||
};
|
||||
if let Err(error) = answer {
|
||||
app.status(error);
|
||||
|
||||
@@ -180,6 +180,8 @@ impl VectorcraftApp {
|
||||
multi_color: None,
|
||||
global_edit_count: None,
|
||||
shape_angle: None,
|
||||
radius_corners: None,
|
||||
selected_rectangles: None,
|
||||
trace_presets: None,
|
||||
trace_target: None,
|
||||
attributes_info: None,
|
||||
|
||||
@@ -124,10 +124,11 @@ impl VectorcraftApp {
|
||||
}
|
||||
}
|
||||
|
||||
/// Paste in place, in front and in back (#693), Select › All on Active Artboard (#1006), and Align,
|
||||
/// Distribute Objects and Distribute Spacing with Align to Artboard, and Edit Symbol from the Symbols
|
||||
/// panel act on the active artboard, the view's, which the app adds to command `id`'s `params` as
|
||||
/// `artboard`. A batch passes it on to those steps. While the Artboard tool has several artboards
|
||||
/// Add Artboard Guides (Object › Plug-ins › Arrange Tools), Paste in place, in front and in
|
||||
/// back (#693), Select › All on Active Artboard (#1006), and Align, Distribute Objects and
|
||||
/// Distribute Spacing with Align to Artboard, and Edit Symbol from the Symbols panel act on the
|
||||
/// active artboard, the view's, which the app adds to command `id`'s `params` as `artboard`. A
|
||||
/// batch passes it on to those steps. While the Artboard tool has several artboards
|
||||
/// selected, the paste commands get those as `artboards` instead, and paste a copy on each; in a
|
||||
/// document without artboards they get neither.
|
||||
fn add_active_artboard(&self, id: &str, params: &mut Value) {
|
||||
|
||||
@@ -160,6 +160,12 @@ pub struct CanvasCache {
|
||||
pub(crate) global_edit_count: Option<(crate::panels::properties::GlobalEditKey, usize)>,
|
||||
/// The selected live shape's angle, for (document uid, revision, kind of shape).
|
||||
pub shape_angle: Option<ShapeAngleCache>,
|
||||
/// The corners a live shape's Corner Radius field sets, as one hash, for (document uid,
|
||||
/// File › Revert count, revision).
|
||||
pub(crate) radius_corners: Option<((u64, u64, u64), u64)>,
|
||||
/// The selected live rectangles the per-corner fields set, as one hash, for (document uid,
|
||||
/// File › Revert count, revision).
|
||||
pub(crate) selected_rectangles: Option<((u64, u64, u64), u64)>,
|
||||
/// The Image Trace presets, for the session's preset revision.
|
||||
pub(crate) trace_presets: Option<(u64, Arc<crate::panels::image_trace::PresetList>)>,
|
||||
/// What the Image Trace panel traces, for (document uid, revision).
|
||||
|
||||
@@ -19,7 +19,7 @@ use serde_json::json;
|
||||
use vectorcraft_geom::{Affine, Point};
|
||||
|
||||
use super::BodyKind;
|
||||
use super::raster::{backdrop, cache_key, frame_options, frame_ppp, frame_view, pixel_region, placed_key, plugin_key, snapped_rect};
|
||||
use super::raster::{backdrop, cache_key, frame_options, frame_ppp, frame_view, pixel_region, placed_key, plugin_key, smooth_images, snapped_rect};
|
||||
use crate::doc_windows::Win;
|
||||
use crate::state::View;
|
||||
use crate::{CacheKey, VectorcraftApp};
|
||||
@@ -128,10 +128,10 @@ fn render_pane(
|
||||
display: Option<&craft::color_ui::display::DisplayTransform>,
|
||||
cms: Arc<vectorcraft_color::cms::Cms>,
|
||||
over: Option<(&crate::display_profile::Backdrop, f64)>,
|
||||
) -> vectorcraft_render::Rendered {
|
||||
let mut img = vectorcraft_color::cms::with_active(cms, || r.render(doc, w, h, view, opts));
|
||||
) -> vectorcraft_render::Rendered<Vec<u32>> {
|
||||
let mut img = vectorcraft_color::cms::with_active(cms, || r.render_words(doc, w, h, view, opts));
|
||||
let width = img.width;
|
||||
crate::display_profile::convert_over(display, &mut img.pixels, width, view, over);
|
||||
crate::display_profile::convert_over(display, bytemuck::cast_slice_mut(&mut img.pixels), width, view, over);
|
||||
img
|
||||
}
|
||||
|
||||
@@ -152,7 +152,7 @@ impl PaneSource {
|
||||
let ppp = frame_ppp(space.size(), ppp, max_side);
|
||||
let side = |l: f32| ((l * ppp).round().max(1.0) as u32).min(u32::from(u16::MAX));
|
||||
let (pw, ph) = (side(space.width()), side(space.height()));
|
||||
let smooth_images = pixel.is_none() || app.session.prefs.anti_aliased_bitmaps;
|
||||
let smooth_images = smooth_images(&app.session.prefs, pixel.is_some());
|
||||
let plugins = plugin_key(&mut app.canvas.plugin_keys, &app.session, st);
|
||||
let placed = placed_key(&mut app.canvas.placed_keys, &app.session, st);
|
||||
let mut cache = cache_key(app, ctx, st, env.tokens.tokens(), cv, (pw, ph, ppp), (pixel, smooth_images, plugins, placed));
|
||||
|
||||
@@ -32,13 +32,13 @@ pub(crate) fn color_image(img: &vectorcraft_render::Rendered) -> egui::ColorImag
|
||||
}
|
||||
}
|
||||
|
||||
/// Convert an owned [`vectorcraft_render::Rendered`] raster directly into an [`egui::ColorImage`].
|
||||
/// Reuses the raster's heap allocation in place via zero-copy buffer casting when size and
|
||||
/// alignment permit, eliminating redundant multi-megabyte allocations on texture upload.
|
||||
pub(crate) fn color_image_owned(img: vectorcraft_render::Rendered) -> egui::ColorImage {
|
||||
/// The raster `img` rendered in words ([`vectorcraft_render::Renderer::render_words`]) as an egui
|
||||
/// image, in the buffer `img` holds: a word and a [`egui::Color32`] are both four bytes aligned to
|
||||
/// four, so the pixels are not copied. A raster whose pixels don't match its size gives an empty
|
||||
/// image of that size.
|
||||
pub(crate) fn color_image_owned(img: vectorcraft_render::Rendered<Vec<u32>>) -> egui::ColorImage {
|
||||
let size = [img.width as usize, img.height as usize];
|
||||
let expected = size[0].saturating_mul(size[1]).saturating_mul(4);
|
||||
if expected == img.pixels.len() {
|
||||
if size[0].saturating_mul(size[1]) == img.pixels.len() {
|
||||
let pixels: Vec<egui::Color32> = bytemuck::allocation::try_cast_vec(img.pixels).unwrap_or_else(|(_, v)| bytemuck::cast_slice(&v).to_vec());
|
||||
egui::ColorImage::new(size, pixels)
|
||||
} else {
|
||||
@@ -155,7 +155,7 @@ pub(crate) struct KeptFrame {
|
||||
|
||||
/// A frame the render worker finished.
|
||||
pub(crate) struct WorkerFrame {
|
||||
pub(crate) img: vectorcraft_render::Rendered,
|
||||
pub(crate) img: vectorcraft_render::Rendered<Vec<u32>>,
|
||||
/// [`vectorcraft_render::FrameStats::moved`] of the renders that made the frame.
|
||||
pub(crate) moved: usize,
|
||||
/// The frame holds pixels copied from the last frame.
|
||||
@@ -214,10 +214,12 @@ fn exposed_parts(w: u32, h: u32, (dx, dy): (i64, i64)) -> Option<Vec<[u32; 4]>>
|
||||
}
|
||||
|
||||
/// `pixels` of a `w`×`h` frame with the art moved by `(dx, dy)` device pixels. The pixels the art
|
||||
/// does not reach stay transparent.
|
||||
fn moved_pixels(pixels: &[u8], w: u32, h: u32, (dx, dy): (i64, i64)) -> Vec<u8> {
|
||||
/// does not reach stay transparent. The result holds a pixel a word, as
|
||||
/// [`vectorcraft_render::Renderer::render_words`] returns a frame.
|
||||
fn moved_pixels(pixels: &[u8], w: u32, h: u32, (dx, dy): (i64, i64)) -> Vec<u32> {
|
||||
let (w, h) = (i64::from(w), i64::from(h));
|
||||
let mut out = vec![0; pixels.len()];
|
||||
let mut words = vec![0u32; pixels.len() / 4];
|
||||
let out: &mut [u8] = bytemuck::cast_slice_mut(&mut words);
|
||||
let (x0, x1) = (dx.max(0), (w + dx).min(w));
|
||||
if x1 > x0 {
|
||||
for y in dy.max(0)..(h + dy).min(h) {
|
||||
@@ -225,7 +227,7 @@ fn moved_pixels(pixels: &[u8], w: u32, h: u32, (dx, dy): (i64, i64)) -> Vec<u8>
|
||||
out[to..to + n].copy_from_slice(&pixels[from..from + n]);
|
||||
}
|
||||
}
|
||||
out
|
||||
words
|
||||
}
|
||||
|
||||
/// The frame of `job` from `pixels`, the last frame's moved by the pan, and the exposed `parts`
|
||||
@@ -233,12 +235,13 @@ fn moved_pixels(pixels: &[u8], w: u32, h: u32, (dx, dy): (i64, i64)) -> Vec<u8>
|
||||
/// art in a way that depends on the frame's size ([`vectorcraft_render::FrameStats::view_sized`]).
|
||||
fn composed_frame(
|
||||
r: &mut vectorcraft_render::Renderer,
|
||||
mut pixels: Vec<u8>,
|
||||
mut words: Vec<u32>,
|
||||
parts: Vec<[u32; 4]>,
|
||||
job: &crate::render_worker::Job,
|
||||
) -> Option<(vectorcraft_render::Rendered, usize)> {
|
||||
) -> Option<(vectorcraft_render::Rendered<Vec<u32>>, usize)> {
|
||||
let mut moved = 0;
|
||||
let stride = job.w as usize * 4;
|
||||
let pixels: &mut [u8] = bytemuck::cast_slice_mut(&mut words);
|
||||
for [x0, y0, x1, y1] in parts {
|
||||
let view = Affine::translate((-f64::from(x0), -f64::from(y0))) * job.view;
|
||||
let part = r.render(&job.doc, x1 - x0, y1 - y0, view, &job.opts);
|
||||
@@ -252,7 +255,7 @@ fn composed_frame(
|
||||
pixels[to..to + row].copy_from_slice(line);
|
||||
}
|
||||
}
|
||||
Some((vectorcraft_render::Rendered { width: job.w, height: job.h, pixels }, moved))
|
||||
Some((vectorcraft_render::Rendered { width: job.w, height: job.h, pixels: words }, moved))
|
||||
}
|
||||
|
||||
/// Render the frame of `job`. A pan by whole device pixels copies the pixels that stay on screen
|
||||
@@ -276,25 +279,32 @@ pub(crate) fn render_job(r: &mut vectorcraft_render::Renderer, kept: &mut Option
|
||||
});
|
||||
let reused = copied.is_some();
|
||||
let (mut img, moved) = copied.unwrap_or_else(|| {
|
||||
let img = r.render(&job.doc, job.w, job.h, job.view, &job.opts);
|
||||
let img = r.render_words(&job.doc, job.w, job.h, job.view, &job.opts);
|
||||
let moved = r.stats.moved;
|
||||
(img, moved)
|
||||
});
|
||||
// A copied frame's parts draw nothing that depends on the frame's size ([`composed_frame`]).
|
||||
let view_sized = !reused && r.stats.view_sized > 0;
|
||||
let keeps =
|
||||
job.may_keep && moved == 0 && r.stats.view_sized == 0 && img.pixels.len() <= MAX_KEPT_BYTES && (img.width, img.height) == (job.w, job.h);
|
||||
*kept =
|
||||
keeps.then(|| KeptFrame { key: job.key.clone(), opts: job.opts.clone(), view: job.view, pixels: holds_pixels.then(|| img.pixels.clone()) });
|
||||
let keeps = job.may_keep
|
||||
&& moved == 0
|
||||
&& r.stats.view_sized == 0
|
||||
&& img.pixels.len().saturating_mul(4) <= MAX_KEPT_BYTES
|
||||
&& (img.width, img.height) == (job.w, job.h);
|
||||
*kept = keeps.then(|| KeptFrame {
|
||||
key: job.key.clone(),
|
||||
opts: job.opts.clone(),
|
||||
view: job.view,
|
||||
pixels: holds_pixels.then(|| bytemuck::cast_slice(&img.pixels).to_vec()),
|
||||
});
|
||||
// The kept frame stays sRGB, so the next frame's copied pixels are converted only once.
|
||||
let width = img.width;
|
||||
crate::display_profile::convert_over(job.display.as_deref(), &mut img.pixels, width, job.view, job.key.over());
|
||||
crate::display_profile::convert_over(job.display.as_deref(), bytemuck::cast_slice_mut(&mut img.pixels), width, job.view, job.key.over());
|
||||
WorkerFrame { img, moved, reused, view_sized }
|
||||
}
|
||||
|
||||
/// Upload the art's raster directly into the canvas texture without reallocating or copying pixels;
|
||||
/// Pixel Preview's document pixels keep hard edges when magnified.
|
||||
pub(super) fn upload(app: &mut VectorcraftApp, ctx: &egui::Context, img: vectorcraft_render::Rendered, pixel: bool) {
|
||||
/// Upload the art's raster into the canvas texture in the buffer it was rendered into, without
|
||||
/// copying its pixels; Pixel Preview's document pixels keep hard edges when magnified.
|
||||
pub(super) fn upload(app: &mut VectorcraftApp, ctx: &egui::Context, img: vectorcraft_render::Rendered<Vec<u32>>, pixel: bool) {
|
||||
let color = color_image_owned(img);
|
||||
let options = if pixel { egui::TextureOptions::NEAREST } else { egui::TextureOptions::LINEAR };
|
||||
match &mut app.canvas.texture {
|
||||
@@ -325,6 +335,15 @@ pub(super) fn snapped_rect(min: egui::Pos2, size: egui::Vec2, device_ppp: f32) -
|
||||
egui::Rect::from_min_size(pos2(snap(min.x), snap(min.y)), size)
|
||||
}
|
||||
|
||||
/// Whether a view smooths the bitmaps it draws larger than their pixels. While Pixel Preview draws
|
||||
/// its own pixel raster, it follows File Handling › Display Bitmaps as Anti-aliased Images in Pixel Preview.
|
||||
/// This requires a document pixel larger than a screen pixel and a region within the display's texture limit.
|
||||
/// Otherwise it follows File Handling › Display Bitmaps as Anti-aliased Images. Off, each image pixel shows as
|
||||
/// a hard-edged square, in pattern tiles and placed documents too. An image marked pixelated is never smoothed (the renderer checks it).
|
||||
pub(super) fn smooth_images(prefs: &vectorcraft_engine::Prefs, pixel_preview: bool) -> bool {
|
||||
if pixel_preview { prefs.anti_aliased_bitmaps } else { prefs.smooth_bitmaps }
|
||||
}
|
||||
|
||||
/// Pixel Preview: the whole document pixels (x0, y0, x1, y1) under the canvas, rotated view
|
||||
/// included. None when the view is degenerate, or when a side of the region is more than
|
||||
/// `max_side` pixels, the largest texture side the display supports.
|
||||
@@ -365,9 +384,7 @@ pub(super) fn picture(app: &mut VectorcraftApp, ui: &mut Ui, space: &CanvasSpace
|
||||
// View › Pixel Preview: the art as it rasterizes, one pixel per point, while a document pixel
|
||||
// is bigger than a screen pixel (below that the screen render already shows it).
|
||||
let pixel = (app.ui.view.pixel_preview && view.zoom * device_ppp as f64 > 1.0).then(|| pixel_region(&view, max_side)).flatten();
|
||||
// File Handling › Display Bitmaps as Anti-aliased Images in Pixel Preview: off, images show
|
||||
// their pixels as they rasterize, hard-edged.
|
||||
let smooth_images = pixel.is_none() || app.session.prefs.anti_aliased_bitmaps;
|
||||
let smooth_images = smooth_images(&app.session.prefs, pixel.is_some());
|
||||
let plugins = plugin_key(&mut app.canvas.plugin_keys, &app.session, st);
|
||||
let placed = placed_key(&mut app.canvas.placed_keys, &app.session, st);
|
||||
let key = cache_key(app, ui.ctx(), st, env.tokens.tokens(), &view, (w, h, ppp), (pixel, smooth_images, plugins, placed));
|
||||
@@ -785,9 +802,9 @@ fn draw_changed(app: &mut VectorcraftApp, frame: &Frame, region: Option<[u32; 4]
|
||||
let renderer = if plain_patch { web_patch_renderer(&mut app.canvas.web_patch_renderer) } else { &mut app.canvas.renderer };
|
||||
let part = effects.view(|| {
|
||||
if plain_patch {
|
||||
renderer.render_plain_patch(doc, x1 - x0, y1 - y0, part_view, opts)
|
||||
renderer.render_plain_patch_words(doc, x1 - x0, y1 - y0, part_view, opts)
|
||||
} else {
|
||||
Some(renderer.render(doc, x1 - x0, y1 - y0, part_view, opts))
|
||||
Some(renderer.render_words(doc, x1 - x0, y1 - y0, part_view, opts))
|
||||
}
|
||||
});
|
||||
let Some(mut part) = part else {
|
||||
@@ -800,8 +817,8 @@ fn draw_changed(app: &mut VectorcraftApp, frame: &Frame, region: Option<[u32; 4]
|
||||
return false;
|
||||
}
|
||||
let width = part.width;
|
||||
crate::display_profile::convert_over(display.as_deref(), &mut part.pixels, width, part_view, key.over());
|
||||
let color = color_image(&part);
|
||||
crate::display_profile::convert_over(display.as_deref(), bytemuck::cast_slice_mut(&mut part.pixels), width, part_view, key.over());
|
||||
let color = color_image_owned(part);
|
||||
let options = if pixel.is_some() { egui::TextureOptions::NEAREST } else { egui::TextureOptions::LINEAR };
|
||||
tex.set_partial([x0 as usize, y0 as usize], color, options);
|
||||
app.canvas.moved |= renderer.stats.moved > 0;
|
||||
@@ -912,10 +929,10 @@ fn draw_frame(app: &mut VectorcraftApp, ui: &Ui, frame: Frame) {
|
||||
_ => {
|
||||
let t0 = monotonic_ms();
|
||||
let renderer = &mut app.canvas.renderer;
|
||||
let mut img = effects.view(|| renderer.render(doc, w, h, view, &opts));
|
||||
let mut img = effects.view(|| renderer.render_words(doc, w, h, view, &opts));
|
||||
effects.first_view_done();
|
||||
let width = img.width;
|
||||
crate::display_profile::convert_over(display.as_deref(), &mut img.pixels, width, view, key.over());
|
||||
crate::display_profile::convert_over(display.as_deref(), bytemuck::cast_slice_mut(&mut img.pixels), width, view, key.over());
|
||||
upload(app, ui.ctx(), img, pixel.is_some());
|
||||
app.canvas.key = Some(key.clone());
|
||||
app.canvas.shown = Some((doc.clone(), opts.clone()));
|
||||
|
||||
@@ -1752,7 +1752,8 @@ fn translucent_art_over_the_paper() {
|
||||
};
|
||||
let worker = crate::canvas::render_job(&mut vectorcraft_render::Renderer::new(), &mut None, &job(&key, &doc)).img;
|
||||
let near = |a: &[u8], b: egui::Color32| a.iter().zip(b.to_array()).all(|(x, y)| x.abs_diff(y) <= 1);
|
||||
assert!(worker.pixels.as_chunks::<4>().0.iter().zip(&shown).all(|(a, b)| near(a, *b)), "the worker's frame matches");
|
||||
let worker: &[u8] = bytemuck::cast_slice(&worker.pixels);
|
||||
assert!(worker.as_chunks::<4>().0.iter().zip(&shown).all(|(a, b)| near(a, *b)), "the worker's frame matches");
|
||||
// An edit renders its part again, blended too.
|
||||
app.run("paint.setFill", json!({"ids": [half], "color": "#0000ff"})).unwrap();
|
||||
let (pos, part_w, part) = upload(&mut app).expect("the edit shows");
|
||||
@@ -1760,7 +1761,7 @@ fn translucent_art_over_the_paper() {
|
||||
let key = app.canvas.key.clone().unwrap();
|
||||
let doc = app.session.active().unwrap().doc.clone();
|
||||
let whole = crate::canvas::render_job(&mut vectorcraft_render::Renderer::new(), &mut None, &job(&key, &doc)).img;
|
||||
let whole = whole.pixels.as_chunks::<4>().0;
|
||||
let whole = bytemuck::cast_slice::<u32, u8>(&whole.pixels).as_chunks::<4>().0;
|
||||
for (i, c) in part.iter().enumerate() {
|
||||
let at = (y0 + i / part_w) * view_w as usize + x0 + i % part_w;
|
||||
assert!(near(&whole[at], *c), "the part matches the whole frame at {at}: {c:?}, {:?}", whole[at]);
|
||||
@@ -2548,7 +2549,7 @@ fn cached_frames_keep_their_scale() {
|
||||
);
|
||||
}
|
||||
// Deliver the actual replacement and verify that it replaces the cached key.
|
||||
let img = app.canvas.renderer.render(&job.doc, job.w, job.h, job.view, &job.opts);
|
||||
let img = app.canvas.renderer.render_words(&job.doc, job.w, job.h, job.view, &job.opts);
|
||||
let expected = job.key.clone();
|
||||
completed
|
||||
.send(crate::render_worker::Done { key: job.key, doc: job.doc, opts: job.opts, img, ms: 1.0, moved: 0, reused: false, view_sized: false })
|
||||
@@ -2690,7 +2691,7 @@ fn a_pan_fills_the_area() {
|
||||
assert!(!fill_job.may_copy && !fill_job.may_keep, "the fill worker copies nothing and holds no frame");
|
||||
assert!(app.canvas.fill.is_none(), "nothing to draw until the fill arrives");
|
||||
// The fill arrives; the next frame draws it, and asks for no other fill.
|
||||
let img = app.canvas.renderer.render(&fill_job.doc, fill_job.w, fill_job.h, fill_job.view, &fill_job.opts);
|
||||
let img = app.canvas.renderer.render_words(&fill_job.doc, fill_job.w, fill_job.h, fill_job.view, &fill_job.opts);
|
||||
let (doc, opts) = (fill_job.doc, fill_job.opts);
|
||||
fill_completed
|
||||
.send(crate::render_worker::Done { key: fill_job.key, doc, opts, img, ms: 5.0, moved: 0, reused: false, view_sized: false })
|
||||
@@ -2738,12 +2739,12 @@ fn a_pan_fills_the_area() {
|
||||
assert_eq!(Some(&next.key), app.canvas.worker.as_ref().unwrap().pending.as_ref());
|
||||
app.view_mut().unwrap().center = Point::new(250.0, 150.0);
|
||||
// That fill finishes after the worker's frame: it is taken and not kept.
|
||||
let img = app.canvas.renderer.render(&next.doc, next.w, next.h, next.view, &next.opts);
|
||||
let img = app.canvas.renderer.render_words(&next.doc, next.w, next.h, next.view, &next.opts);
|
||||
fill_completed
|
||||
.send(crate::render_worker::Done { key: next.key, doc: next.doc, opts: next.opts, img, ms: 5.0, moved: 0, reused: false, view_sized: false })
|
||||
.unwrap();
|
||||
// The worker's frame arrives: it covers the canvas, and the fill is no longer drawn or kept.
|
||||
let img = app.canvas.renderer.render(&job.doc, job.w, job.h, job.view, &job.opts);
|
||||
let img = app.canvas.renderer.render_words(&job.doc, job.w, job.h, job.view, &job.opts);
|
||||
let expected = job.key.clone();
|
||||
completed
|
||||
.send(crate::render_worker::Done { key: job.key, doc: job.doc, opts: job.opts, img, ms: 50.0, moved: 0, reused: false, view_sized: false })
|
||||
@@ -3174,6 +3175,77 @@ fn pixel_preview_smooths_bitmaps_only_when_asked() {
|
||||
assert!(smooth(&mut app), "Pixel Preview, on");
|
||||
}
|
||||
|
||||
/// File Handling › Display Bitmaps as Anti-aliased Images (#10712): on by default, the canvas
|
||||
/// smooths images out of Pixel Preview as it always has; off, it draws them with each pixel taking
|
||||
/// its nearest image pixel. Pixel Preview keeps following its own preference.
|
||||
#[test]
|
||||
fn every_view_smooths_bitmaps_unless_turned_off() {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
app.canvas.worker_started = true; // render on this thread
|
||||
let ctx = crate::testing::ui_context();
|
||||
let smooth = |app: &mut VectorcraftApp| {
|
||||
let (_, mut delta) = frame_output(app, &ctx);
|
||||
delta.clear();
|
||||
app.canvas.key.as_ref().map(|k| k.smooth_images).unwrap()
|
||||
};
|
||||
assert!(smooth(&mut app), "on by default");
|
||||
app.run("prefs.set", json!({"key": "smoothBitmaps", "value": false})).unwrap();
|
||||
assert!(!smooth(&mut app), "off: nearest sampling in Preview");
|
||||
app.run("prefs.set", json!({"key": "antiAliasedBitmaps", "value": true})).unwrap();
|
||||
app.ui.view.pixel_preview = true;
|
||||
app.view_mut().unwrap().zoom = 8.0;
|
||||
assert!(smooth(&mut app), "Pixel Preview follows its own preference");
|
||||
app.ui.view.pixel_preview = false;
|
||||
app.run("prefs.set", json!({"key": "smoothBitmaps", "value": true})).unwrap();
|
||||
assert!(smooth(&mut app), "on again");
|
||||
}
|
||||
|
||||
/// File Handling › Display Bitmaps as Anti-aliased Images (#10712), in the canvas's pixels: a 2×2
|
||||
/// black and white checker zoomed far in shows only black and white with the setting off, and a
|
||||
/// ramp of greys between its squares with it on.
|
||||
#[test]
|
||||
fn a_zoomed_in_bitmap_shows_hard_pixels_with_smoothing_off() {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
app.ui.task_bar = false;
|
||||
app.ui.view.rulers = false;
|
||||
let img = image::RgbaImage::from_fn(2, 2, |x, y| image::Rgba(if (x + y) % 2 == 0 { [0, 0, 0, 255] } else { [255, 255, 255, 255] }));
|
||||
let mut png = vec![];
|
||||
img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
|
||||
let data = vectorcraft_format::base64_encode(&png);
|
||||
app.run("file.place", json!({"name": "checker.png", "dataBase64": data, "link": false, "at": [200, 150]})).unwrap();
|
||||
app.run("select.none", json!({})).unwrap();
|
||||
app.canvas.worker_started = true; // render on this thread
|
||||
let ctx = crate::testing::ui_context();
|
||||
// How many pixels of the canvas's middle row, across the checker's top row, are neither its
|
||||
// black nor its white.
|
||||
let greys = |app: &mut VectorcraftApp| {
|
||||
let (_, mut delta) = frame_output(app, &ctx);
|
||||
let art = app.canvas.texture.as_ref().unwrap().id();
|
||||
let (w, h, px) = delta
|
||||
.set
|
||||
.iter()
|
||||
.find(|e| e.0.eq(&art))
|
||||
.and_then(|e| e.1.last())
|
||||
.map(|d| {
|
||||
let egui::ImageData::Color(img) = &d.image;
|
||||
(img.width(), img.height(), img.pixels.clone())
|
||||
})
|
||||
.expect("the art rendered");
|
||||
delta.clear();
|
||||
// The checker is centered in the view, 2 pt square at a zoom of 32: 64 pixels a side.
|
||||
let (cx, y) = (w / 2, h / 2 - 16);
|
||||
(cx - 28..cx + 28).filter(|x| (16..240).contains(&px[y * w + x].r())).count()
|
||||
};
|
||||
frame_output(&mut app, &ctx).1.clear(); // the first frame fits the view to the artboard
|
||||
let view = app.view_mut().unwrap();
|
||||
(view.zoom, view.center) = (32.0, Point::new(200.0, 150.0));
|
||||
assert!(greys(&mut app) >= 8, "on by default: a ramp from black to white");
|
||||
app.run("prefs.set", json!({"key": "smoothBitmaps", "value": false})).unwrap();
|
||||
assert_eq!(greys(&mut app), 0, "off: each pixel is black or white");
|
||||
}
|
||||
|
||||
/// Appearance of Black › On Screen (#394): Display All Blacks Accurately (the default) shows
|
||||
/// pure CMYK black through the CMYK profile, a dark grey; Display All Blacks as Rich Black
|
||||
/// shows it as RGB black. A rich black shows the same either way.
|
||||
@@ -5961,7 +6033,7 @@ fn poll_worker_accepts_frames_not_older_than_displayed_and_discards_obsolete_fra
|
||||
// It is newer than displayed revision 2: it MUST be accepted and uploaded.
|
||||
let mut rev5_key = initial_key.clone();
|
||||
rev5_key.revision = 5;
|
||||
let img5 = vectorcraft_render::Rendered { width: 10, height: 10, pixels: vec![200; 400] };
|
||||
let img5 = vectorcraft_render::Rendered { width: 10, height: 10, pixels: vec![u32::from_ne_bytes([200; 4]); 100] };
|
||||
done_tx
|
||||
.send(crate::render_worker::Done {
|
||||
key: rev5_key,
|
||||
@@ -5985,7 +6057,7 @@ fn poll_worker_accepts_frames_not_older_than_displayed_and_discards_obsolete_fra
|
||||
// Worker completes an older revision 3 (out of order). It is older than displayed 5, so discarded.
|
||||
let mut rev3_key = initial_key.clone();
|
||||
rev3_key.revision = 3;
|
||||
let img3 = vectorcraft_render::Rendered { width: 10, height: 10, pixels: vec![150; 400] };
|
||||
let img3 = vectorcraft_render::Rendered { width: 10, height: 10, pixels: vec![u32::from_ne_bytes([150; 4]); 100] };
|
||||
done_tx
|
||||
.send(crate::render_worker::Done {
|
||||
key: rev3_key,
|
||||
@@ -6008,7 +6080,7 @@ fn poll_worker_accepts_frames_not_older_than_displayed_and_discards_obsolete_fra
|
||||
// Worker completes another intermediate revision 8. Newer than displayed 5, so uploaded.
|
||||
let mut rev8_key = initial_key.clone();
|
||||
rev8_key.revision = 8;
|
||||
let img8 = vectorcraft_render::Rendered { width: 10, height: 10, pixels: vec![180; 400] };
|
||||
let img8 = vectorcraft_render::Rendered { width: 10, height: 10, pixels: vec![u32::from_ne_bytes([180; 4]); 100] };
|
||||
done_tx
|
||||
.send(crate::render_worker::Done {
|
||||
key: rev8_key,
|
||||
@@ -6031,7 +6103,7 @@ fn poll_worker_accepts_frames_not_older_than_displayed_and_discards_obsolete_fra
|
||||
// Finally, the settling frame at revision 10 completes: it is accepted and uploaded.
|
||||
let mut rev10_key = initial_key;
|
||||
rev10_key.revision = 10;
|
||||
let img10 = vectorcraft_render::Rendered { width: 10, height: 10, pixels: vec![255; 400] };
|
||||
let img10 = vectorcraft_render::Rendered { width: 10, height: 10, pixels: vec![u32::MAX; 100] };
|
||||
done_tx
|
||||
.send(crate::render_worker::Done {
|
||||
key: rev10_key,
|
||||
@@ -6101,7 +6173,7 @@ fn the_contour_bar_sets_corners_and_bakes() {
|
||||
|
||||
/// A frame the render worker finished for `job`: white pixels of the job's size.
|
||||
fn finished(job: &crate::render_worker::Job) -> crate::render_worker::Done {
|
||||
let img = vectorcraft_render::Rendered { width: job.w, height: job.h, pixels: vec![255; job.w as usize * job.h as usize * 4] };
|
||||
let img = vectorcraft_render::Rendered { width: job.w, height: job.h, pixels: vec![u32::MAX; job.w as usize * job.h as usize] };
|
||||
crate::render_worker::Done {
|
||||
key: job.key.clone(),
|
||||
doc: job.doc.clone(),
|
||||
@@ -6167,9 +6239,9 @@ fn a_whole_pixel_pan() {
|
||||
let frame = render_job(&mut r, &mut kept, &job);
|
||||
assert!(frame.reused, "{pan:?}");
|
||||
let at = ((64 + pan.1 as i64) * 256 + 128 + pan.0 as i64) as usize * 4;
|
||||
assert_eq!(frame.img.pixels[at..at + 4], [1, 2, 3, 4], "{pan:?}: the marked pixel moved with the art");
|
||||
let mut img = bytemuck::cast_slice::<u32, u8>(&frame.img.pixels).to_vec();
|
||||
assert_eq!(img[at..at + 4], [1, 2, 3, 4], "{pan:?}: the marked pixel moved with the art");
|
||||
let whole = vectorcraft_render::Renderer::new().render(&doc, 256, 128, job.view, &job.opts);
|
||||
let mut img = frame.img.pixels;
|
||||
img[at..at + 4].copy_from_slice(&whole.pixels[at..at + 4]);
|
||||
assert_eq!(img, whole.pixels, "{pan:?}: the same picture as a whole render");
|
||||
}
|
||||
@@ -6431,11 +6503,12 @@ fn worker_frames_match_a_fresh_render() {
|
||||
let frame = render_job(&mut r, &mut kept, &job);
|
||||
assert_eq!(frame.reused, copies, "{name}");
|
||||
let whole = vectorcraft_render::Renderer::new().render(&job.doc, job.w, job.h, job.view, &job.opts);
|
||||
let pixels: &[u8] = bytemuck::cast_slice(&frame.img.pixels);
|
||||
if copies {
|
||||
let off = frame.img.pixels.iter().zip(&whole.pixels).map(|(a, b)| a.abs_diff(*b)).max();
|
||||
let off = pixels.iter().zip(&whole.pixels).map(|(a, b)| a.abs_diff(*b)).max();
|
||||
assert!(off.is_some_and(|d| d <= 1), "{name}: {off:?}");
|
||||
} else {
|
||||
assert_eq!(frame.img.pixels, whole.pixels, "{name}");
|
||||
assert!(pixels == whole.pixels.as_slice(), "{name}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6494,7 +6567,7 @@ fn a_pan_over_art() {
|
||||
let pan = job(-40.0);
|
||||
let frame = render_job(&mut r, &mut kept, &pan);
|
||||
let whole = vectorcraft_render::Renderer::new().render(&pan.doc, pan.w, pan.h, pan.view, &pan.opts);
|
||||
let off = frame.img.pixels.iter().zip(&whole.pixels).map(|(a, b)| a.abs_diff(*b)).max();
|
||||
let off = bytemuck::cast_slice::<u32, u8>(&frame.img.pixels).iter().zip(&whole.pixels).map(|(a, b)| a.abs_diff(*b)).max();
|
||||
assert!(off.is_some_and(|d| d <= 1), "{name}: a channel differs by {off:?}");
|
||||
assert!(!frame.reused, "{name}: the pan renders whole");
|
||||
assert!(kept.is_none(), "{name}: the frame is not kept");
|
||||
@@ -6965,3 +7038,22 @@ fn a_wheel_pan_under_a_resting_pointer_keeps_the_tool_cursor() {
|
||||
}
|
||||
assert!(asks() > before, "once the view is still, the tool gives the cursor again");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_worker_s_frame_reaches_its_texture_image_in_the_buffer_it_was_rendered_into() {
|
||||
let (doc, key) = pan_doc();
|
||||
let mut r = vectorcraft_render::Renderer::new();
|
||||
let job = pan_job(&doc, &key, (0.0, 0.0));
|
||||
let frame = render_job(&mut r, &mut None, &job).img;
|
||||
let at = frame.pixels.as_ptr() as usize;
|
||||
let color = color_image_owned(frame);
|
||||
assert_eq!(color.pixels.as_ptr() as usize, at, "the frame's pixels are handed to the image, not copied");
|
||||
let bytes = vectorcraft_render::Renderer::new().render(&doc, job.w, job.h, job.view, &job.opts);
|
||||
assert!(color.pixels == color_image(&bytes).pixels, "the image holds the frame's pixels");
|
||||
assert_eq!(color.size, [256, 128]);
|
||||
// A raster whose pixels don't match its size gives an empty image of that size.
|
||||
let short = vectorcraft_render::Rendered { width: 3, height: 2, pixels: vec![u32::MAX; 5] };
|
||||
let empty = color_image_owned(short);
|
||||
assert_eq!(empty.pixels.len(), 6, "the empty image has one pixel per position of its size");
|
||||
assert!(empty.size == [3, 2] && empty.pixels.iter().all(|c| *c == Color32::TRANSPARENT), "a raster of the wrong length is not shown");
|
||||
}
|
||||
@@ -149,11 +149,40 @@ struct SessionTool<'a> {
|
||||
/// The canvas's context and layer: a window over the canvas (a floating document's) hides it from the pointer.
|
||||
ctx: egui::Context,
|
||||
layer: egui::LayerId,
|
||||
/// The drag samples of this pass for a tool that takes every position the pointer passed, handed to the session
|
||||
/// together by [`Self::send_samples`].
|
||||
samples: RefCell<Vec<PointerEvent>>,
|
||||
}
|
||||
|
||||
impl<'a> SessionTool<'a> {
|
||||
fn new(app: &'a mut VectorcraftApp, view: ViewInfo, ui: &Ui) -> Self {
|
||||
Self { app: RefCell::new(app), view, carrying: Cell::new(false), ctx: ui.ctx().clone(), layer: ui.layer_id() }
|
||||
Self { app: RefCell::new(app), view, carrying: Cell::new(false), ctx: ui.ctx().clone(), layer: ui.layer_id(), samples: RefCell::new(vec![]) }
|
||||
}
|
||||
|
||||
/// Keeps `ev`, a drag or the release, for [`Self::send_samples`] when the tool takes every position the pointer
|
||||
/// passed; otherwise hands the kept samples and then `ev` to the session.
|
||||
fn send_sample(&self, ev: PointerEvent) {
|
||||
if self.app().session.tool_wants_samples() {
|
||||
self.samples.borrow_mut().push(ev);
|
||||
} else {
|
||||
self.send_samples();
|
||||
dispatch(&mut self.app(), &ev, self.view);
|
||||
}
|
||||
}
|
||||
|
||||
/// Hands the drag samples kept in this pass to the session ([`vectorcraft_engine::Session::pointer_samples`]),
|
||||
/// which applies only the last of the tool's previews, and acts on what they ask of the UI. Each call on the tool
|
||||
/// other than a drag runs it first, so every other event reaches the tool after the samples before it.
|
||||
fn send_samples(&self) {
|
||||
let samples = std::mem::take(&mut *self.samples.borrow_mut());
|
||||
let mut rest = samples.as_slice();
|
||||
while !rest.is_empty() {
|
||||
let mut app = self.app();
|
||||
let (fed, r) = app.session.pointer_samples(rest, self.view);
|
||||
sync_artboard(&mut app);
|
||||
apply_requests(&mut app, r);
|
||||
rest = rest.get(fed.max(1)..).unwrap_or_default();
|
||||
}
|
||||
}
|
||||
|
||||
/// `ev` with Shift, Alt, Cmd and Ctrl as they were held when the gesture's button went up in this pass, latched ones
|
||||
@@ -284,6 +313,7 @@ fn engine_key(chord: Chord) -> Option<(EngineKey, bool)> {
|
||||
|
||||
impl CanvasTool for SessionTool<'_> {
|
||||
fn press(&mut self, pointer: &ToolPointer, cx: &mut ToolContext<'_>) -> ToolAction {
|
||||
self.send_samples();
|
||||
let mut app = self.app();
|
||||
if app.ui.screen_mode == 3 {
|
||||
// Presentation Mode: the tool gets nothing; the release of a click steps to the next artboard.
|
||||
@@ -342,7 +372,7 @@ impl CanvasTool for SessionTool<'_> {
|
||||
if !carried {
|
||||
// The moves of the pass that releases the press came before its release, with the keys held then.
|
||||
let ev = self.at_release(pointer, pointer_event(PointerKind::Drag, pointer, cx));
|
||||
dispatch(&mut self.app(), &ev, self.view);
|
||||
self.send_sample(ev);
|
||||
self.app().canvas.last_drag = Some((pointer.pos, ev));
|
||||
}
|
||||
self.carrying.set(carried);
|
||||
@@ -367,6 +397,7 @@ impl CanvasTool for SessionTool<'_> {
|
||||
let given_up = cx.over_drop_target() || carried.is_some();
|
||||
if given_up {
|
||||
// The art goes to the drop target, or nowhere off the canvas: the move is given up where it started.
|
||||
self.send_samples();
|
||||
let _ = self.app().session.cancel_interaction();
|
||||
}
|
||||
if let Some(art) = carried.filter(|_| !cx.over_drop_target()) {
|
||||
@@ -381,9 +412,11 @@ impl CanvasTool for SessionTool<'_> {
|
||||
// that pass still draws a square. A move that was given up gets none.
|
||||
let last = self.app().canvas.last_drag.map(|(_, ev)| ev);
|
||||
if !given_up && last.is_some_and(|last| (last.pos, last.mods, last.backquote) != (up.pos, up.mods, up.backquote)) {
|
||||
dispatch(&mut self.app(), &PointerEvent { kind: PointerKind::Drag, ..up }, self.view);
|
||||
self.send_sample(PointerEvent { kind: PointerKind::Drag, ..up });
|
||||
}
|
||||
dispatch(&mut self.app(), &up, self.view);
|
||||
// The release goes to the session after the samples of its pass, which preview the stroke once before it.
|
||||
self.send_sample(up);
|
||||
self.send_samples();
|
||||
if self.app().canvas.last_drag.is_some() {
|
||||
// A press that dragged is no click, and the framework counts presses: the next press starts a new run.
|
||||
self.app().ui.trace_pick_clicks = pointer.clicks;
|
||||
@@ -412,10 +445,12 @@ impl CanvasTool for SessionTool<'_> {
|
||||
}
|
||||
|
||||
fn hover(&mut self, pointer: &ToolPointer, cx: &mut ToolContext<'_>) {
|
||||
self.send_samples();
|
||||
self.send(PointerKind::Move, pointer, cx);
|
||||
}
|
||||
|
||||
fn cancel(&mut self, reason: CancelReason, cx: &mut ToolContext<'_>) {
|
||||
self.send_samples();
|
||||
let mut app = self.app();
|
||||
if app.ui.screen_mode == 3 {
|
||||
// The tool had no press of Presentation Mode's.
|
||||
@@ -435,6 +470,7 @@ impl CanvasTool for SessionTool<'_> {
|
||||
}
|
||||
|
||||
fn claims(&self) -> ToolClaims {
|
||||
self.send_samples();
|
||||
let mut app = self.app();
|
||||
let view = self.view;
|
||||
let claim = |app: &mut VectorcraftApp, key: EngineKey| app.session.tool_claims_key(key, view);
|
||||
@@ -477,6 +513,7 @@ impl CanvasTool for SessionTool<'_> {
|
||||
}
|
||||
|
||||
fn key(&mut self, key: &ToolKey, cx: &mut ToolContext<'_>) -> bool {
|
||||
self.send_samples();
|
||||
let space = cx.held(Key::Space);
|
||||
let held = tool_mods(cx.mods, space);
|
||||
match key {
|
||||
@@ -564,6 +601,7 @@ impl CanvasTool for SessionTool<'_> {
|
||||
/// While the view moves under the pointer, the cursor the tool last gave for the same tool and keys stays: asking
|
||||
/// the tool again would hit-test the art under the pointer in every frame of a pan or zoom (#2452).
|
||||
fn cursor(&self, cx: &ToolContext<'_>) -> Cursor {
|
||||
self.send_samples();
|
||||
let Some(space) = cx.space() else { return tool_cursor(vectorcraft_tools::Cursor::Arrow) };
|
||||
let at = cx.pointer.map_or(Point::ZERO, |p| space.view.to_doc(p.pos));
|
||||
let mods = tool_mods(cx.mods, cx.held(Key::Space));
|
||||
@@ -730,6 +768,7 @@ pub(crate) fn run(app: &mut VectorcraftApp, ui: &mut Ui, pass: &ToolPass) -> Too
|
||||
app.canvas.zoom_tool = None;
|
||||
let mut tool = SessionTool::new(app, view_info, ui);
|
||||
let response = host_run_session(&mut tool, ui, pass);
|
||||
tool.send_samples();
|
||||
drop(tool);
|
||||
response
|
||||
};
|
||||
|
||||
@@ -215,3 +215,138 @@ fn the_caps_lock_command_before_the_first_frame_stays_in_place() {
|
||||
frame(&mut app, &ctx, vec![]);
|
||||
assert!(app.session.caps_lock);
|
||||
}
|
||||
|
||||
/// The moves of one pass reach the Pencil together: the pass previews the stroke once, and the path the release draws
|
||||
/// runs from the press to the last move.
|
||||
#[test]
|
||||
fn a_pencil_pass_of_four_moves_previews_once() {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.new", serde_json::json!({"width": 400, "height": 300})).unwrap();
|
||||
app.select_tool("pencil");
|
||||
let ctx = crate::testing::ui_context();
|
||||
frame(&mut app, &ctx, vec![]);
|
||||
let view = app.canvas_view().unwrap();
|
||||
let on_wave = |x: f64| Point::new(x, 150.0 + 20.0 * (x / 15.0).sin());
|
||||
let at = |x: f64| view.to_screen(on_wave(x));
|
||||
let button =
|
||||
|x: f64, pressed| egui::Event::PointerButton { pos: at(x), button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
|
||||
let moves = |from: f64, n: u32| (1..=n).map(|i| egui::Event::PointerMoved(at(from + 6.0 * f64::from(i)))).collect::<Vec<_>>();
|
||||
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at(100.0)), button(100.0, true)]);
|
||||
frame(&mut app, &ctx, moves(100.0, 4));
|
||||
// Each preview the pass runs moves the revision by the same amount.
|
||||
let revision = |app: &VectorcraftApp| app.session.active().unwrap().revision;
|
||||
let before = revision(&app);
|
||||
frame(&mut app, &ctx, moves(124.0, 1));
|
||||
let one = revision(&app) - before;
|
||||
assert!(one > 0, "a pass of one move previews the stroke");
|
||||
let before = revision(&app);
|
||||
frame(&mut app, &ctx, moves(130.0, 4));
|
||||
assert_eq!(revision(&app) - before, one, "a pass of 4 moves previews the stroke once, as a pass of one move does");
|
||||
frame(&mut app, &ctx, vec![button(154.0, false)]);
|
||||
let mut ends = vec![];
|
||||
app.session.active().unwrap().doc.walk(|n| {
|
||||
if let Some(pd) = n.path_data() {
|
||||
ends.extend(pd.subpaths.iter().filter_map(|sp| Some((sp.anchors.first()?.p, sp.anchors.last()?.p))));
|
||||
}
|
||||
});
|
||||
let near = |a: Point, x: f64| a.distance(on_wave(x)) < 0.5;
|
||||
assert!(matches!(ends.as_slice(), [(first, last)] if near(*first, 100.0) && near(*last, 154.0)), "{ends:?}");
|
||||
}
|
||||
|
||||
/// The release reaches the Pencil after the moves of its pass: a pass of 4 moves and the release previews the moves
|
||||
/// once, as a pass of one move and the release does, and the path runs from the press to the release.
|
||||
#[test]
|
||||
fn a_pencil_release_with_moves_previews_once() {
|
||||
// The revision's change in the pass that releases after `last` moves, and the ends of the paths drawn.
|
||||
let stroke = |last: u32| {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.new", serde_json::json!({"width": 400, "height": 300})).unwrap();
|
||||
app.select_tool("pencil");
|
||||
let ctx = crate::testing::ui_context();
|
||||
frame(&mut app, &ctx, vec![]);
|
||||
let view = app.canvas_view().unwrap();
|
||||
let on_wave = |x: f64| Point::new(x, 150.0 + 20.0 * (x / 15.0).sin());
|
||||
let at = |x: f64| view.to_screen(on_wave(x));
|
||||
let button =
|
||||
|x: f64, pressed| egui::Event::PointerButton { pos: at(x), button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
|
||||
let moves = |from: f64, n: u32| (1..=n).map(|i| egui::Event::PointerMoved(at(from + 6.0 * f64::from(i)))).collect::<Vec<_>>();
|
||||
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at(100.0)), button(100.0, true)]);
|
||||
frame(&mut app, &ctx, moves(100.0, 4));
|
||||
let before = app.session.active().unwrap().revision;
|
||||
let end = 124.0 + 6.0 * f64::from(last);
|
||||
let mut pass = moves(124.0, last);
|
||||
pass.push(button(end, false));
|
||||
frame(&mut app, &ctx, pass);
|
||||
let changed = app.session.active().unwrap().revision - before;
|
||||
let mut ends = vec![];
|
||||
app.session.active().unwrap().doc.walk(|n| {
|
||||
if let Some(pd) = n.path_data() {
|
||||
ends.extend(pd.subpaths.iter().filter_map(|sp| Some((sp.anchors.first()?.p, sp.anchors.last()?.p))));
|
||||
}
|
||||
});
|
||||
let near = |a: Point, x: f64| a.distance(on_wave(x)) < 0.5;
|
||||
assert!(matches!(ends.as_slice(), [(first, last)] if near(*first, 100.0) && near(*last, end)), "{ends:?}");
|
||||
changed
|
||||
};
|
||||
let one = stroke(1);
|
||||
assert!(one > stroke(0), "a move in the release's pass previews the stroke");
|
||||
assert_eq!(stroke(4), one, "a pass of 4 moves and the release previews the moves once, as a pass of one move does");
|
||||
}
|
||||
|
||||
/// The Pencil draws the same path when the moves come in passes of 4, the last one with the release, as when each move
|
||||
/// comes in a pass of its own: the moves inside a pass bend the path.
|
||||
#[test]
|
||||
fn a_pencil_stroke_in_passes_of_four_keeps_every_bend() {
|
||||
let stroke = |grouped: bool| {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.new", serde_json::json!({"width": 400, "height": 300})).unwrap();
|
||||
app.select_tool("pencil");
|
||||
let ctx = crate::testing::ui_context();
|
||||
frame(&mut app, &ctx, vec![]);
|
||||
let view = app.canvas_view().unwrap();
|
||||
let start = view.to_screen(Point::new(80.0, 150.0));
|
||||
let end = view.to_screen(Point::new(320.0, 150.0));
|
||||
let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
|
||||
// Every fourth move lies on the chord: a path made from the last move of each pass alone has no bend.
|
||||
let moves: Vec<_> = (1..=12)
|
||||
.zip([90.0, 210.0, 90.0, 150.0, 90.0, 210.0, 90.0, 150.0, 90.0, 210.0, 90.0, 150.0])
|
||||
.map(|(i, y)| egui::Event::PointerMoved(view.to_screen(Point::new(80.0 + 20.0 * f64::from(i), y))))
|
||||
.collect();
|
||||
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(start), button(start, true)]);
|
||||
let pass_size = if grouped { 4 } else { 1 };
|
||||
for (i, chunk) in moves.chunks(pass_size).enumerate() {
|
||||
let mut events = chunk.to_vec();
|
||||
if grouped && (i + 1) * pass_size == moves.len() {
|
||||
events.push(button(end, false));
|
||||
}
|
||||
frame(&mut app, &ctx, events);
|
||||
}
|
||||
if !grouped {
|
||||
frame(&mut app, &ctx, vec![button(end, false)]);
|
||||
}
|
||||
let mut paths = vec![];
|
||||
app.session.active().unwrap().doc.walk(|n| {
|
||||
if let Some(pd) = n.path_data() {
|
||||
paths.push(pd.clone());
|
||||
}
|
||||
});
|
||||
paths
|
||||
};
|
||||
let separate = stroke(false);
|
||||
let grouped = stroke(true);
|
||||
assert_eq!(grouped, separate, "grouping moves with the release preserves every path's data");
|
||||
assert_eq!(separate.len(), 1, "the stroke creates one path");
|
||||
assert_eq!(separate[0].subpaths.len(), 1, "the stroke creates one subpath");
|
||||
let anchors = &separate[0].subpaths[0].anchors;
|
||||
let first = anchors.first().unwrap().p;
|
||||
let last = anchors.last().unwrap().p;
|
||||
let chord = first.distance(last);
|
||||
assert!(chord > 1.0, "the stroke has distinct endpoints");
|
||||
assert!(
|
||||
anchors.iter().any(|a| {
|
||||
let cross = (last.x - first.x) * (a.p.y - first.y) - (last.y - first.y) * (a.p.x - first.x);
|
||||
cross.abs() / chord > 1.0
|
||||
}),
|
||||
"the finished path has a bend more than 1 pt from its chord"
|
||||
);
|
||||
}
|
||||
@@ -127,10 +127,11 @@ fn corner_radius(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
let Some(picked) = crate::panels::picked_corners(app) else { return };
|
||||
let label = tl!("Corner Radius:");
|
||||
let lengths = crate::canvas::general_lengths(app);
|
||||
let target = crate::panels::corner_target(app, &picked.corners);
|
||||
let mut typed = None;
|
||||
group(ui, rank::GROUP, |ui| {
|
||||
crate::panels::corners_link(app, ui);
|
||||
let number = NumberField::length(label, Bind::given(picked.radius), lengths).show(ui);
|
||||
let number = NumberField::length(label, Bind::given(picked.radius), lengths).edit_target(target).show(ui);
|
||||
typed = number.edit.events.committed().copied().flatten().or(typed);
|
||||
});
|
||||
if let Some(radius) = typed {
|
||||
|
||||
@@ -3224,6 +3224,34 @@ fn the_control_bar_opacity_drops_an_unfinished_value_on_file_revert() {
|
||||
assert_eq!(opacity, 0.01, "Revert drops the unfinished value: 1%, not 20+1");
|
||||
}
|
||||
|
||||
/// A radius typed into the Control bar's Corner Radius field and not yet entered is dropped when
|
||||
/// another corner with the same radius is Direct-Selected: Enter sets only what was typed after.
|
||||
#[test]
|
||||
fn the_control_bar_corner_radius_drops_an_unfinished_value_when_the_corners_change() {
|
||||
use egui::{Key, Modifiers};
|
||||
crate::i18n::set_current(crate::i18n::Lang::EN);
|
||||
let mut app = crate::VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
|
||||
let id = app.run("shape.rectangle", json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap();
|
||||
app.run("select.set", json!({"ids": [id]})).unwrap();
|
||||
app.run("object.expandShape", json!({})).unwrap();
|
||||
app.select_tool("directSelection");
|
||||
app.run("select.anchors", json!({"id": id, "anchors": [[0, 0]], "mode": "set"})).unwrap();
|
||||
let mut bar = crate::tests::panel_harness::Panel::new(app, crate::chrome::control_bar);
|
||||
bar.room(egui::vec2(2400.0, 400.0)).frame();
|
||||
bar.click_role("Corner Radius:", Role::SPIN_BUTTON);
|
||||
bar.key(Key::A, Modifiers::COMMAND);
|
||||
bar.type_text("3+");
|
||||
bar.app().run("select.anchors", json!({"id": id, "anchors": [[0, 1]], "mode": "set"})).unwrap();
|
||||
bar.frame();
|
||||
assert_eq!(bar.value_role("Corner Radius:", Role::SPIN_BUTTON).as_deref(), Some("0 pt"), "the field shows the new corner's radius");
|
||||
bar.type_text("1");
|
||||
bar.key(Key::Enter, Modifiers::NONE);
|
||||
let n = bar.app().session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().clone();
|
||||
let lc = vectorcraft_doc::LiveCorners::of(&n).unwrap();
|
||||
assert_eq!((0..4).map(|k| lc.radius(k)).collect::<Vec<_>>(), [0.0, 1.0, 0.0, 0.0], "the second corner takes 1 pt, not 3+1");
|
||||
}
|
||||
|
||||
/// With the Artboard tool in use, the Control bar shows the Align buttons after the artboard
|
||||
/// controls while it has room, and the Distribute buttons for two or more selected artboards with
|
||||
/// Align to Artboard and three or more with Align to Selection. A
|
||||
|
||||
@@ -349,7 +349,7 @@ fn image(f: &CompositeFont, zoom: u64, marks: &[Mark], ppp: f32, ink: Color32) -
|
||||
mark_line(&mut rendered, ((base - y) as f32 * ppp).round(), ppp.ceil().max(1.0) as usize, m.color());
|
||||
}
|
||||
}
|
||||
crate::canvas::color_image_owned(rendered)
|
||||
crate::canvas::color_image(&rendered)
|
||||
}
|
||||
|
||||
/// Draws a horizontal line `thickness` pixels thick from row `y` across `image`; a row outside it draws nothing.
|
||||
|
||||
@@ -650,3 +650,25 @@ fn edit_find_next_starts_at_the_first_restored_match_with_that_frame_selected()
|
||||
assert_eq!(selected(&p), vec![first]);
|
||||
assert_eq!(undo_steps(&p), before);
|
||||
}
|
||||
|
||||
/// `ui.findAndReplace` and `ui.paramDialog` with edit.findReplace open the dialog that `ui.inspect` lists with key null
|
||||
/// and the fields the params text names, as both params texts say.
|
||||
#[test]
|
||||
fn params_texts_match_what_ui_inspect_lists() {
|
||||
let expected = ["find", "replace", "matchCase", "wholeWord", "backwards", "hiddenLayers", "lockedLayers", "action"];
|
||||
let doc = |command: &str| crate::menus::UI_COMMANDS.iter().find(|c| c.0 == command).expect("registered").3;
|
||||
for (command, params) in [("ui.findAndReplace", json!({})), ("ui.paramDialog", json!({"command": super::COMMAND, "params": {}}))] {
|
||||
let mut app = crate::testing::windowed(app_with(&["alpha"]).0);
|
||||
app.run(command, params).unwrap();
|
||||
let ctx = app.ui_ctx.clone().unwrap();
|
||||
let ui = crate::control::inspect(&app, &ctx);
|
||||
let entry = ui["dialogs"].as_array().and_then(|d| d.last()).cloned().expect("a dialog");
|
||||
assert_eq!(entry.get("key"), Some(&Value::Null), "{command}: {entry}");
|
||||
assert!(doc(command).contains("with key null"), "{command} opens a dialog with key null, which its params text does not say");
|
||||
let missing: Vec<&str> = expected.iter().copied().filter(|f| entry["fields"].get(*f).is_none()).collect();
|
||||
assert!(missing.is_empty(), "{command}: ui.inspect does not list {missing:?}");
|
||||
}
|
||||
let named = doc("ui.paramDialog");
|
||||
let unnamed: Vec<&str> = expected.iter().copied().filter(|f| !named.contains(*f)).collect();
|
||||
assert!(unnamed.is_empty(), "the params text of ui.paramDialog does not name {unnamed:?}");
|
||||
}
|
||||
@@ -128,8 +128,8 @@ fn render_page_preview(
|
||||
let region = doc.artboards.first()?.rect;
|
||||
let px = PREVIEW_PX * pixels_per_point as f64;
|
||||
let scale = px / region.width().max(region.height()).max(1.0);
|
||||
let img = renderer.render_region(doc, region, scale, true);
|
||||
Some(Arc::new(crate::canvas::color_image(&img)))
|
||||
let img = renderer.render_region_words(doc, region, scale, true);
|
||||
Some(Arc::new(crate::canvas::color_image_owned(img)))
|
||||
}
|
||||
|
||||
/// Everything the dialog asks and shows: the form's value, and what an OK needs to open or place the file.
|
||||
|
||||
@@ -111,6 +111,10 @@ impl StackDialog for JavaScriptFiles {
|
||||
dialog_id(KEY)
|
||||
}
|
||||
|
||||
fn key(&self) -> Option<&str> {
|
||||
Some(KEY)
|
||||
}
|
||||
|
||||
fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option<DialogResult<()>> {
|
||||
let Self { open, files, form } = self;
|
||||
let shown = Dialog::new(tl!("JavaScript Files"))
|
||||
@@ -418,4 +422,19 @@ mod tests {
|
||||
fixture.click(&add);
|
||||
assert_eq!(form.borrow().pending, Some(Pending::Add));
|
||||
}
|
||||
|
||||
/// `ui.javascriptFilesDialog` opens the dialog whose `key` its params text names, as `ui.inspect` lists it.
|
||||
#[test]
|
||||
fn params_text_names_the_dialog_key_ui_inspect_lists() {
|
||||
const COMMAND: &str = "ui.javascriptFilesDialog";
|
||||
let doc = crate::menus::UI_COMMANDS.iter().find(|c| c.0 == COMMAND).expect("registered").3;
|
||||
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default()));
|
||||
app.run("file.new", json!({"width": 100, "height": 100})).unwrap();
|
||||
app.run(COMMAND, json!({})).unwrap();
|
||||
let ctx = app.ui_ctx.clone().unwrap();
|
||||
let ui = crate::control::inspect(&app, &ctx);
|
||||
let key = ui["dialogs"].as_array().and_then(|d| d.last()).and_then(|d| d["key"].as_str()).expect("a dialog with a key");
|
||||
assert_eq!(key, KEY);
|
||||
assert!(doc.contains(&format!("dialog `{key}`")), "{COMMAND} opens `{key}`, which its params text does not name");
|
||||
}
|
||||
}
|
||||
@@ -21,10 +21,14 @@ use serde_json::{Map, Value, json};
|
||||
use vectorcraft_doc::{Background, ColorMode, Unit};
|
||||
use vectorcraft_engine::cmd::newdoc::{self, ArtboardLayout, DocSettings, MAX_ARTBOARDS, PreviewMode, ProfileFile, RASTER_PPI};
|
||||
|
||||
use craft::behavior::{ColumnWidth, IconId};
|
||||
use craft::behavior::{ColumnWidth, CursorIcon, IconId, Input, Metrics, PartKey, Sense};
|
||||
use craft::theme::Srgba;
|
||||
use craft::ui::buttons::Button;
|
||||
use craft::ui::choice::{Checkbox, Segmented};
|
||||
use craft::ui::contract::{Bind, Entry, FieldLayout, Gap, Props as _, Show as _, ShowContainer as _, SideLabel, Sizing, clicked};
|
||||
use craft::ui::choice::{Checkbox, Segmented, SwatchMetrics};
|
||||
use craft::ui::contract::{
|
||||
Access, Bind, Common, Component, Cx, Entry, FieldLayout, Gap, MeasureCx, PaintUi, PartsCx, Props as _, Role, Show as _, ShowContainer as _,
|
||||
SideLabel, Sizing, clicked,
|
||||
};
|
||||
use craft::ui::display::{Shade, Text};
|
||||
use craft::ui::form::Field;
|
||||
use craft::ui::layout::CellAlign;
|
||||
@@ -35,10 +39,12 @@ use craft::ui::patterns::form_dialogs::{
|
||||
use craft::ui::patterns::presets::{GroupPath, NamedPresetEvent, PresetLibrary};
|
||||
use craft::ui::pickers::Select;
|
||||
use craft::ui::popover::Popover;
|
||||
use craft::ui::primitives::{PaintShape, StrokeWidth};
|
||||
use craft::ui::runtime::env::{Env, Label, LengthUnits, UnitKind, WordRows};
|
||||
use craft::ui::sections::Section;
|
||||
use craft::ui::style::TypeRole;
|
||||
use craft::ui::style::{ComponentStyle, DataColor, StyleColor, StyleCx, TypeRole};
|
||||
use craft::ui::text::{LinkMode, LinkedWords, NumberField, follow_equal, link_toggle};
|
||||
use egui::{Color32, Rect, Response, Vec2};
|
||||
|
||||
use super::host::open_held;
|
||||
use crate::VectorcraftApp;
|
||||
@@ -356,12 +362,16 @@ impl DocumentSettings for VcNewDocument {
|
||||
let bleed = text(tl!("Bleed"));
|
||||
Field::new(bleed.clone()).layout(FieldLayout::Above).id_salt("bleed").show(ui, |ui, _| bleed_row(ui, s, &mut memory, lengths, compact));
|
||||
|
||||
// The list with a chip after it: white, or No Color's slash for transparent.
|
||||
Field::new(background.clone()).layout(FieldLayout::Above).id_salt("background").show(ui, |ui, _| {
|
||||
let entries: Vec<Entry<Background>> = BACKGROUNDS.iter().map(|(b, name)| Entry::new(*b, text(tl!(name)))).collect();
|
||||
let select = Select::new(background.clone(), Bind::given(s.background), &entries).sizing(Sizing::FillWidth);
|
||||
if let Some(b) = select.show(ui).events.committed().copied() {
|
||||
s.background = b;
|
||||
}
|
||||
Row::new().show(ui, |ui, _| {
|
||||
let entries: Vec<Entry<Background>> = BACKGROUNDS.iter().map(|(b, name)| Entry::new(*b, text(tl!(name)))).collect();
|
||||
let select = Select::new(background.clone(), Bind::given(s.background), &entries).sizing(Sizing::FillWidth);
|
||||
if let Some(b) = select.show(ui).events.committed().copied() {
|
||||
s.background = b;
|
||||
}
|
||||
background_chip(ui, s.background);
|
||||
});
|
||||
});
|
||||
|
||||
Section::new(text(tl!("Advanced Options"))).initially_open(false).show(ui, |ui, _| advanced(ui, s));
|
||||
@@ -420,6 +430,127 @@ fn built_in_card(preset: &DocSettings, values: &VcNewDocument, orientation: Opti
|
||||
DocumentCard::new(text(preset_name(&preset.name)), line, value, CardSource::preset(None))
|
||||
}
|
||||
|
||||
/// The chip after Background Contents: the paper white, or No Color for transparent. It shows the choice and opens
|
||||
/// nothing. It is display-only: it is not a Tab stop, offers no click and draws in full color.
|
||||
fn background_chip(ui: &mut egui::Ui, background: Background) {
|
||||
let name = crate::i18n::fmt(tl!("{row} swatch"), &[("row", tl!("Background Contents"))]);
|
||||
BackgroundChip::new(name, background).show(ui);
|
||||
}
|
||||
|
||||
// TEMPORARY: craft-libs on the pinned rev has no display-only PaintChip, so this chip draws the swatch-size well
|
||||
// itself. Replace it with `PaintChip::chip_size(PaintChipSize::Swatch).display_only()` once storytold/craft-libs#4953
|
||||
// merges and the pin moves past it.
|
||||
|
||||
/// The No Color diagonal stops this many well heights short of the chip's edges, as PaintChip's does.
|
||||
const NO_COLOR_INSET: f32 = 0.15;
|
||||
/// A one-column rail's cell holds this many swatch chips to a row, as PaintChip's swatch size does.
|
||||
const SWATCHES_PER_RAIL_BUTTON: f32 = 3.0;
|
||||
/// The chip's well, which keeps the arrow cursor: the chip opens nothing.
|
||||
const BACKGROUND_WELL: PartKey = PartKey::new("well");
|
||||
|
||||
/// The style of a [`BackgroundChip`].
|
||||
#[derive(Clone, Debug, PartialEq, ComponentStyle)]
|
||||
pub(crate) struct BackgroundChipStyle {
|
||||
#[style(metrics)]
|
||||
metrics: Metrics,
|
||||
/// The well's side.
|
||||
side: f32,
|
||||
/// The well's corners.
|
||||
radius: egui::CornerRadius,
|
||||
/// The ring on the well's outline.
|
||||
edge: StyleColor,
|
||||
/// The fill of No Color.
|
||||
none_fill: StyleColor,
|
||||
/// The No Color diagonal.
|
||||
none_mark: StyleColor,
|
||||
}
|
||||
|
||||
/// A swatch-size color well that shows the Background Contents choice: white, or No Color for transparent.
|
||||
///
|
||||
/// - Pointer and keys: none; it is not a Tab stop and draws as an enabled chip.
|
||||
/// - AccessKit: a color well named by the label, its value the hex or "No Color".
|
||||
#[derive(craft::ui::contract::Component, craft::ui::contract::Props)]
|
||||
#[component(sample = background_chip_sample)]
|
||||
pub(crate) struct BackgroundChip {
|
||||
#[common]
|
||||
common: Common,
|
||||
background: Background,
|
||||
}
|
||||
|
||||
impl BackgroundChip {
|
||||
/// A chip named `label` that shows `background`.
|
||||
fn new(label: impl Into<Label>, background: Background) -> Self {
|
||||
BackgroundChip { common: Common::new(), background }.label(label).read_only(true)
|
||||
}
|
||||
}
|
||||
|
||||
/// A white chip, for the suite.
|
||||
fn background_chip_sample() -> BackgroundChip {
|
||||
BackgroundChip::new("Background Contents swatch", Background::White)
|
||||
}
|
||||
|
||||
impl Component for BackgroundChip {
|
||||
const ROLE: Role = Role::COLOR_WELL;
|
||||
const STOPS: bool = false;
|
||||
const INPUT: Input = Input::Display;
|
||||
const SHOWS_LABEL: bool = false;
|
||||
const OVERLAYS: bool = false;
|
||||
type Style = BackgroundChipStyle;
|
||||
type Output = Response;
|
||||
|
||||
fn style(cx: &StyleCx<'_>, _: BackgroundChipStyleKey) -> BackgroundChipStyle {
|
||||
let colors = &cx.tokens.color;
|
||||
let gap = cx.tokens.space.gap.tight;
|
||||
BackgroundChipStyle {
|
||||
metrics: Metrics::new(),
|
||||
side: ((cx.tokens.size.rail.button - (SWATCHES_PER_RAIL_BUTTON * gap)) / SWATCHES_PER_RAIL_BUTTON).max(1.0),
|
||||
radius: SwatchMetrics::of(cx).radius,
|
||||
edge: cx.color(colors.line.control_edge),
|
||||
none_fill: cx.color(colors.surface.sunken),
|
||||
none_mark: cx.color(colors.status.bad.solid),
|
||||
}
|
||||
}
|
||||
|
||||
fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 {
|
||||
Vec2::splat(cx.style.side)
|
||||
}
|
||||
|
||||
fn sense(&self) -> Sense {
|
||||
Sense::empty()
|
||||
}
|
||||
|
||||
fn parts(&mut self, rect: Rect, cx: &mut PartsCx<'_, Self>) {
|
||||
let _ = cx.part(BACKGROUND_WELL, rect).cursor(CursorIcon::Default);
|
||||
}
|
||||
|
||||
fn access(&self, access: &mut Access, _: &Cx<'_, Self>) {
|
||||
access.value(match self.background {
|
||||
Background::White => Srgba::WHITE.to_hex(),
|
||||
Background::Transparent => tl!("No Color").to_owned(),
|
||||
});
|
||||
}
|
||||
|
||||
fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) {
|
||||
let well = Rect::from_center_size(cx.rect.center(), Vec2::splat(cx.style.side));
|
||||
let shape = PaintShape::Rect(well, cx.style.radius);
|
||||
match self.background {
|
||||
Background::White => ui.draw().data_fill(&shape, DataColor::new(Color32::WHITE)),
|
||||
Background::Transparent => {
|
||||
let draw = ui.draw();
|
||||
draw.fill(&shape, cx.style.none_fill);
|
||||
let inner = well.shrink(cx.style.side * NO_COLOR_INSET);
|
||||
let (from, to) = if cx.flow.is_rtl() { (inner.right_bottom(), inner.left_top()) } else { (inner.left_bottom(), inner.right_top()) };
|
||||
draw.stroke(&PaintShape::Path(vec![from, to]), StrokeWidth::Medium, cx.style.none_mark);
|
||||
}
|
||||
}
|
||||
ui.draw().stroke(&shape, StrokeWidth::Thin, cx.style.edge);
|
||||
}
|
||||
|
||||
fn finish(self, cx: Cx<'_, Self>) -> Response {
|
||||
cx.response.clone()
|
||||
}
|
||||
}
|
||||
|
||||
/// A label with the text `s`, already translated.
|
||||
fn text(s: &str) -> Label {
|
||||
Label::from(s.to_owned())
|
||||
@@ -1135,6 +1266,22 @@ mod tests {
|
||||
})
|
||||
}
|
||||
|
||||
/// The dialog reads rows as `file.new` does: a whole number from 1 to the artboard limit,
|
||||
/// `4.0` included, and a fractional, zero or larger count is refused with nothing changed.
|
||||
#[test]
|
||||
fn the_dialog_reads_rows_as_file_new_does() {
|
||||
let mut app = app();
|
||||
open(&mut app);
|
||||
set(&app, "artboards", json!(5)).unwrap();
|
||||
set(&app, "artboardLayout", json!({"layout": "gridByColumn", "rows": 4.0})).unwrap();
|
||||
assert_eq!(fields(&app)["artboardLayout"]["rows"], json!(4));
|
||||
for rows in [json!(3.5), json!(0.4), json!(MAX_ARTBOARDS + 1), json!(0)] {
|
||||
let e = set(&app, "artboardLayout", json!({"layout": "gridByColumn", "rows": rows})).unwrap_err();
|
||||
assert!(e.contains("can't take"), "{rows}: {e}");
|
||||
assert_eq!(fields(&app)["artboardLayout"]["rows"], json!(4), "{rows}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Press Create: the dialog files its answer and the pump runs `file.new` with it.
|
||||
fn create(app: &mut VectorcraftApp) {
|
||||
let ctx = ctx(app);
|
||||
@@ -1796,6 +1943,44 @@ mod tests {
|
||||
assert!(sides[3].x1 <= link.x0, "the link button {link:?} ends the Bleed row {sides:?}");
|
||||
}
|
||||
|
||||
/// A chip follows Background Contents in its row: No Color while the list says Transparent, white once it says
|
||||
/// White. Before, the list stood alone.
|
||||
#[test]
|
||||
fn new_document_background_contents_shows_its_chip() {
|
||||
use egui::accesskit::{Action, Role};
|
||||
let chip_name = "Background Contents swatch";
|
||||
let mut app = app();
|
||||
open(&mut app);
|
||||
let look = |app: &mut VectorcraftApp| {
|
||||
let out = laid_out_in(app, egui::vec2(1280.0, 900.0));
|
||||
let nodes = out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default();
|
||||
let find = |name: &str, role: Role| {
|
||||
nodes
|
||||
.iter()
|
||||
.find(|(_, n)| n.role() == role && n.label() == Some(name))
|
||||
.map(|(_, n)| (n.bounds().expect("laid out"), n.value().map(str::to_owned)))
|
||||
.unwrap_or_else(|| panic!("no {role:?} {name}"))
|
||||
};
|
||||
let (list, _) = find("Background Contents", Role::ComboBox);
|
||||
let (chip, value) = find(chip_name, Role::ColorWell);
|
||||
let node = nodes.iter().find(|(_, n)| n.role() == Role::ColorWell && n.label() == Some(chip_name)).map(|(_, n)| n).expect("the chip");
|
||||
assert!(!node.supports_action(Action::Click), "the chip opens nothing, so it offers no click");
|
||||
assert!(!node.supports_action(Action::Focus), "the chip is not a Tab stop");
|
||||
assert!(!node.is_disabled(), "the chip is not disabled, so it draws in full color");
|
||||
assert!(node.is_read_only(), "the chip shows the choice; the list changes it");
|
||||
let dialog = nodes.iter().find(|(_, n)| n.role() == Role::Dialog).and_then(|(_, n)| n.bounds()).expect("the dialog");
|
||||
assert!(list.x1 <= chip.x0, "the chip {chip:?} follows the list {list:?}");
|
||||
assert!(chip.y0 < list.y1 && list.y0 < chip.y1, "the chip {chip:?} shares the list's row {list:?}");
|
||||
assert!(chip.x1 <= dialog.x1, "the chip {chip:?} ends inside the dialog {dialog:?}");
|
||||
value.expect("the chip names its paint")
|
||||
};
|
||||
let transparent = look(&mut app);
|
||||
set(&app, "backgroundContents", json!("white")).unwrap();
|
||||
let white = look(&mut app);
|
||||
assert_eq!(transparent, "No Color", "Transparent shows No Color");
|
||||
assert_ne!(white, transparent, "White shows a color, not No Color");
|
||||
}
|
||||
|
||||
/// Turning the Bleed link on sets every side to Top's bleed; unlinking keeps the four values.
|
||||
#[test]
|
||||
fn new_document_bleed_link_turned_on_sets_every_side_to_top() {
|
||||
|
||||
@@ -2132,6 +2132,10 @@ impl StackDialog for RecolorDialog {
|
||||
self.id
|
||||
}
|
||||
|
||||
fn key(&self) -> Option<&str> {
|
||||
Some(KIND)
|
||||
}
|
||||
|
||||
fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option<DialogResult<Fields>> {
|
||||
self.shown(ui)
|
||||
}
|
||||
@@ -6374,4 +6378,21 @@ mod tests {
|
||||
rc.settled();
|
||||
assert!(rc.by_label(tl!("Color Groups")).is_none(), "and hides with `groupStorage`");
|
||||
}
|
||||
|
||||
/// `ui.recolorDialog` opens the dialog whose `key` its params text names, as `ui.inspect` lists it.
|
||||
#[test]
|
||||
fn params_text_names_the_dialog_key_ui_inspect_lists() {
|
||||
const COMMAND: &str = "ui.recolorDialog";
|
||||
let doc = crate::menus::UI_COMMANDS.iter().find(|c| c.0 == COMMAND).expect("registered").3;
|
||||
let mut app = app(120);
|
||||
let red = square(&mut app, 10.0, "#ff0000");
|
||||
app.run("select.set", json!({"ids": [red]})).unwrap();
|
||||
let rc = opened(app, json!({}));
|
||||
let app = rc.app();
|
||||
let ctx = app.ui_ctx.clone().unwrap();
|
||||
let ui = crate::control::inspect(&app, &ctx);
|
||||
let key = ui["dialogs"].as_array().and_then(|d| d.last()).and_then(|d| d["key"].as_str()).expect("a dialog with a key");
|
||||
assert_eq!(key, KIND);
|
||||
assert!(doc.contains(&format!("dialog `{key}`")), "{COMMAND} opens `{key}`, which its params text does not name");
|
||||
}
|
||||
}
|
||||
@@ -1700,6 +1700,36 @@ fn every_number_and_length_field_is_named() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Opens the dialog of `command` and checks its params text against the last dialog `ui.inspect` lists: the text says
|
||||
/// the dialog's key is null, and names `fields`, each of which the dialog lists.
|
||||
fn assert_params_text_matches_ui_inspect(command: &str, fields: &[&str]) {
|
||||
let doc = crate::menus::UI_COMMANDS.iter().find(|c| c.0 == command).expect("registered").3;
|
||||
let (mut app, _) = app();
|
||||
app.run(command, json!({})).unwrap();
|
||||
pump(&mut app);
|
||||
let ui = crate::control::inspect(&app, &ctx(&app));
|
||||
let entry = ui["dialogs"].as_array().and_then(|d| d.last()).cloned().expect("a dialog");
|
||||
assert_eq!(entry.get("key"), Some(&Value::Null), "{command}: {entry}");
|
||||
assert!(doc.contains("with key null"), "{command} opens a dialog with key null, which its params text does not say");
|
||||
for field in fields {
|
||||
assert!(entry["fields"].get(field).is_some(), "{command}: ui.inspect does not list `{field}`");
|
||||
assert!(doc.contains(&format!("`{field}`")), "{command}: its params text does not name `{field}`");
|
||||
}
|
||||
}
|
||||
|
||||
/// `file.print` opens the Print dialog, which `ui.inspect` lists with key null and the fields its params text names.
|
||||
#[test]
|
||||
fn print_params_text_matches_what_ui_inspect_lists() {
|
||||
assert_params_text_matches_ui_inspect("file.print", &["preset", "printer", "section", "sheet"]);
|
||||
}
|
||||
|
||||
/// `ui.printPresetDialog` opens the preset editor, which `ui.inspect` lists with key null and the fields its params
|
||||
/// text names.
|
||||
#[test]
|
||||
fn preset_editor_params_text_matches_what_ui_inspect_lists() {
|
||||
assert_params_text_matches_ui_inspect("ui.printPresetDialog", &["name"]);
|
||||
}
|
||||
|
||||
/// Leaving an ink's Frequency or Angle on text that is not a number cancels the typing, and the ink goes back to the
|
||||
/// value it had before it.
|
||||
#[test]
|
||||
|
||||
@@ -263,3 +263,20 @@ fn an_imported_shortcut_reaches_a_filter_plugin_picked_as_its_target() {
|
||||
vectorcraft_plugins::registry::remove(id);
|
||||
assert!(shortcut_editor::entries().iter().all(|e| e.key != key), "a removed filter is no target");
|
||||
}
|
||||
|
||||
/// `ui.shortcutImportDialog` shows its review inside Keyboard Shortcuts, which `ui.inspect` does not list in `dialogs`,
|
||||
/// so its params text names no dialog key.
|
||||
#[test]
|
||||
fn params_text_names_no_dialog_key_for_the_review() {
|
||||
const COMMAND: &str = "ui.shortcutImportDialog";
|
||||
let doc = crate::menus::UI_COMMANDS.iter().find(|c| c.0 == COMMAND).expect("registered").3;
|
||||
let mut app = crate::testing::windowed(app());
|
||||
let b64 = vectorcraft_format::base64_encode(SET.as_bytes());
|
||||
let r = app.run(COMMAND, json!({"dataBase64": b64, "name": "Sent.kys"})).unwrap();
|
||||
assert!(r["entries"].is_u64() && r["unread"].is_u64(), "{r}");
|
||||
assert!(app.shortcuts_dialog.as_ref().is_some_and(|d| d.pending_review.is_some()), "the review waits in Keyboard Shortcuts");
|
||||
let ctx = app.ui_ctx.clone().unwrap();
|
||||
let ui = crate::control::inspect(&app, &ctx);
|
||||
assert_eq!(ui["dialogs"], json!([]), "{COMMAND} opens no dialog that ui.inspect lists");
|
||||
assert!(!doc.contains("dialog `"), "the params text of {COMMAND} names a dialog key that ui.inspect does not list");
|
||||
}
|
||||
@@ -175,6 +175,43 @@ fn the_document_filter_on_an_empty_document_or_none() {
|
||||
assert!(used(&mut app).is_empty());
|
||||
}
|
||||
|
||||
/// The font list draws each family's sample in its own face, and egui hints text by default, so a TrueType face
|
||||
/// without hinting instructions goes through the automatic hinter. A Hebrew letter in such a face that is a bar 20
|
||||
/// by 700 thousandths of an em lays out. The layout runs on a thread of its own, and the test fails when it has not
|
||||
/// ended after 300 s.
|
||||
#[test]
|
||||
fn a_face_without_hinting_instructions_lays_out_a_tall_hebrew_letter() {
|
||||
use egui::epaint::text::{FontData, FontDefinitions, FontFamily, FontId, FontTweak, Fonts, TextOptions};
|
||||
use vectorcraft_text::{FileFontInfo, FileGlyph, build_file_font};
|
||||
|
||||
let mut glyph = FileGlyph { ch: '\u{5d1}', outline: Default::default(), advance: 300.0 };
|
||||
glyph.outline.move_to((0.0, 0.0));
|
||||
glyph.outline.line_to((0.0, 700.0));
|
||||
glyph.outline.line_to((20.0, 700.0));
|
||||
glyph.outline.line_to((20.0, 0.0));
|
||||
glyph.outline.close_path();
|
||||
let info = FileFontInfo { family: "Unhinted Bar".into(), style: "Regular".into(), ..Default::default() };
|
||||
let bytes = build_file_font(&info, &[glyph]).unwrap();
|
||||
let family = FontFamily::Name("Unhinted Bar".into());
|
||||
let mut definitions = FontDefinitions::empty();
|
||||
definitions.font_data.insert("Unhinted Bar".into(), Arc::new(FontData::from_owned(bytes).tweak(FontTweak::default())));
|
||||
definitions.families.insert(family.clone(), vec!["Unhinted Bar".into()]);
|
||||
let options = TextOptions::default();
|
||||
assert!(options.font_hinting, "egui hints text by default");
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
std::thread::spawn(move || {
|
||||
let mut fonts = Fonts::new(options, definitions);
|
||||
let mut view = fonts.with_pixels_per_point(1.0);
|
||||
let font_id = FontId::new(14.0, family);
|
||||
let in_face = view.has_glyph(&font_id, '\u{5d1}');
|
||||
let galley = view.layout_no_wrap("\u{5d1}".into(), font_id, egui::Color32::BLACK);
|
||||
tx.send((in_face, galley.size())).ok()
|
||||
});
|
||||
let (in_face, size) = rx.recv_timeout(std::time::Duration::from_secs(300)).unwrap_or_else(|e| panic!("laying out U+05D1: {e}"));
|
||||
assert!(in_face, "the face maps U+05D1");
|
||||
assert!(size.x > 0.0, "the letter is laid out with its advance: {size:?}");
|
||||
}
|
||||
|
||||
/// A fixed time the Recently Added tests count from.
|
||||
fn clock() -> SystemTime {
|
||||
SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(1_800_000_000)
|
||||
|
||||
@@ -127,13 +127,14 @@ impl VectorcraftApp {
|
||||
/// after losing its graphics), everything uploaded to the old one is made again: the fonts and
|
||||
/// theme, the canvas, the place cursor's thumbnails and every [`TexCache`]. The host hands it
|
||||
/// the window's context when it creates the app, so the first frame's input has the app's
|
||||
/// commands.
|
||||
/// commands. Each new context draws its text without hinting ([`crate::ui_fonts::hinting_off`]).
|
||||
pub fn adopt_context(&mut self, ctx: &egui::Context) {
|
||||
let tag = context_tag(ctx);
|
||||
self.ui_ctx = Some(ctx.clone());
|
||||
if self.context == tag {
|
||||
return;
|
||||
}
|
||||
crate::ui_fonts::hinting_off(ctx);
|
||||
if self.context != 0 {
|
||||
log::info!("vectorcraft: new graphics context: uploading the UI again");
|
||||
forget_textures();
|
||||
@@ -158,16 +159,16 @@ thread_local! {
|
||||
pub(crate) fn doc_image(size_px: [usize; 2], build: impl FnOnce(f64, f64) -> Option<vectorcraft_doc::Document>) -> Option<egui::ColorImage> {
|
||||
let (w, h) = (size_px[0] as f64, size_px[1] as f64);
|
||||
let doc = build(w, h)?;
|
||||
let img = RENDERER.with(|r| r.borrow_mut().render_region(&doc, vectorcraft_geom::Rect::new(0.0, 0.0, w, h), 1.0, false));
|
||||
Some(crate::canvas::color_image(&img))
|
||||
let img = RENDERER.with(|r| r.borrow_mut().render_region_words(&doc, vectorcraft_geom::Rect::new(0.0, 0.0, w, h), 1.0, false));
|
||||
Some(crate::canvas::color_image_owned(img))
|
||||
}
|
||||
|
||||
/// `region` of `doc` rendered on white, its longest side `px` pixels (artboard and page
|
||||
/// thumbnails).
|
||||
pub(crate) fn region_image(doc: &vectorcraft_doc::Document, region: vectorcraft_geom::Rect, px: u32) -> egui::ColorImage {
|
||||
let scale = f64::from(px) / region.width().max(region.height()).max(1.0);
|
||||
let img = RENDERER.with(|r| r.borrow_mut().render_region(doc, region, scale, true));
|
||||
crate::canvas::color_image(&img)
|
||||
let img = RENDERER.with(|r| r.borrow_mut().render_region_words(doc, region, scale, true));
|
||||
crate::canvas::color_image_owned(img)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -186,6 +186,12 @@ pub(crate) fn shown_state_with(
|
||||
why_off: &mut dyn FnMut(&str) -> Option<Option<String>>,
|
||||
) -> Option<(bool, Option<bool>)> {
|
||||
let en = why_off(id).is_none()
|
||||
&& (id != "ui.menuDialog"
|
||||
|| if p.get("command").and_then(Value::as_str) == Some("addon.arrange.artboardGuides") {
|
||||
why_off("addon.arrange.artboardGuides").is_none()
|
||||
} else {
|
||||
app.session.active().is_some_and(|d| !d.selection.is_empty())
|
||||
})
|
||||
&& (id != crate::addons::select::link_status::COMMAND || crate::addons::select::link_status::enabled(app, p))
|
||||
&& (!vectorcraft_engine::cmd::plugin::is_command_id(id) || crate::dialogs::plugin::canvas_item_enabled(app, id, p));
|
||||
if (!en && hidden_when_disabled(id)) || swapped_out(id, why_off) || east_asian_hidden(app, id) {
|
||||
@@ -416,7 +422,7 @@ fn ui_enabled(app: &VectorcraftApp, id: &str) -> bool {
|
||||
"ui.saveBrushLibrary" => crate::panels::brushes::has_brushes(app),
|
||||
id if id.starts_with(crate::panels::brushes::USER_SLOT) => crate::panels::brushes::user_library(app, id).is_some(),
|
||||
"ui.spotColors" => app.session.active().is_some(),
|
||||
"ui.menuDialog" => app.session.active().is_some_and(|d| !d.selection.is_empty()),
|
||||
"ui.menuDialog" => app.session.active().is_some_and(|d| !d.selection.is_empty() || !d.doc.artboards.is_empty()),
|
||||
"ui.simplifyAuto" | "ui.simplifyMoreOptions" => crate::dialogs::simplify_slider::showing(app),
|
||||
"ui.smoothAuto" => crate::dialogs::smooth_slider::showing(app),
|
||||
"ui.recolorUndo" => crate::dialogs::recolor::can_step(app, true),
|
||||
|
||||
@@ -224,7 +224,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"ui.shortcutImportDialog",
|
||||
"Import Shortcut Set…",
|
||||
"",
|
||||
"{path? | dataBase64?, name?} open Import Shortcut Set for a shortcut set another app saved as text (.kys; without a file, pick one): each entry matched to a tool, command or panel, and its key and modifier codes decoded (dialog `shortcutImport`: name, start: defaults|current, remember, rows: [{name, section, line, key, modifiers, target: entry id | \"\" (no equivalent) | null (not chosen), from, choices, on}], keys and mods: {code: {text, from, votes, names}}); Apply assigns the ready rows over Edit › Keyboard Shortcuts' working set, remembers the matches (importMatches.set) and shows Keyboard Shortcuts, whose OK keeps them. File › Open of a .kys opens it too",
|
||||
"{path? | dataBase64?, name?} open Import Shortcut Set for a shortcut set another app saved as text (.kys; without a file, pick one): each entry matched to a tool, command or panel, and its key and modifier codes decoded. The review opens inside Edit › Keyboard Shortcuts, which ui.inspect does not list in `dialogs` and ui.dialog.set does not reach; with a file the reply is {entries, unread}. Without the window, shortcutSet.read reads a file and matches its entries, and importMatches.set stores matches. Apply assigns the ready rows over Edit › Keyboard Shortcuts' working set, remembers the matches (importMatches.set) and shows Keyboard Shortcuts, whose OK keeps them. File › Open of a .kys opens it too",
|
||||
),
|
||||
("view.outline", "Outline", "Cmd+Y", "{} toggle Outline/Preview"),
|
||||
("view.pixelPreview", "Pixel Preview", "Cmd+Alt+Y", "{}"),
|
||||
@@ -1031,7 +1031,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"ui.paramDialog",
|
||||
"Command Dialog",
|
||||
"",
|
||||
"{command, label?, params?} open a parameter dialog for any command. A missing, empty, non-string or unknown command, a label that is neither a string nor null, or params that are neither an object nor null is an error, and no dialog opens. A null label or params is treated as omitted. A plug-in command that is not installed yet waits for the plug-ins still loading. For commands other than edit.findReplace, params.__doc may be an unsigned document uid: the dialog previews and confirms only while that document is active, and OK after a document switch closes it without running the command. An invalid __doc is an error; omitting it keeps the existing behavior. For edit.findReplace it opens Find and Replace (dialog `findReplace`), which stays open: fields find, replace, matchCase, wholeWord, backwards, hiddenLayers, lockedLayers, and action, which ui.dialog.confirm runs: find (the next match, edit.findNext, shown in the dialog with its place among the matches), replace (the match found, edit.replaceMatch), replaceFind (both), replaceAll (edit.findReplace) or done (close). An action whose button the open tab does not show is refused: find runs on the Find and Replace tabs, replace, replaceFind and replaceAll on the Replace tab, done on every tab. After each one action is find again. Replace and Replace & Find change a match that find reached with the find text and options as they are now, and find one otherwise. The dialog opens on the last search, with the fields params gives in its place (a null field gives none; a field of the wrong type is an error, and ui.dialog.confirm then runs no action), and Edit › Find Next goes on from it in the same document while the dialog is closed",
|
||||
"{command, label?, params?} open a parameter dialog for any command. A missing, empty, non-string or unknown command, a label that is neither a string nor null, or params that are neither an object nor null is an error, and no dialog opens. A null label or params is treated as omitted. A plug-in command that is not installed yet waits for the plug-ins still loading. For commands other than edit.findReplace, params.__doc may be an unsigned document uid: the dialog previews and confirms only while that document is active, and OK after a document switch closes it without running the command. An invalid __doc is an error; omitting it keeps the existing behavior. For edit.findReplace it opens Find and Replace (listed last in ui.inspect's `dialogs`, with key null), which stays open: fields find, replace, matchCase, wholeWord, backwards, hiddenLayers, lockedLayers, and action (it also lists tab, more, goToKind, goToTarget and the read-only message), which ui.dialog.confirm runs: find (the next match, edit.findNext, shown in the dialog with its place among the matches), replace (the match found, edit.replaceMatch), replaceFind (both), replaceAll (edit.findReplace) or done (close). An action whose button the open tab does not show is refused: find runs on the Find and Replace tabs, replace, replaceFind and replaceAll on the Replace tab, done on every tab. After each one action is find again. Replace and Replace & Find change a match that find reached with the find text and options as they are now, and find one otherwise. The dialog opens on the last search, with the fields params gives in its place (a null field gives none; a field of the wrong type is an error, and ui.dialog.confirm then runs no action), and Edit › Find Next goes on from it in the same document while the dialog is closed",
|
||||
),
|
||||
(
|
||||
"ui.recolorDialog",
|
||||
@@ -1556,7 +1556,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.commonTangents|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.type.numbers|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.arrange.markBounds|addon.color.applyNearestSwatch|addon.color.randomFill|addon.select.byArtboards|addon.select.editPointsOnly|addon.document.floodFillArtboards|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; addon.document.floodFillArtboards is refused, with the command's reason, while that command is disabled (for example with no document open); 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.type.numbers|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.arrange.artboardGuides|addon.arrange.markBounds|addon.color.applyNearestSwatch|addon.color.randomFill|addon.select.byArtboards|addon.select.editPointsOnly|addon.document.floodFillArtboards|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`); addon.arrange.artboardGuides fails when the document has no artboards; 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; addon.document.floodFillArtboards is refused, with the command's reason, while that command is disabled (for example with no document open); 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",
|
||||
@@ -2004,7 +2004,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"file.print",
|
||||
"Print…",
|
||||
"Cmd+P",
|
||||
"{} open the Print dialog (dialog `print`: the print.setup settings, preset (setting it loads that print preset; Save Preset… saves them as one), printer, toFile; on desktop, installed printers appear once the background lookup has returned and the dialog has applied the list; ui.dialog.set accepts a named printer once it appears in the list; PDF File is available at once; Print keeps the settings with the document and prints, Done (discard: true) only keeps them); with params {preset? (a print preset's name: its settings instead of the document's), settings? (over the document's or the preset's), printer? (print.printers name; \"\" the default), paper? (the printer driver's paper keyword, such as Letter or CR80: the queue is asked for that paper as the job's media on macOS and Linux; on Windows, with file output, with directPdf, or anything but a keyword it is an error; the Print dialog sends the driver's keyword for the Size chosen), toFile?, path?, format?: pdf|postscript, level?, flattenerPreset?, maxPages? (as engine file.print)} print without it: the print-ready PDF (engine file.print) goes to the printer → {pages, printer, printed: true, warnings}; with toFile, a path or no printing here (no print service) it is saved as a PDF at path (else a picked file, the web downloads it) → {path, pages, printed: false, warnings}; a PostScript file (format postscript, or a .ps path) is always saved that way; a job of more than maxPages pages is neither printed nor saved → {pages, format}",
|
||||
"{} open the Print dialog (listed last in ui.inspect's `dialogs`, with key null; fields: the print.setup settings, `preset` (setting it loads that print preset; Save Preset… saves them as one), `printer` (a print.printers name, or PDF File, with which Print saves the job as a PDF), `section` and `sheet`; on desktop, installed printers appear once the background lookup has returned and the dialog has applied the list; ui.dialog.set accepts a named printer once it appears in the list; PDF File is available at once; Print keeps the settings with the document and prints, Done (`choice`: done, then ui.dialog.confirm) only keeps them); with params {preset? (a print preset's name: its settings instead of the document's), settings? (over the document's or the preset's), printer? (print.printers name; \"\" the default), paper? (the printer driver's paper keyword, such as Letter or CR80: the queue is asked for that paper as the job's media on macOS and Linux; on Windows, with file output, with directPdf, or anything but a keyword it is an error; the Print dialog sends the driver's keyword for the Size chosen), toFile?, path?, format?: pdf|postscript, level?, flattenerPreset?, maxPages? (as engine file.print)} print without it: the print-ready PDF (engine file.print) goes to the printer → {pages, printer, printed: true, warnings}; with toFile, a path or no printing here (no print service) it is saved as a PDF at path (else a picked file, the web downloads it) → {path, pages, printed: false, warnings}; a PostScript file (format postscript, or a .ps path) is always saved that way; a job of more than maxPages pages is neither printed nor saved → {pages, format}",
|
||||
),
|
||||
(
|
||||
"print.printers",
|
||||
@@ -2023,7 +2023,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"ui.printPresetDialog",
|
||||
"Print Preset",
|
||||
"",
|
||||
"{name?: a saved preset to edit | preset?: the preset a new one starts from (default [Default])} open the preset editor (dialog `printPreset`: the Print dialog's settings fields plus `name`); OK runs print.presets.save and returns to Print Presets",
|
||||
"{name?: a saved preset to edit | preset?: the preset a new one starts from (default [Default])} open the preset editor (listed last in ui.inspect's `dialogs`, with key null; fields: the Print dialog's settings fields plus `name`); OK runs print.presets.save and returns to Print Presets",
|
||||
),
|
||||
(
|
||||
"plugin.dialog",
|
||||
@@ -2107,7 +2107,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"ui.checkScript",
|
||||
"Check Script…",
|
||||
"",
|
||||
"{path? | data? | dataBase64?, name?, includes?: true with a path} check a script written for the reference app without running it (script.check; with a path, the files its #include lines name are checked too) and show the report (dialog `scriptCheck`: `report`, script.check's result; Copy Report copies it as JSON); without a file pick one (the web opens the browser's file picker; File › Open of a .jsx, .jsxinc or .jsxbin file shows the report too)",
|
||||
"{path? | data? | dataBase64?, name?, includes?: true with a path} check a script written for the reference app without running it (script.check; with a path, the files its #include lines name are checked too) and show the report (listed last in ui.inspect's `dialogs`, with key null; fields `lines`, `notes` and `groups`); with a file the reply is script.check's result, and the report's Copy button copies the report as text; without a file pick one (the web opens the browser's file picker; File › Open of a .jsx, .jsxinc or .jsxbin file shows the report too)",
|
||||
),
|
||||
(
|
||||
"ui.perspectiveGridDialog",
|
||||
@@ -2235,6 +2235,11 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"",
|
||||
"{plane?: left|right|ground (default: the active plane)} open the plane's options, as double-clicking its plane widget does (dialog `perspectivePlane`: location (pt along the plane's normal), objects: none|move|copy): OK runs perspective.plane.move",
|
||||
),
|
||||
("ui.findAndReplace", "Find and Replace…", "", "{} open the Find and Replace dialog (Edit › Find and Replace…; dialog `findReplace`)"),
|
||||
(
|
||||
"ui.findAndReplace",
|
||||
"Find and Replace…",
|
||||
"",
|
||||
"{} open the Find and Replace dialog (Edit › Find and Replace…; listed last in ui.inspect's `dialogs`, with key null; fields and buttons as ui.paramDialog with edit.findReplace)",
|
||||
),
|
||||
("ui.retype", "Retype", "", "{} open the Retype panel (Window › Retype) or start Retype"),
|
||||
];
|
||||
@@ -54,6 +54,8 @@ pub mod transform;
|
||||
pub mod transparency;
|
||||
pub mod variables;
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::hash::{DefaultHasher, Hash, Hasher};
|
||||
use std::sync::Arc;
|
||||
|
||||
use craft::behavior::{IconId, Mixed};
|
||||
@@ -83,7 +85,7 @@ use craft::ui::text::{NumberField, link_toggle};
|
||||
use egui::Ui;
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::{BlendMode, Color, Paint};
|
||||
use vectorcraft_doc::{LiveCorners, Node, NodeId, NodeKind, StrokeLayer};
|
||||
use vectorcraft_doc::{LiveCorners, LiveShape, Node, NodeId, NodeKind, StrokeLayer};
|
||||
use vectorcraft_engine::inspect::StrokeMixed;
|
||||
use vectorcraft_geom::shapes::CornerKind;
|
||||
|
||||
@@ -124,6 +126,28 @@ pub(crate) fn corner_length(c: &LiveCorners, k: usize) -> f64 {
|
||||
if c.radii_relative() { c.radius(k) * c.corner(k).map_or(0.0, |c| c.max_radius()) } else { c.radius(k) }
|
||||
}
|
||||
|
||||
/// What a corner field edits, as its edit target: the active document's uid, how many times
|
||||
/// File › Revert and Undo or Redo replaced its content (after which a node id can name another
|
||||
/// object), the selected objects in id order, and `corners`, the corners the field sets (a picked
|
||||
/// corner as its [`CornerPlace`]). A field drops a value typed and not yet committed when this
|
||||
/// changes, even where the new corners have the same radius, and keeps it when the same objects
|
||||
/// are selected in another order. Rounding a corner replaces its anchors without changing the
|
||||
/// corner, so a scrub that rounds a Direct-Selected corner keeps its target. The Layers panel's
|
||||
/// target is not part of it.
|
||||
pub(crate) fn corner_target(app: &VectorcraftApp, corners: impl Hash) -> u64 {
|
||||
let mut hasher = DefaultHasher::new();
|
||||
app.session
|
||||
.active()
|
||||
.map(|st| {
|
||||
let mut objects = st.selection.objects.to_vec();
|
||||
objects.sort_unstable();
|
||||
(st.uid, st.reverts, st.history_restores, objects)
|
||||
})
|
||||
.hash(&mut hasher);
|
||||
corners.hash(&mut hasher);
|
||||
hasher.finish()
|
||||
}
|
||||
|
||||
/// One entry per corner kind, labelled as the Corners dialog labels them.
|
||||
pub(crate) fn corner_entries() -> Vec<Entry<CornerKind>> {
|
||||
CornerKind::ALL.iter().map(|k| Entry::new(*k, crate::dialogs::corners::kind_label(*k))).collect()
|
||||
@@ -227,6 +251,8 @@ fn rectangle_corners() -> [(usize, &'static str, &'static str); 4] {
|
||||
fn corner_fields(app: &mut VectorcraftApp, ui: &mut Ui, n: &Node) {
|
||||
let Some(lc) = LiveCorners::of(n) else { return };
|
||||
let lengths = general_lengths(app);
|
||||
let rectangles = selected_rectangles(app);
|
||||
let target = corner_target(app, rectangles);
|
||||
let entries = corner_entries();
|
||||
let mut radii = Vec::new();
|
||||
let mut kinds = Vec::new();
|
||||
@@ -242,7 +268,8 @@ fn corner_fields(app: &mut VectorcraftApp, ui: &mut Ui, n: &Node) {
|
||||
for (k, label, corner) in rectangle_corners() {
|
||||
Field::new(label).show(ui, |ui, _| {
|
||||
Row::new().wrap(true).show(ui, |ui, _| {
|
||||
radii.push((k, NumberField::length(label, Bind::given(Some(corner_length(&lc, k))), lengths).show(ui).edit));
|
||||
let field = NumberField::length(label, Bind::given(Some(corner_length(&lc, k))), lengths).edit_target(target);
|
||||
radii.push((k, field.show(ui).edit));
|
||||
if let Some(kind) = corner_select(ui, corner, Some(lc.kind(k)), &entries) {
|
||||
kinds.push((k, kind));
|
||||
}
|
||||
@@ -267,7 +294,9 @@ fn corner_fields(app: &mut VectorcraftApp, ui: &mut Ui, n: &Node) {
|
||||
|
||||
/// [`corner_radius_row`]'s field: [`corner_radius`], which a new value sets on those corners.
|
||||
pub(crate) fn corner_radius_field(app: &mut VectorcraftApp, ui: &mut Ui, n: &Node) {
|
||||
let edit = NumberField::length(tl!("Corner Radius"), Bind::given(corner_radius(app, n)), general_lengths(app)).show(ui).edit;
|
||||
let corners = radius_corners(app);
|
||||
let target = corner_target(app, corners);
|
||||
let edit = NumberField::length(tl!("Corner Radius"), Bind::given(corner_radius(app, n)), general_lengths(app)).edit_target(target).show(ui).edit;
|
||||
apply_edits(app, &edit, EditPath::Scope, |app, v: &Option<f64>, _| {
|
||||
if let Some(r) = v {
|
||||
app.run("object.setLiveShape", json!({"radius": r.max(0.0)})).ok();
|
||||
@@ -309,6 +338,8 @@ pub(crate) fn command_icon(id: &str, tools: crate::icons::ToolIcons) -> Option<&
|
||||
pub(crate) struct PickedCorners {
|
||||
/// `object.setLiveShape`'s `items`: `{id, corners}` for each path.
|
||||
pub items: Vec<Value>,
|
||||
/// The same corners as `items`: each path's id and its [`CornerPlace`]s.
|
||||
pub corners: Vec<(NodeId, Vec<CornerPlace>)>,
|
||||
/// The radius the corners share, as a document length; None when they differ.
|
||||
pub radius: Option<f64>,
|
||||
/// The kind the corners share; None when they differ.
|
||||
@@ -317,6 +348,100 @@ pub(crate) struct PickedCorners {
|
||||
pub relative: Option<bool>,
|
||||
}
|
||||
|
||||
/// A corner: its anchor index, counted across subpaths, and a hash of what the index is counted
|
||||
/// in. A live rectangle's, polygon's or star's corners keep their order, so the hash covers only
|
||||
/// their number, and moving, rotating or scaling the shape keeps it. On any other path the hash
|
||||
/// covers the corner's subpath of the unrounded path: its first anchor index, whether it is closed,
|
||||
/// and each anchor's position and handles relative to the subpath's first anchor, in millionths of
|
||||
/// a point. Moving the path, or changing another subpath without changing the subpath's first
|
||||
/// anchor index, keeps it. Reversing, rotating or scaling the subpath, or changing its anchors,
|
||||
/// changes it. Rounding a corner leaves the unrounded path as it is.
|
||||
pub(crate) type CornerPlace = (usize, u64);
|
||||
|
||||
/// Each corner of node `n`'s Live Corners `lc` as its [`CornerPlace`], hashing each subpath once.
|
||||
fn corner_places(n: &Node, lc: &LiveCorners, corners: &BTreeSet<usize>) -> Vec<CornerPlace> {
|
||||
if matches!(n.live_shape(), Some(LiveShape::Rectangle { .. } | LiveShape::Polygon { .. } | LiveShape::Star { .. })) {
|
||||
let mut hasher = DefaultHasher::new();
|
||||
lc.corners.len().hash(&mut hasher);
|
||||
let shape = hasher.finish();
|
||||
return corners.iter().map(|&k| (k, shape)).collect();
|
||||
}
|
||||
let mut places = Vec::with_capacity(corners.len());
|
||||
let mut first = 0;
|
||||
for subpath in &lc.base.subpaths {
|
||||
let end = first + subpath.anchors.len();
|
||||
let mut picked = corners.range(first..end).peekable();
|
||||
if picked.peek().is_some()
|
||||
&& let Some(origin) = subpath.anchors.first().map(|a| a.p)
|
||||
{
|
||||
let mut hasher = DefaultHasher::new();
|
||||
first.hash(&mut hasher);
|
||||
subpath.closed.hash(&mut hasher);
|
||||
subpath.anchors.len().hash(&mut hasher);
|
||||
for anchor in &subpath.anchors {
|
||||
for p in [anchor.p, anchor.h_in, anchor.h_out] {
|
||||
[((p.x - origin.x) * 1e6).round() as i64, ((p.y - origin.y) * 1e6).round() as i64].hash(&mut hasher);
|
||||
}
|
||||
}
|
||||
let shape = hasher.finish();
|
||||
places.extend(picked.map(|&k| (k, shape)));
|
||||
}
|
||||
first = end;
|
||||
}
|
||||
places
|
||||
}
|
||||
|
||||
/// The selected live rectangles, as one hash, for (document uid, File › Revert count, revision).
|
||||
fn selected_rectangles(app: &mut VectorcraftApp) -> u64 {
|
||||
let Some(st) = app.session.active() else { return 0 };
|
||||
let key = (st.uid, st.reverts, st.revision);
|
||||
if let Some((k, id)) = app.canvas.selected_rectangles
|
||||
&& k == key
|
||||
{
|
||||
return id;
|
||||
}
|
||||
// The live rectangles among the selected objects, the ones `set_rectangle_corners` sets.
|
||||
let mut hasher = DefaultHasher::new();
|
||||
let mut objects = st.selection.objects.to_vec();
|
||||
objects.sort_unstable();
|
||||
for id in objects {
|
||||
if st.doc.node(id).is_some_and(|n| matches!(n.live_shape(), Some(LiveShape::Rectangle { .. }))) {
|
||||
id.hash(&mut hasher);
|
||||
}
|
||||
}
|
||||
let rectangles = hasher.finish();
|
||||
app.canvas.selected_rectangles = Some((key, rectangles));
|
||||
rectangles
|
||||
}
|
||||
|
||||
/// The corners that `object.setLiveShape` with a `radius` and no `items` sets, as one hash: each
|
||||
/// selected object with Live Corners and its [`LiveCorners::picked`] corners. Measured once per
|
||||
/// (document uid, File › Revert count, revision): the panels read it every frame, and Select All
|
||||
/// can select hundreds of thousands of shapes.
|
||||
fn radius_corners(app: &mut VectorcraftApp) -> u64 {
|
||||
let Some(st) = app.session.active() else { return 0 };
|
||||
let key = (st.uid, st.reverts, st.revision);
|
||||
if let Some((k, id)) = app.canvas.radius_corners
|
||||
&& k == key
|
||||
{
|
||||
return id;
|
||||
}
|
||||
let mut hasher = DefaultHasher::new();
|
||||
let mut objects = st.selection.objects.to_vec();
|
||||
objects.sort_unstable();
|
||||
for id in objects {
|
||||
let Some(n) = st.doc.node(id) else { continue };
|
||||
let Some(lc) = LiveCorners::of(n) else { continue };
|
||||
let corners = lc.picked(st.selection.partial(id));
|
||||
if !corners.is_empty() {
|
||||
(id, corner_places(n, &lc, &corners)).hash(&mut hasher);
|
||||
}
|
||||
}
|
||||
let corners = hasher.finish();
|
||||
app.canvas.radius_corners = Some((key, corners));
|
||||
corners
|
||||
}
|
||||
|
||||
/// The picked corners of the selection: for each selected path with Live Corners, the corners
|
||||
/// holding a Direct-Selected anchor, or every corner of a path selected whole. A path whose
|
||||
/// selected anchors hold no corner adds none. None when no path adds a corner.
|
||||
@@ -326,9 +451,10 @@ pub(crate) fn picked_corners(app: &VectorcraftApp) -> Option<PickedCorners> {
|
||||
rest.iter().all(|v| same(*v, first)).then_some(first)
|
||||
}
|
||||
let st = app.session.active()?;
|
||||
let (mut items, mut radii, mut kinds, mut relative) = (Vec::new(), Vec::new(), Vec::new(), Vec::new());
|
||||
let (mut items, mut picked, mut radii, mut kinds, mut relative) = (Vec::new(), Vec::new(), Vec::new(), Vec::new(), Vec::new());
|
||||
for &id in &st.selection.objects {
|
||||
let Some(lc) = st.doc.node(id).and_then(LiveCorners::of) else { continue };
|
||||
let Some(n) = st.doc.node(id) else { continue };
|
||||
let Some(lc) = LiveCorners::of(n) else { continue };
|
||||
let corners = st.selection.partial(id).map_or_else(|| lc.all(), |anchors| lc.corners_of(anchors));
|
||||
if corners.is_empty() {
|
||||
continue;
|
||||
@@ -339,12 +465,15 @@ pub(crate) fn picked_corners(app: &VectorcraftApp) -> Option<PickedCorners> {
|
||||
}
|
||||
relative.push(lc.radii_relative());
|
||||
items.push(json!({"id": id, "corners": corners}));
|
||||
picked.push((id, corner_places(n, &lc, &corners)));
|
||||
}
|
||||
if items.is_empty() {
|
||||
return None;
|
||||
}
|
||||
picked.sort_unstable_by_key(|(id, _)| *id);
|
||||
Some(PickedCorners {
|
||||
items,
|
||||
corners: picked,
|
||||
radius: shared(&radii, |a, b| (a - b).abs() < 1e-9),
|
||||
kind: shared(&kinds, |a, b| a == b),
|
||||
relative: shared(&relative, |a, b| a == b),
|
||||
@@ -374,6 +503,7 @@ pub(crate) fn corners_link(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
fn corners_popup(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
let Some(picked) = picked_corners(app) else { return };
|
||||
let lengths = general_lengths(app);
|
||||
let target = corner_target(app, &picked.corners);
|
||||
let (mut set, mut radius) = (None, None);
|
||||
Stack::new().show(ui, |ui, _| {
|
||||
Field::new(tl!("Corner")).show(ui, |ui, _| {
|
||||
@@ -389,7 +519,7 @@ fn corners_popup(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
}
|
||||
});
|
||||
Field::new(tl!("Radius")).show(ui, |ui, _| {
|
||||
radius = Some(NumberField::length(tl!("Radius"), Bind::given(picked.radius), lengths).show(ui).edit);
|
||||
radius = Some(NumberField::length(tl!("Radius"), Bind::given(picked.radius), lengths).edit_target(target).show(ui).edit);
|
||||
});
|
||||
let rounding = RadioGroup::new(tl!("Rounding"), Bind::given(picked.relative)).show(ui, |ui, _| {
|
||||
Row::new().show(ui, |ui, _| {
|
||||
|
||||
@@ -24,7 +24,7 @@ use vectorcraft_doc::{ImageMap, NodeId, NodeKind};
|
||||
use vectorcraft_engine::cmd::{AttributesInfo, RECENT_URLS};
|
||||
use vectorcraft_geom::FillRule;
|
||||
|
||||
use super::{part_hidden, selection_len, set_part_hidden};
|
||||
use super::{part_hidden, selection_len, selection_target, set_part_hidden};
|
||||
use crate::VectorcraftApp;
|
||||
|
||||
/// The part store's key for the options (centre, direction, fill rule, image map, URL).
|
||||
@@ -116,17 +116,6 @@ fn info(app: &mut VectorcraftApp) -> (AttributesInfo, bool) {
|
||||
v
|
||||
}
|
||||
|
||||
/// What the URL and Note fields edit, as their edit target: the document, how many times File › Revert replaced its
|
||||
/// content, and the selected objects (or the object targeted in the Layers panel). A field drops an unfinished value
|
||||
/// when this changes, even where the new objects hold the same text.
|
||||
type EditTarget = Option<(u64, u64, Vec<NodeId>)>;
|
||||
|
||||
/// The [`EditTarget`] of the active document.
|
||||
fn edit_target(app: &VectorcraftApp) -> EditTarget {
|
||||
let st = app.session.active()?;
|
||||
Some((st.uid, st.reverts, st.selection.subjects().to_vec()))
|
||||
}
|
||||
|
||||
/// A value the targets share, or mixed where they differ (`None`).
|
||||
fn or_mixed<T>(v: Option<T>) -> Mixed<T> {
|
||||
v.map_or(Mixed::Mixed, Mixed::Same)
|
||||
@@ -150,7 +139,8 @@ fn pair<T: Valued>(ui: &mut Ui, name: &'static str, enabled: bool, current: Opti
|
||||
pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
let (info, paths) = info(app);
|
||||
let has = !info.ids.is_empty();
|
||||
let target = edit_target(app);
|
||||
// The URL and Note fields drop an unfinished value when the selection target changes.
|
||||
let target = selection_target(app);
|
||||
// (command, params) for each edit of this pass; errors show in the status bar through `run`.
|
||||
let mut acts: Vec<(&'static str, Value)> = Vec::new();
|
||||
Row::new().show(ui, |ui, _| {
|
||||
@@ -422,6 +412,96 @@ mod tests {
|
||||
assert_eq!(same(&url_and_note(&panel, a)), SAME, "the reverted object keeps the file's note");
|
||||
}
|
||||
|
||||
/// Undo drops an unfinished URL, though the object it takes away and the object made and selected after it have
|
||||
/// the same id and no URL: Enter leaves the new object without one.
|
||||
#[test]
|
||||
fn undo_drops_an_unfinished_url() {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
run(&mut app, "file.new", json!({"width": 100, "height": 100}));
|
||||
let a = run(&mut app, "shape.rectangle", json!({"x": 0, "y": 0, "width": 30, "height": 30}))["id"].as_u64().unwrap();
|
||||
run(&mut app, "select.set", json!({"ids": [a]}));
|
||||
let mut panel = Panel::new(app, show);
|
||||
panel.room(egui::vec2(320.0, 480.0));
|
||||
panel.frame();
|
||||
unfinished(&mut panel, "URL", "https://example.com/typed");
|
||||
run(&mut panel.app(), "edit.undo", json!({}));
|
||||
let b = run(&mut panel.app(), "shape.rectangle", json!({"x": 50, "y": 0, "width": 30, "height": 30}))["id"].as_u64().unwrap();
|
||||
assert_eq!(b, a, "the new rectangle has the undone rectangle's id");
|
||||
run(&mut panel.app(), "select.set", json!({"ids": [b]}));
|
||||
settle(&mut panel);
|
||||
panel.key(egui::Key::Enter, egui::Modifiers::NONE);
|
||||
assert_eq!(url_and_note(&panel, b).0.as_deref(), Some(""), "Enter leaves the new rectangle without a URL");
|
||||
}
|
||||
|
||||
/// Redo drops an unfinished note, though the object keeps its id and the step Redo restores leaves its note as it
|
||||
/// was: a click elsewhere leaves that note.
|
||||
#[test]
|
||||
fn redo_drops_an_unfinished_note() {
|
||||
let (mut app, a, _) = twins();
|
||||
run(&mut app, "attributes.set", json!({"ids": [a], "url": "https://example.com/redone"}));
|
||||
run(&mut app, "edit.undo", json!({}));
|
||||
run(&mut app, "select.set", json!({"ids": [a]}));
|
||||
let mut panel = Panel::new(app, show);
|
||||
panel.room(egui::vec2(320.0, 480.0));
|
||||
panel.frame();
|
||||
unfinished(&mut panel, "Note", "typed note");
|
||||
run(&mut panel.app(), "edit.redo", json!({}));
|
||||
run(&mut panel.app(), "select.set", json!({"ids": [a]}));
|
||||
settle(&mut panel);
|
||||
assert_eq!(panel.value("Note").as_deref(), Some("same note"), "the Note field shows the object's note");
|
||||
let at = below(&panel);
|
||||
panel.click_at(at);
|
||||
let (url, note) = url_and_note(&panel, a);
|
||||
assert_eq!(
|
||||
(url.as_deref(), note.as_deref()),
|
||||
(Some("https://example.com/redone"), Some("same note")),
|
||||
"Redo restores the URL and a click elsewhere keeps the note"
|
||||
);
|
||||
}
|
||||
|
||||
/// The same objects selected in another order keep an unfinished note, and a click elsewhere gives it to both.
|
||||
#[test]
|
||||
fn an_unfinished_note_stays_when_the_same_objects_are_selected_in_another_order() {
|
||||
let (mut app, a, b) = twins();
|
||||
run(&mut app, "select.set", json!({"ids": [a, b]}));
|
||||
let mut panel = Panel::new(app, show);
|
||||
panel.room(egui::vec2(320.0, 480.0));
|
||||
panel.frame();
|
||||
unfinished(&mut panel, "Note", "typed note");
|
||||
run(&mut panel.app(), "select.set", json!({"ids": [b, a]}));
|
||||
settle(&mut panel);
|
||||
assert_eq!(panel.value("Note").as_deref(), Some("typed note"), "the Note field keeps the unfinished note");
|
||||
let at = below(&panel);
|
||||
panel.click_at(at);
|
||||
let notes = (url_and_note(&panel, a).1, url_and_note(&panel, b).1);
|
||||
assert_eq!((notes.0.as_deref(), notes.1.as_deref()), (Some("typed note"), Some("typed note")), "both objects take the note");
|
||||
}
|
||||
|
||||
/// Selecting a part of a symbol instance drops an unfinished note: a selected part takes no note, so selecting the
|
||||
/// instance again and clicking elsewhere leaves the instance's note.
|
||||
#[test]
|
||||
fn selecting_a_part_of_the_instance_drops_an_unfinished_note() {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
run(&mut app, "file.new", json!({"width": 100, "height": 100}));
|
||||
let left = run(&mut app, "shape.rectangle", json!({"x": 0, "y": 0, "width": 30, "height": 30}))["id"].clone();
|
||||
let right = run(&mut app, "shape.rectangle", json!({"x": 50, "y": 0, "width": 30, "height": 30}))["id"].clone();
|
||||
let instance = run(&mut app, "symbol.new", json!({"name": "Pair", "ids": [left, right], "type": "dynamic"}))["id"].as_u64().unwrap();
|
||||
run(&mut app, "attributes.set", json!({"ids": [instance], "note": "instance note"}));
|
||||
run(&mut app, "select.set", json!({"ids": [instance]}));
|
||||
let mut panel = Panel::new(app, show);
|
||||
panel.room(egui::vec2(320.0, 480.0));
|
||||
panel.frame();
|
||||
unfinished(&mut panel, "Note", "typed note");
|
||||
run(&mut panel.app(), "symbol.instance.selectPart", json!({"id": instance, "path": [0]}));
|
||||
settle(&mut panel);
|
||||
assert_ne!(panel.value("Note").as_deref(), Some("typed note"), "the Note field drops the unfinished note");
|
||||
run(&mut panel.app(), "select.set", json!({"ids": [instance]}));
|
||||
settle(&mut panel);
|
||||
let at = below(&panel);
|
||||
panel.click_at(at);
|
||||
assert_eq!(url_and_note(&panel, instance).1.as_deref(), Some("instance note"), "the instance keeps its note");
|
||||
}
|
||||
|
||||
/// Only web and mail URLs reach the browser.
|
||||
#[test]
|
||||
fn the_browser_opens_web_and_mail_urls_only() {
|
||||
|
||||
@@ -364,14 +364,15 @@ fn render(
|
||||
overprint_preview: overprints == Overprints::Simulate,
|
||||
..Default::default()
|
||||
};
|
||||
let mut img = r.render(&shot.doc, w, hh, view, &opts);
|
||||
let mut img = r.render_words(&shot.doc, w, hh, view, &opts);
|
||||
if h != Highlight::None {
|
||||
let mask = shot
|
||||
.report
|
||||
.highlight_art(&shot.doc, h)
|
||||
.map(|art| r.render(&art, w, hh, view, &RenderOptions { skip_templates: true, ..Default::default() }));
|
||||
let red = [color.r(), color.g(), color.b()].map(f32::from);
|
||||
for (i, p) in img.pixels.as_chunks_mut::<4>().0.iter_mut().enumerate() {
|
||||
let pixels: &mut [u8] = bytemuck::cast_slice_mut(&mut img.pixels);
|
||||
for (i, p) in pixels.as_chunks_mut::<4>().0.iter_mut().enumerate() {
|
||||
// A light grey of the art, so the highlight stands out.
|
||||
let luma = 0.299 * p[0] as f32 + 0.587 * p[1] as f32 + 0.114 * p[2] as f32;
|
||||
let grey = 96.0 + luma * 0.62;
|
||||
@@ -381,7 +382,7 @@ fn render(
|
||||
}
|
||||
}
|
||||
}
|
||||
crate::canvas::color_image(&img)
|
||||
crate::canvas::color_image_owned(img)
|
||||
}
|
||||
|
||||
const REFRESH: &str = "ui.flattenerPreview.refresh";
|
||||
|
||||
@@ -300,10 +300,12 @@ fn selected_mid(app: &VectorcraftApp, stops: usize) -> Option<usize> {
|
||||
|
||||
/// What the panel's number fields edit: the gradient behind the active proxy
|
||||
/// ([`vectorcraft_engine::Session::gradient_owner`], which names the selected part of a symbol instance) on the selected
|
||||
/// objects. Each field passes it to [`NumberField::edit_target`], with the stop, midpoint or point it shows, so a value
|
||||
/// left unfinished in the field is dropped when another one is selected.
|
||||
/// objects, with how many times File › Revert and Undo or Redo replaced the document's content (after which the same
|
||||
/// node id can name another object, or the object another gradient). Each field passes it to
|
||||
/// [`NumberField::edit_target`], with the stop, midpoint or point it shows, so a value left unfinished in the field is
|
||||
/// dropped when another one is selected or the content is replaced.
|
||||
fn field_target(app: &VectorcraftApp) -> egui::IdSalt {
|
||||
let objects = app.session.active().map(|st| &st.selection.objects);
|
||||
let objects = app.session.active().map(|st| (&st.selection.objects, st.reverts, st.history_restores));
|
||||
egui::IdSalt::new((app.session.gradient_owner(), objects))
|
||||
}
|
||||
|
||||
|
||||
@@ -424,6 +424,62 @@ fn an_unfinished_aspect_or_repeats_value_does_not_reach_another_object() {
|
||||
assert_eq!(of(&rig, b), (Some(2.0), 2), "the other object takes 2%, not 20+2, and 2 repeats, not 20+2");
|
||||
}
|
||||
|
||||
/// A selected rectangle with a white-to-black gradient at 30°, then a red-to-blue one at 30° set over it.
|
||||
fn two_gradients() -> VectorcraftApp {
|
||||
let mut app = app(json!({"gradient": {"angle": 30}}));
|
||||
let stops = json!([{"offset": 0, "color": "#ff0000"}, {"offset": 1, "color": "#0000ff"}]);
|
||||
app.run("paint.setFill", json!({"gradient": {"angle": 30, "stops": stops}})).unwrap();
|
||||
app
|
||||
}
|
||||
|
||||
/// File › Revert drops an unfinished Angle value, though the reverted document has the same object, with a gradient at
|
||||
/// the same angle, selected again before the next frame.
|
||||
#[test]
|
||||
fn an_unfinished_angle_value_is_dropped_by_file_revert() {
|
||||
let mut app = app(json!({"gradient": {"angle": 30}}));
|
||||
let a = app.session.active().unwrap().selection.objects[0];
|
||||
let dir = vectorcraft_testkit::TempDir::new("gradient-revert");
|
||||
app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string())));
|
||||
app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string())));
|
||||
app.run("file.saveAs", json!({"path": dir.join("Gradient.vectorcraft")})).unwrap();
|
||||
// An unsaved change for Revert to undo: another gradient at the same angle.
|
||||
let stops = json!([{"offset": 0, "color": "#ff0000"}, {"offset": 1, "color": "#0000ff"}]);
|
||||
app.run("paint.setFill", json!({"gradient": {"angle": 30, "stops": stops}})).unwrap();
|
||||
let mut rig = Rig::new(app);
|
||||
rig.type_unfinished("Angle", "20+");
|
||||
rig.app().run("file.revert", json!({"confirmed": true})).unwrap();
|
||||
rig.app().run("select.set", json!({"ids": [a.0]})).unwrap();
|
||||
rig.finish("1");
|
||||
assert_eq!(hexes(&rig.app()), ["#ffffff", "#000000"], "the reverted gradient is selected");
|
||||
assert_eq!(fill(&rig.app()).angle, 1.0, "Revert drops the unfinished value: 1°, not 20+1");
|
||||
}
|
||||
|
||||
/// Undo drops an unfinished Angle value typed for the gradient it takes away, though the gradient it brings back has
|
||||
/// the same angle on the same selected object.
|
||||
#[test]
|
||||
fn an_unfinished_angle_value_is_dropped_by_undo() {
|
||||
let mut rig = Rig::new(two_gradients());
|
||||
rig.type_unfinished("Angle", "20+");
|
||||
rig.app().run("edit.undo", json!({})).unwrap();
|
||||
rig.finish("1");
|
||||
assert_eq!(hexes(&rig.app()), ["#ffffff", "#000000"], "Undo brings back the first gradient");
|
||||
assert_eq!(fill(&rig.app()).angle, 1.0, "Undo drops the unfinished value: 1°, not 20+1");
|
||||
}
|
||||
|
||||
/// Redo drops an unfinished Angle value typed for the gradient it takes away, though the gradient it brings back has
|
||||
/// the same angle on the same selected object.
|
||||
#[test]
|
||||
fn an_unfinished_angle_value_is_dropped_by_redo() {
|
||||
let mut app = two_gradients();
|
||||
app.run("edit.undo", json!({})).unwrap();
|
||||
let mut rig = Rig::new(app);
|
||||
rig.type_unfinished("Angle", "20+");
|
||||
rig.app().run("edit.redo", json!({})).unwrap();
|
||||
rig.finish("1");
|
||||
assert_eq!(hexes(&rig.app()), ["#ff0000", "#0000ff"], "Redo brings back the second gradient");
|
||||
assert_eq!(fill(&rig.app()).angle, 1.0, "Redo drops the unfinished value: 1°, not 20+1");
|
||||
}
|
||||
|
||||
/// An unfinished value is dropped when another object joins the selection, which keeps the same first object, and when
|
||||
/// another part of the same symbol instance is selected.
|
||||
#[test]
|
||||
|
||||
@@ -282,8 +282,8 @@ fn render(paints: Paints, g: &GraphicStyle, look: ThumbLook, px: u32) -> Option<
|
||||
};
|
||||
let layer = doc.layers[0].id;
|
||||
doc.insert(Some(layer), 0, styled_node(&shape, g, look.override_chars)).ok()?;
|
||||
let img = RENDERER.with(|r| r.borrow_mut().render_region(&doc, vectorcraft_geom::Rect::new(0.0, 0.0, SIDE, SIDE), px as f64 / SIDE, true));
|
||||
let mut img = crate::canvas::color_image(&img);
|
||||
let img = RENDERER.with(|r| r.borrow_mut().render_region_words(&doc, vectorcraft_geom::Rect::new(0.0, 0.0, SIDE, SIDE), px as f64 / SIDE, true));
|
||||
let mut img = crate::canvas::color_image_owned(img);
|
||||
if empty {
|
||||
slash(&mut img);
|
||||
}
|
||||
|
||||
@@ -1588,6 +1588,443 @@ fn the_corners_pop_up_takes_every_corner_of_a_whole_path_and_mixed_rounding() {
|
||||
assert_eq!(path_corners(&panel.app(), b), vec![(7.0, round); 4], "every corner of the path selected whole");
|
||||
}
|
||||
|
||||
/// Types `3+` into number field `name`, runs `change`, checks that the field then shows `shown`,
|
||||
/// and types `1` and presses Enter. `case` names the step in a failure.
|
||||
fn finish_after_change(panel: &mut Panel, case: &str, name: &str, shown: &str, change: impl FnOnce(&mut VectorcraftApp)) {
|
||||
use craft::ui::contract::Role;
|
||||
panel.click_role(name, Role::SPIN_BUTTON);
|
||||
panel.key(Key::A, Modifiers::COMMAND);
|
||||
panel.type_text("3+");
|
||||
change(&mut panel.app());
|
||||
panel.frame();
|
||||
assert_eq!(panel.value_role(name, Role::SPIN_BUTTON).as_deref(), Some(shown), "{case}: the field shows the new target's radius");
|
||||
panel.type_text("1");
|
||||
panel.key(Key::Enter, Modifiers::NONE);
|
||||
}
|
||||
|
||||
/// The one corner the Direct-Selected anchor picks ([`crate::panels::picked_corners`]).
|
||||
fn picked_corner(app: &VectorcraftApp) -> usize {
|
||||
let picked = crate::panels::picked_corners(app).unwrap();
|
||||
let corners = picked.items[0]["corners"].as_array().unwrap();
|
||||
assert_eq!((picked.items.len(), corners.len()), (1, 1), "one corner is picked");
|
||||
corners[0].as_u64().unwrap() as usize
|
||||
}
|
||||
|
||||
/// The radii of live-cornered paths `a` and `b` ([`corner_radii`]).
|
||||
fn two_corner_radii(panel: &Panel, a: u64, b: u64) -> (Vec<f64>, Vec<f64>) {
|
||||
let app = panel.app();
|
||||
(corner_radii(&app, a), corner_radii(&app, b))
|
||||
}
|
||||
|
||||
/// The radius of each corner of live-cornered path `id`, in document lengths.
|
||||
fn corner_radii(app: &VectorcraftApp, id: u64) -> Vec<f64> {
|
||||
let n = app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().clone();
|
||||
let lc = vectorcraft_doc::LiveCorners::of(&n).unwrap();
|
||||
(0..lc.all().len()).map(|k| crate::panels::corner_length(&lc, k)).collect()
|
||||
}
|
||||
|
||||
/// A corner radius typed and not yet entered is dropped when the selection moves to other corners
|
||||
/// with the same radius: Enter then sets only what was typed after the change, on the corners now
|
||||
/// shown. Covers the Corner Radius field of live rectangles and live polygons, each corner's field
|
||||
/// of a live rectangle, the field of Direct-Selected corners and the Corners pop-up's Radius.
|
||||
#[test]
|
||||
fn an_unfinished_corner_radius_does_not_reach_other_corners() {
|
||||
let polygon = |app: &mut VectorcraftApp, cx: f64| {
|
||||
app.run("shape.polygon", json!({"cx": cx, "cy": 150, "radius": 40, "sides": 5})).unwrap()["id"].as_u64().unwrap()
|
||||
};
|
||||
let mut app = new_app();
|
||||
let (a, b) = (rect(&mut app, 20.0, 20.0, 60.0, 40.0).as_u64().unwrap(), rect(&mut app, 120.0, 20.0, 60.0, 40.0).as_u64().unwrap());
|
||||
let (p, q) = (polygon(&mut app, 80.0), polygon(&mut app, 240.0));
|
||||
let star = app.run("shape.star", json!({"cx": 200, "cy": 200, "radius1": 80, "radius2": 40})).unwrap()["id"].as_u64().unwrap();
|
||||
app.run("select.set", json!({"ids": [a]})).unwrap();
|
||||
let mut panel = Panel::new(app, show);
|
||||
panel.room(egui::vec2(420.0, 920.0));
|
||||
|
||||
// With the selection unchanged, the value typed so far is kept: 3+1 gives 4.
|
||||
finish_after_change(&mut panel, "unchanged", "Corner Radius", "3+", |_| {});
|
||||
assert_eq!(corner_radii(&panel.app(), a), [4.0; 4], "an unchanged target keeps the typed value");
|
||||
panel.app().run("object.setLiveShape", json!({"ids": [a], "radius": 0})).unwrap();
|
||||
panel.frame();
|
||||
|
||||
// A live rectangle's Corner Radius.
|
||||
finish_after_change(&mut panel, "rectangle", "Corner Radius", "0 pt", |app| {
|
||||
app.run("select.set", json!({"ids": [b]})).unwrap();
|
||||
});
|
||||
assert_eq!(two_corner_radii(&panel, a, b), (vec![0.0; 4], vec![1.0; 4]), "rectangle: b takes 1 pt, not 3+1");
|
||||
|
||||
// A live polygon's Corner Radius.
|
||||
panel.app().run("select.set", json!({"ids": [p]})).unwrap();
|
||||
panel.frame();
|
||||
finish_after_change(&mut panel, "polygon", "Corner Radius", "0 pt", |app| {
|
||||
app.run("select.set", json!({"ids": [q]})).unwrap();
|
||||
});
|
||||
assert_eq!(two_corner_radii(&panel, p, q), (vec![0.0; 5], vec![1.0; 5]), "polygon: q takes 1 pt, not 3+1");
|
||||
|
||||
// Each corner's field of a live rectangle, with Single Corner Radius off.
|
||||
crate::panels::transform::set_pref(&mut panel.app(), "singleCornerRadius", false);
|
||||
panel.app().run("object.setLiveShape", json!({"ids": [a, b], "radius": 0})).unwrap();
|
||||
panel.app().run("select.set", json!({"ids": [a]})).unwrap();
|
||||
panel.frame();
|
||||
finish_after_change(&mut panel, "Top Left", "Top Left", "0 pt", |app| {
|
||||
app.run("select.set", json!({"ids": [b]})).unwrap();
|
||||
});
|
||||
assert_eq!(two_corner_radii(&panel, a, b), (vec![0.0; 4], vec![1.0, 0.0, 0.0, 0.0]), "Top Left: b takes 1 pt, not 3+1");
|
||||
|
||||
// Changing the selected rectangles drops the draft while their layer stays targeted.
|
||||
panel.app().run("object.setLiveShape", json!({"ids": [a, b], "radius": 0})).unwrap();
|
||||
panel.app().run("select.set", json!({"ids": [a, b]})).unwrap();
|
||||
let layer = panel.app().session.active().unwrap().doc.default_layer().unwrap();
|
||||
panel.app().session.active_mut().unwrap().selection.target = Some(layer);
|
||||
panel.frame();
|
||||
finish_after_change(&mut panel, "selected rectangles", "Top Left", "0 pt", |app| {
|
||||
app.session.active_mut().unwrap().selection.objects.retain(|id| id.0 == b);
|
||||
});
|
||||
assert_eq!(two_corner_radii(&panel, a, b), (vec![0.0; 4], vec![1.0, 0.0, 0.0, 0.0]), "selected rectangles: b takes 1 pt, not 3+1");
|
||||
panel.app().session.active_mut().unwrap().selection.target = None;
|
||||
crate::panels::transform::set_pref(&mut panel.app(), "singleCornerRadius", true);
|
||||
|
||||
// Direct-Selected corners: another corner of the same path, so the selected objects stay the same.
|
||||
panel.app().select_tool("directSelection");
|
||||
panel.app().run("select.anchors", json!({"id": star, "anchors": [[0, 2]], "mode": "set"})).unwrap();
|
||||
panel.frame();
|
||||
let before = picked_corner(&panel.app());
|
||||
finish_after_change(&mut panel, "Direct-Selected", "Corner Radius", "0 pt", |app| {
|
||||
app.run("select.anchors", json!({"id": star, "anchors": [[0, 4]], "mode": "set"})).unwrap();
|
||||
});
|
||||
let after = picked_corner(&panel.app());
|
||||
let radii = corner_radii(&panel.app(), star);
|
||||
assert_eq!((radii[before], radii[after]), (0.0, 1.0), "Direct-Selected: the second corner takes 1 pt, not 3+1");
|
||||
|
||||
// The Corners pop-up's Radius.
|
||||
panel.app().run("select.anchors", json!({"id": star, "anchors": [[0, 6]], "mode": "set"})).unwrap();
|
||||
panel.frame();
|
||||
let before = picked_corner(&panel.app());
|
||||
panel.click("Corners");
|
||||
finish_after_change(&mut panel, "pop-up", "Radius", "0 pt", |app| {
|
||||
app.run("select.anchors", json!({"id": star, "anchors": [[0, 8]], "mode": "set"})).unwrap();
|
||||
});
|
||||
let after = picked_corner(&panel.app());
|
||||
let radii = corner_radii(&panel.app(), star);
|
||||
assert_eq!((radii[before], radii[after]), (0.0, 1.0), "pop-up: the second corner takes 1 pt, not 3+1");
|
||||
}
|
||||
|
||||
/// Rounding a Direct-Selected sharp corner gives it new anchors, and the corner fields' edit target
|
||||
/// stays the same, so a scrub that rounds the corner goes on editing it.
|
||||
#[test]
|
||||
fn rounding_a_direct_selected_corner_keeps_the_corner_fields_target() {
|
||||
let mut app = new_app();
|
||||
let star = app.run("shape.star", json!({"cx": 200, "cy": 150, "radius1": 80, "radius2": 40})).unwrap()["id"].as_u64().unwrap();
|
||||
app.select_tool("directSelection");
|
||||
app.run("select.anchors", json!({"id": star, "anchors": [[0, 2]], "mode": "set"})).unwrap();
|
||||
let anchors = app.session.active().unwrap().selection.anchors.clone();
|
||||
let target = |app: &VectorcraftApp| {
|
||||
let picked = crate::panels::picked_corners(app).unwrap();
|
||||
crate::panels::corner_target(app, &picked.corners)
|
||||
};
|
||||
let before = target(&app);
|
||||
let picked = crate::panels::picked_corners(&app).unwrap();
|
||||
crate::panels::set_picked_corners(&mut app, &picked, json!({"radius": 5}));
|
||||
assert_eq!(corner_radii(&app, star)[picked_corner(&app)], 5.0, "the corner is rounded");
|
||||
assert_ne!(app.session.active().unwrap().selection.anchors, anchors, "the rounded corner has other anchors");
|
||||
assert_eq!(target(&app), before, "the same corner is the target");
|
||||
}
|
||||
|
||||
/// Reversing a path drops an unfinished radius when the picked index names a different corner:
|
||||
/// an expanded rectangle, a path whose first corner and last corner have sides of the same
|
||||
/// lengths and turn the same way, a crossing path whose corners share a position, a path whose
|
||||
/// reversed corner has sides in the same directions, a path with two corners at the same point
|
||||
/// whose sides lean the same ways, and a small subpath beside a very large one.
|
||||
#[test]
|
||||
fn an_unfinished_corner_radius_is_dropped_when_the_path_is_reversed() {
|
||||
let mut app = new_app();
|
||||
let expanded = rect(&mut app, 20.0, 20.0, 60.0, 40.0).as_u64().unwrap();
|
||||
app.run("select.set", json!({"ids": [expanded]})).unwrap();
|
||||
app.run("object.expandShape", json!({})).unwrap();
|
||||
let kite = app.run("path.create", json!({"d": "M20 20 L26 12 L36 28 L30 20 Z"})).unwrap()["id"].as_u64().unwrap();
|
||||
let crossing = app.run("path.create", json!({"d": "M0 0 L20 20 L40 0 L40 40 L20 20 L0 40"})).unwrap()["id"].as_u64().unwrap();
|
||||
let parallel = app.run("path.create", json!({"d": "M0 0 L0 20 L20 20 L40 40 L20 40 L20 20"})).unwrap()["id"].as_u64().unwrap();
|
||||
let coincident = app.run("path.create", json!({"d": "M0 0 L20 20 L40 30 L50 40 L20 20 L0 10"})).unwrap()["id"].as_u64().unwrap();
|
||||
let small =
|
||||
app.run("path.create", json!({"d": "M0 0 L0.2 0 L0.2 0.2 L0 0.2 Z M0 0 L1000000 0 L1000000 1000000 Z"})).unwrap()["id"].as_u64().unwrap();
|
||||
app.select_tool("directSelection");
|
||||
let mut panel = Panel::new(app, show);
|
||||
panel.room(egui::vec2(420.0, 920.0));
|
||||
for (case, id, index) in [
|
||||
("expanded rectangle", expanded, 0),
|
||||
("kite", kite, 0),
|
||||
("crossing path", crossing, 1),
|
||||
("parallel sides", parallel, 1),
|
||||
("coincident corners", coincident, 1),
|
||||
("small subpath", small, 1),
|
||||
] {
|
||||
// Where the corner at `index` is and the directions its sides leave it in.
|
||||
let corner = |app: &VectorcraftApp| {
|
||||
let node = app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap();
|
||||
let c = *vectorcraft_doc::LiveCorners::of(node).unwrap().corner(index).unwrap();
|
||||
(c.at, c.u, c.v)
|
||||
};
|
||||
panel.app().run("select.anchors", json!({"id": id, "anchors": [[0, index]], "mode": "set"})).unwrap();
|
||||
panel.frame();
|
||||
let before = corner(&panel.app());
|
||||
finish_after_change(&mut panel, case, "Corner Radius", "0 pt", |app| {
|
||||
app.run("path.reverse", json!({"ids": [id]})).unwrap();
|
||||
});
|
||||
let app = panel.app();
|
||||
assert_ne!(corner(&app), before, "{case}: index {index} names a different corner");
|
||||
let picked = picked_corner(&app);
|
||||
assert_eq!(picked, index, "{case}: the picked corner index stays the same");
|
||||
let radii = corner_radii(&app, id);
|
||||
assert_eq!(radii[picked], 1.0, "{case}: the corner now picked takes 1 pt");
|
||||
assert!(radii.iter().all(|&radius| radius != 4.0), "{case}: no corner takes the unfinished 3+1 draft");
|
||||
}
|
||||
}
|
||||
|
||||
/// Reversing another subpath keeps an unfinished radius for the picked corner of the first subpath.
|
||||
#[test]
|
||||
fn an_unfinished_corner_radius_stays_when_another_subpath_is_reversed() {
|
||||
let mut app = new_app();
|
||||
let id = app.run("path.create", json!({"d": "M0 0 L40 0 L40 30 L0 30 Z M100 100 L140 100 L120 140 Z"})).unwrap()["id"].as_u64().unwrap();
|
||||
app.select_tool("directSelection");
|
||||
app.run("select.anchors", json!({"id": id, "anchors": [[0, 1]], "mode": "set"})).unwrap();
|
||||
let mut panel = Panel::new(app, show);
|
||||
panel.room(egui::vec2(420.0, 920.0));
|
||||
finish_after_change(&mut panel, "second subpath reversed", "Corner Radius", "3+", |app| {
|
||||
app.run("path.reverse", json!({"ids": [id], "subpath": 1})).unwrap();
|
||||
});
|
||||
let app = panel.app();
|
||||
assert_eq!(picked_corner(&app), 1, "the first subpath's corner stays picked");
|
||||
let radii = corner_radii(&app, id);
|
||||
assert_eq!(radii[1], 4.0, "the picked corner takes 3+1");
|
||||
assert!(radii[..4].iter().enumerate().all(|(index, &radius)| index == 1 || radius == 0.0), "the other corners of the first subpath stay sharp");
|
||||
}
|
||||
|
||||
/// Moving another subpath's bounds keeps an unfinished radius for the picked corner of the first subpath.
|
||||
#[test]
|
||||
fn an_unfinished_corner_radius_stays_when_another_subpath_moves_the_bounds() {
|
||||
let mut app = new_app();
|
||||
let id = app.run("path.create", json!({"d": "M0 0 L40 0 L40 30 L0 30 Z M100 100 L140 100 L120 140 Z"})).unwrap()["id"].as_u64().unwrap();
|
||||
app.select_tool("directSelection");
|
||||
app.run("select.anchors", json!({"id": id, "anchors": [[0, 1]], "mode": "set"})).unwrap();
|
||||
let mut panel = Panel::new(app, show);
|
||||
panel.room(egui::vec2(420.0, 920.0));
|
||||
finish_after_change(&mut panel, "second subpath moves the bounds", "Corner Radius", "3+", |app| {
|
||||
app.run("path.moveAnchor", json!({"id": id, "subpath": 1, "anchor": 0, "x": -200, "y": -200})).unwrap();
|
||||
});
|
||||
let app = panel.app();
|
||||
assert_eq!(picked_corner(&app), 1, "the first subpath's corner stays picked");
|
||||
let radii = corner_radii(&app, id);
|
||||
assert_eq!(radii[1], 4.0, "the picked corner takes 3+1");
|
||||
assert!(radii[..4].iter().enumerate().all(|(index, &radius)| index == 1 || radius == 0.0), "the other corners of the first subpath stay sharp");
|
||||
}
|
||||
|
||||
/// Moving, rotating or scaling a live shape keeps an unfinished Corner Radius: Enter gives 3+1.
|
||||
/// Moving a path keeps its corner target, and scaling a path drops it.
|
||||
#[test]
|
||||
fn an_unfinished_corner_radius_stays_while_the_shape_moves_rotates_or_scales() {
|
||||
let mut app = new_app();
|
||||
let p = app.run("shape.polygon", json!({"cx": 100, "cy": 100, "radius": 40, "sides": 5})).unwrap()["id"].as_u64().unwrap();
|
||||
let r = rect(&mut app, 200.0, 20.0, 60.0, 40.0).as_u64().unwrap();
|
||||
let path = square_path(&mut app, 300.0);
|
||||
let slanted = app.run("path.create", json!({"d": "M300 50 L360 70 L340 130 L290 110 Z"})).unwrap()["id"].as_u64().unwrap();
|
||||
let mut panel = Panel::new(app, show);
|
||||
panel.room(egui::vec2(420.0, 920.0));
|
||||
let cases: [(&str, u64, usize, &str, Value); 4] = [
|
||||
("polygon moved", p, 5, "object.move", json!({"dx": 12.25, "dy": -5})),
|
||||
("polygon rotated", p, 5, "object.rotate", json!({"angle": 30})),
|
||||
("rectangle scaled", r, 4, "object.scale", json!({"sx": 200, "sy": 100})),
|
||||
("rectangle rotated", r, 4, "object.rotate", json!({"angle": 30})),
|
||||
];
|
||||
for (case, id, corners, command, params) in cases {
|
||||
panel.app().run("select.set", json!({"ids": [id]})).unwrap();
|
||||
panel.frame();
|
||||
finish_after_change(&mut panel, case, "Corner Radius", "3+", |app| {
|
||||
app.run(command, params).unwrap();
|
||||
});
|
||||
assert_eq!(corner_radii(&panel.app(), id), vec![4.0; corners], "{case}: every corner takes 3+1");
|
||||
panel.app().run("object.setLiveShape", json!({"ids": [id], "radius": 0})).unwrap();
|
||||
panel.frame();
|
||||
}
|
||||
// Moving a path keeps its Direct-Selected corner target; scaling the path drops it.
|
||||
let mut app = panel.app();
|
||||
for path in [path, slanted] {
|
||||
let target = |app: &mut VectorcraftApp| {
|
||||
app.select_tool("directSelection");
|
||||
app.run("select.anchors", json!({"id": path, "anchors": [[0, 0]], "mode": "set"})).unwrap();
|
||||
let picked = crate::panels::picked_corners(app).unwrap();
|
||||
crate::panels::corner_target(app, &picked.corners)
|
||||
};
|
||||
let before = target(&mut app);
|
||||
let case = "path moved";
|
||||
app.select_tool("selection");
|
||||
app.run("select.set", json!({"ids": [path]})).unwrap();
|
||||
app.run("object.move", json!({"dx": 12.25, "dy": -5})).unwrap();
|
||||
assert_eq!(target(&mut app), before, "{case}: the same corner is the target");
|
||||
for (case, params) in [("path scaled", json!({"sx": 200, "sy": 200})), ("path scaled unevenly", json!({"sx": 200, "sy": 100}))] {
|
||||
let before = target(&mut app);
|
||||
app.select_tool("selection");
|
||||
app.run("select.set", json!({"ids": [path]})).unwrap();
|
||||
app.run("object.scale", params).unwrap();
|
||||
assert_ne!(target(&mut app), before, "{case}: scaling the path drops the value");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A Direct-Selected live star corner keeps an unfinished radius while the star rotates.
|
||||
#[test]
|
||||
fn an_unfinished_corner_radius_stays_while_a_star_rotates() {
|
||||
let mut app = new_app();
|
||||
let id = app.run("shape.star", json!({"cx": 100, "cy": 100, "radius1": 40, "radius2": 20, "points": 5})).unwrap()["id"].as_u64().unwrap();
|
||||
app.select_tool("directSelection");
|
||||
app.run("select.anchors", json!({"id": id, "anchors": [[0, 0]], "mode": "set"})).unwrap();
|
||||
let mut panel = Panel::new(app, show);
|
||||
panel.room(egui::vec2(420.0, 920.0));
|
||||
panel.frame();
|
||||
finish_after_change(&mut panel, "star rotated", "Corner Radius", "3+", |app| {
|
||||
app.select_tool("selection");
|
||||
app.run("select.set", json!({"ids": [id]})).unwrap();
|
||||
app.run("object.rotate", json!({"angle": 30})).unwrap();
|
||||
app.select_tool("directSelection");
|
||||
app.run("select.anchors", json!({"id": id, "anchors": [[0, 0]], "mode": "set"})).unwrap();
|
||||
});
|
||||
let app = panel.app();
|
||||
let picked = picked_corner(&app);
|
||||
assert_eq!(picked, 0, "the same star corner stays selected");
|
||||
assert_eq!(corner_radii(&app, id)[picked], 4.0, "the picked corner takes 3+1");
|
||||
}
|
||||
|
||||
/// Selecting the same rectangles in another order keeps an unfinished radius for all their corners.
|
||||
#[test]
|
||||
fn an_unfinished_corner_radius_stays_when_the_same_objects_are_selected_in_another_order() {
|
||||
let mut app = new_app();
|
||||
let a = rect(&mut app, 20.0, 20.0, 60.0, 40.0).as_u64().unwrap();
|
||||
let b = rect(&mut app, 200.0, 20.0, 60.0, 40.0).as_u64().unwrap();
|
||||
app.run("select.set", json!({"ids": [a, b]})).unwrap();
|
||||
let mut panel = Panel::new(app, show);
|
||||
panel.room(egui::vec2(420.0, 920.0));
|
||||
finish_after_change(&mut panel, "selection order", "Corner Radius", "3+", |app| {
|
||||
app.run("select.set", json!({"ids": [b, a]})).unwrap();
|
||||
});
|
||||
assert_eq!(corner_radii(&panel.app(), a), [4.0; 4], "every corner of the first rectangle takes 3+1");
|
||||
assert_eq!(corner_radii(&panel.app(), b), [4.0; 4], "every corner of the second rectangle takes 3+1");
|
||||
}
|
||||
|
||||
/// A live polygon's Corner Radius typed and not yet entered is dropped when the polygon gains a
|
||||
/// side, since Enter would then set a corner the value was not typed for.
|
||||
#[test]
|
||||
fn an_unfinished_corner_radius_is_dropped_when_a_polygon_gains_a_side() {
|
||||
let mut app = new_app();
|
||||
let p = app.run("shape.polygon", json!({"cx": 100, "cy": 100, "radius": 40, "sides": 5})).unwrap()["id"].as_u64().unwrap();
|
||||
app.run("select.set", json!({"ids": [p]})).unwrap();
|
||||
let mut panel = Panel::new(app, show);
|
||||
panel.room(egui::vec2(420.0, 920.0));
|
||||
finish_after_change(&mut panel, "sides", "Corner Radius", "0 pt", |app| {
|
||||
app.run("object.setLiveShape", json!({"ids": [p], "sides": 6})).unwrap();
|
||||
});
|
||||
assert_eq!(corner_radii(&panel.app(), p), [1.0; 6], "every corner of the six takes 1 pt, not 3+1");
|
||||
|
||||
let p = panel.app().run("shape.polygon", json!({"cx": 200, "cy": 100, "radius": 40, "sides": 5})).unwrap()["id"].as_u64().unwrap();
|
||||
panel.app().select_tool("directSelection");
|
||||
panel.app().run("select.anchors", json!({"id": p, "anchors": [[0, 2]], "mode": "set"})).unwrap();
|
||||
panel.frame();
|
||||
finish_after_change(&mut panel, "Direct-Selected vertex", "Corner Radius", "0 pt", |app| {
|
||||
app.run("object.setLiveShape", json!({"ids": [p], "sides": 6})).unwrap();
|
||||
app.run("select.anchors", json!({"id": p, "anchors": [[0, 2]], "mode": "set"})).unwrap();
|
||||
});
|
||||
assert_eq!(picked_corner(&panel.app()), 2, "the same anchor index stays selected");
|
||||
assert!(corner_radii(&panel.app(), p).iter().all(|&radius| radius != 4.0), "no corner takes the unfinished 3+1 draft");
|
||||
}
|
||||
|
||||
/// A live shape's Corner Radius typed and not yet entered is dropped when Direct Selection moves
|
||||
/// to another corner of the same shape: the selected objects stay the same, and the corner the
|
||||
/// field sets changes.
|
||||
#[test]
|
||||
fn an_unfinished_live_shape_corner_radius_is_dropped_when_another_corner_is_direct_selected() {
|
||||
let mut app = new_app();
|
||||
let a = rect(&mut app, 20.0, 20.0, 60.0, 40.0).as_u64().unwrap();
|
||||
let p = app.run("shape.polygon", json!({"cx": 200, "cy": 150, "radius": 40, "sides": 5})).unwrap()["id"].as_u64().unwrap();
|
||||
app.select_tool("directSelection");
|
||||
app.run("select.anchors", json!({"id": a, "anchors": [[0, 0]], "mode": "set"})).unwrap();
|
||||
let mut panel = Panel::new(app, show);
|
||||
panel.room(egui::vec2(420.0, 920.0));
|
||||
panel.frame();
|
||||
finish_after_change(&mut panel, "rectangle corner", "Corner Radius", "0 pt", |app| {
|
||||
app.run("select.anchors", json!({"id": a, "anchors": [[0, 1]], "mode": "set"})).unwrap();
|
||||
});
|
||||
assert_eq!(corner_radii(&panel.app(), a), [0.0, 1.0, 0.0, 0.0], "rectangle corner: the second corner takes 1 pt, not 3+1");
|
||||
|
||||
panel.app().run("select.anchors", json!({"id": p, "anchors": [[0, 0]], "mode": "set"})).unwrap();
|
||||
panel.frame();
|
||||
finish_after_change(&mut panel, "polygon corner", "Corner Radius", "0 pt", |app| {
|
||||
app.run("select.anchors", json!({"id": p, "anchors": [[0, 2]], "mode": "set"})).unwrap();
|
||||
});
|
||||
assert_eq!(corner_radii(&panel.app(), p), [0.0, 0.0, 1.0, 0.0, 0.0], "polygon corner: the third corner takes 1 pt, not 3+1");
|
||||
}
|
||||
|
||||
/// With Single Corner Radius off, a Top Left radius typed and not yet entered stays while Direct
|
||||
/// Selection moves to another anchor of the same live rectangle: the field sets the top left
|
||||
/// corner whichever anchors are selected.
|
||||
#[test]
|
||||
fn an_unfinished_rectangle_corner_radius_stays_while_its_anchors_change() {
|
||||
let mut app = new_app();
|
||||
let a = rect(&mut app, 20.0, 20.0, 60.0, 40.0).as_u64().unwrap();
|
||||
app.run("select.set", json!({"ids": [a]})).unwrap();
|
||||
let mut panel = Panel::new(app, show);
|
||||
panel.room(egui::vec2(420.0, 920.0));
|
||||
crate::panels::transform::set_pref(&mut panel.app(), "singleCornerRadius", false);
|
||||
panel.app().select_tool("directSelection");
|
||||
panel.app().run("select.anchors", json!({"id": a, "anchors": [[0, 0]], "mode": "set"})).unwrap();
|
||||
panel.frame();
|
||||
finish_after_change(&mut panel, "anchors", "Top Left", "3+", |app| {
|
||||
app.run("select.anchors", json!({"id": a, "anchors": [[0, 1]], "mode": "set"})).unwrap();
|
||||
});
|
||||
assert_eq!(corner_radii(&panel.app(), a), [4.0, 0.0, 0.0, 0.0], "the typed value is kept: 3+1 gives 4");
|
||||
}
|
||||
|
||||
/// A corner radius typed and not yet entered is dropped when File › Revert replaces the document,
|
||||
/// even where the same rectangle is selected again with the same radius.
|
||||
#[test]
|
||||
fn an_unfinished_corner_radius_is_dropped_by_file_revert() {
|
||||
let mut app = new_app();
|
||||
let id = rect(&mut app, 20.0, 20.0, 60.0, 40.0).as_u64().unwrap();
|
||||
let dir = vectorcraft_testkit::TempDir::new("corner-radius-revert");
|
||||
app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string())));
|
||||
app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string())));
|
||||
app.run("file.saveAs", json!({"path": dir.join("Corners.vectorcraft")})).unwrap();
|
||||
// An unsaved change for Revert to undo, leaving the rectangle as saved.
|
||||
rect(&mut app, 200.0, 200.0, 20.0, 20.0);
|
||||
app.run("select.set", json!({"ids": [id]})).unwrap();
|
||||
let mut panel = Panel::new(app, show);
|
||||
panel.room(egui::vec2(420.0, 920.0));
|
||||
finish_after_change(&mut panel, "File Revert", "Corner Radius", "0 pt", |app| {
|
||||
app.run("file.revert", json!({"confirmed": true})).unwrap();
|
||||
app.run("select.set", json!({"ids": [id]})).unwrap();
|
||||
});
|
||||
assert_eq!(corner_radii(&panel.app(), id), [1.0; 4], "Revert drops the unfinished value");
|
||||
}
|
||||
|
||||
/// A corner radius typed and not yet entered is dropped when Undo or Redo restores the document,
|
||||
/// even where the same rectangle is selected again with the same radius.
|
||||
#[test]
|
||||
fn an_unfinished_corner_radius_is_dropped_by_undo_and_redo() {
|
||||
for command in ["edit.undo", "edit.redo"] {
|
||||
let mut app = new_app();
|
||||
let id = rect(&mut app, 20.0, 20.0, 60.0, 40.0).as_u64().unwrap();
|
||||
// A step for Undo to take back and Redo to make again, leaving the rectangle as it is.
|
||||
rect(&mut app, 200.0, 200.0, 20.0, 20.0);
|
||||
if command == "edit.redo" {
|
||||
app.run("edit.undo", json!({})).unwrap();
|
||||
}
|
||||
app.run("select.set", json!({"ids": [id]})).unwrap();
|
||||
let mut panel = Panel::new(app, show);
|
||||
panel.room(egui::vec2(420.0, 920.0));
|
||||
finish_after_change(&mut panel, command, "Corner Radius", "0 pt", |app| {
|
||||
app.run(command, json!({})).unwrap();
|
||||
app.run("select.set", json!({"ids": [id]})).unwrap();
|
||||
});
|
||||
assert_eq!(corner_radii(&panel.app(), id), [1.0; 4], "{command} drops the unfinished value");
|
||||
}
|
||||
}
|
||||
|
||||
/// One effect on the one selected object shows its name and a Delete icon beside the fx button,
|
||||
/// which removes it in one undo step, the object's own or its stroke's. With several effects the
|
||||
/// icon activates the Appearance panel; without one, or with several objects selected, no name.
|
||||
|
||||
@@ -116,10 +116,11 @@ pub(super) fn corner_rows(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
panels::set_picked_corners(app, &picked, json!({"kind": kind}));
|
||||
}
|
||||
let lengths = crate::canvas::general_lengths(app);
|
||||
let target = panels::corner_target(app, &picked.corners);
|
||||
let mut edit = None;
|
||||
Field::new(tl!("Corner Radius")).show(ui, |ui, _| {
|
||||
Row::new().show(ui, |ui, _| {
|
||||
edit = Some(NumberField::length(tl!("Corner Radius"), Bind::given(picked.radius), lengths).show(ui).edit);
|
||||
edit = Some(NumberField::length(tl!("Corner Radius"), Bind::given(picked.radius), lengths).edit_target(target).show(ui).edit);
|
||||
panels::corners_link(app, ui);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -100,7 +100,7 @@ impl ThumbSource<SymbolThumb> for SymbolPictures<'_> {
|
||||
render_art(&mut renderer, self.doc, self.name, vectorcraft_geom::Rect::new(x0, y0, x1, y1), (*w, *h))
|
||||
}
|
||||
};
|
||||
img.map_or(ThumbRender::Blank, |img| ThumbRender::Ready(crate::canvas::color_image_owned(img)))
|
||||
img.map_or(ThumbRender::Blank, |img| ThumbRender::Ready(crate::canvas::color_image(&img)))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -64,6 +64,9 @@ pub struct PrefsWindow {
|
||||
/// General › Script File Access: the file access kept with Always, read when the window opens; `None` where the
|
||||
/// session keeps none (no settings folder, and the web).
|
||||
script_access: Option<script_access::Access>,
|
||||
/// Automation drove the window: a pass that carried injected input showed it. OK then saves no agent setting
|
||||
/// changed in it until the window closes ([`model::Live`]'s `apply`).
|
||||
automated: bool,
|
||||
}
|
||||
|
||||
impl PrefsWindow {
|
||||
@@ -248,6 +251,7 @@ pub fn open(app: &mut VectorcraftApp, category: Option<&str>) {
|
||||
reset_asked: None,
|
||||
strings: Default::default(),
|
||||
script_access,
|
||||
automated: false,
|
||||
};
|
||||
w.state.selected = selected.to_string();
|
||||
w.sync_strings();
|
||||
@@ -257,6 +261,7 @@ pub fn open(app: &mut VectorcraftApp, category: Option<&str>) {
|
||||
/// One pass of the window, while it is open. The window leaves `app` for the pass so its model can use the app.
|
||||
pub fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui) {
|
||||
let Some(mut w) = app.prefs.take() else { return };
|
||||
w.automated |= app.automation_is_acting();
|
||||
// Rows drawn by `PathSetting` edit the draft directly.
|
||||
w.sync_strings();
|
||||
let mut state = std::mem::take(&mut w.state);
|
||||
|
||||
Loaded 100 of 114 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user