mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-04 21:12:57 -05:00
Merge main into fix/prefs-agents-control-clients
This commit is contained in:
commit
c4105eecb3
109 files changed
+5246
-615
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 }
|
||||
|
||||
+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);
|
||||
|
||||
@@ -31,8 +31,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 +102,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
|
||||
),
|
||||
@@ -526,6 +526,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 +556,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 +586,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 +626,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 +653,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)
|
||||
|
||||
@@ -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() {
|
||||
|
||||
@@ -29,6 +29,14 @@ const ENVELOPES: &str = "CDR envelopes were not applied, and the shapes under th
|
||||
const LENSES: &str = "CDR lenses and object transparency were not applied, and the objects they are on show opaque";
|
||||
const TOO_DEEP: &str = "parts of the drawing nested too deeply, or past the import limits, were left out";
|
||||
const DAMAGED: &str = "damaged parts of the drawing were left out";
|
||||
/// Shown with [`UNSUPPORTED_OBJECTS`] or [`TOO_DEEP`]: `craft-cdr` opens a PowerClip frame whose
|
||||
/// contents were all left out as a plain shape. Its warnings name neither the kinds of objects
|
||||
/// left out nor the frames that lost their contents, so this line is shown whenever objects were
|
||||
/// left out. Once `craft-cdr` reports which frames lost their contents, show it only for those.
|
||||
const EMPTY_FRAMES: &str = "CDR PowerClip frames whose contents were left out opened empty, as plain shapes";
|
||||
/// The first version, in hundreds, whose PowerClip frames `craft-cdr` reads: earlier versions
|
||||
/// store their objects' styles inline, and the reader opens none of them as frames.
|
||||
const FRAMES_FROM: u16 = 400;
|
||||
const PAGES_CUT: &str = "CDR pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard";
|
||||
|
||||
const CMX_UNSUPPORTED_OBJECTS: &str =
|
||||
@@ -103,7 +111,11 @@ pub(super) fn import(bytes: &[u8]) -> Result<(Document, Vec<String>)> {
|
||||
}
|
||||
why => err(format!("this CDR drawing can't be read ({why})")),
|
||||
})?;
|
||||
Ok(build(&d, note, PAGES_CUT))
|
||||
let (doc, mut warnings) = build(&d, note, PAGES_CUT);
|
||||
if d.version >= FRAMES_FROM && d.warnings.iter().any(|w| matches!(w, Warning::UnsupportedObjects | Warning::TooDeep)) {
|
||||
warnings.push(EMPTY_FRAMES.to_string());
|
||||
}
|
||||
Ok((doc, warnings))
|
||||
}
|
||||
|
||||
/// Is `bytes` a `.cmx` file, of any byte order or coordinate size?
|
||||
|
||||
@@ -9,7 +9,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Open Document",
|
||||
[],
|
||||
None,
|
||||
"{path | name | dataBase64 (a file's path, or its name with its bytes), pages?: \"2-3, 5\" (PDF/.ai: 1-based, default all; one artboard each) | page?: n, cropTo?: bounding|art|crop (default)|trim|bleed|media (the box each artboard gets; bounding: the art's bounds; trim: the bleed box round it becomes the document's bleed, and the artboards are 36 pt apart plus that bleed on both sides; a PDF-compatible file whose first PDF page's PieceInfo holds, in itself or nested up to four dictionaries deep counting PieceInfo, a key starting with AIPrivateData or AIPDFPrivateData, when its pages are imported as editable art rather than its editing copy restored, opens on its trim boxes with cropTo and crop omitted and on its crop boxes with cropTo: crop, or crop: crop and no cropTo), password? (encrypted PDFs; see document.pdfInfo), textAs?: text (default: point type per line, lines wrapped in a frame as area type where they lay out the same, in the file's fonts by name; missing ones are listed in warnings) | outlines (glyph paths), layers?: true (default: optional content groups become layers with their visibility, print state and lock — art that is off comes in as a hidden layer; other art goes to a layer per page; a PSD file's layers become layers holding their pixels, with their names, visibility, opacity and blend modes, groups as layers of sublayers, layer masks as opacity masks, clipped layers and layers in blend modes VectorCraft doesn't have merged with the layers below) | false (one layer per page, without the art that is off; Save then asks for a name; a PSD file opens as its merged image), hiddenLayers?: false (a PSD file's hidden layers come in hidden instead of being left out), importSlices?: true (a PSD file's slices become user slices over its canvas, with its layers or its merged image; slices the file generated automatically are left out, and slices that can't be read are left out with a warning), editingData?: true (default: an EPS, .ai or PDF that carries its editor's own copy of the art opens from it, with its layers, hidden objects, guides, artboards and the art outside them; a .ai or PDF whose type shows opens from its PDF part with textAs: outlines) | \"always\" (as true, and a .ai's editing copy is used even where it draws differently from its PDF part, which can be older; the warnings say so) | false (only what its page or PDF part prints, for print pipelines; a .ai saved without PDF compatibility then can't be opened), legacyNameEncoding?: windows-1252 (default) | macintosh | windows-949 (also euc-kr) | shift_jis | gbk | big5 (the code page names in the editing data of a .ai or an EPS are read in when they aren't UTF-8: layers, objects, artboards, colors, gradients, patterns, graphic styles, swatches, brushes, symbols, variables and data sets, and data sets' text values; warnings list the first three such names as read, and count the rest), colorMode?: rgb|cmyk (the mode the document opens in, its colours converted as file.documentColorMode does, through the profiles the document keeps after the color management policies of edit.colorSettings, grays? as there; default: the file's — a PDF keeps CMYK, Gray and spot inks (spot swatches at a tint) and opens in CMYK when painted mostly in CMYK), grays?: as file.documentColorMode, dxf?: {layout?: \"Model\" (default) | a paper layout's name (document.dxfInfo lists them), unit?, scale? (the ratio: 1 unit of the art = scale drawing units; default: the drawing at 1:1 in its own unit), fit?: false (scale to fit an artboard of fitTo?: [612, 792], turned to the art's orientation), scaleLineweights?: false (lineweights scale with the art), center?: true (false: the drawing's origin on the artboard's bottom-left corner; fitted art's bottom-left corner), mergeLayers?: false (all art on one layer)} (DXF), crop?: as cropTo (its older name), linkPages?: false (true: each page `pages` picks of a PDF or PDF-compatible .ai opens as a placed document linked to that page of the file, as file.place with link places one, on an artboard of its cropTo box (bounding: its art's bounds; a blank page: its crop box; a PDF-compatible .ai: its trim box for crop; on its trim box a page shows its bleed box round the artboard and gives the document its bleed), in a row 36 pt apart (on trim boxes, plus the bleed on both sides), and a layer named after the page; links.embed makes a page editable art; refused for any other file, without a path, with a password or with textAs: outlines; Save then asks for a name), profileChoice?: \"useEmbedded\"|\"convert\"|\"discard\" (the profile of the document's color mode is not the working space: keep it, convert that model's colors into the working space and take it off, or take it off and keep the numbers) | \"leave\"|\"assignWorking\"|\"assign\" (the document has no profile of its color mode: leave it untagged, tag it with the working space, or with assignProfile?: a profile of that model) (default: what the model's policy of
Line truncated
|
||||
"{path | name | dataBase64 (a file's path, or its name with its bytes), pages?: \"2-3, 5\" (PDF/.ai: 1-based, default all; one artboard each) | page?: n, cropTo?: bounding|art|crop (default)|trim|bleed|media (the box each artboard gets; bounding: the art's bounds; trim: the bleed box round it becomes the document's bleed, and the artboards are 36 pt apart plus that bleed on both sides; a PDF-compatible file whose first PDF page's PieceInfo holds, in itself or nested up to four dictionaries deep counting PieceInfo, a key starting with AIPrivateData or AIPDFPrivateData, when its pages are imported as editable art rather than its editing copy restored, opens on its trim boxes with cropTo and crop omitted and on its crop boxes with cropTo: crop, or crop: crop and no cropTo), password? (encrypted PDFs; see document.pdfInfo), textAs?: text (default: point type per line, lines wrapped in a frame as area type where they lay out the same, in the file's fonts by name; missing ones are listed in warnings) | outlines (glyph paths), layers?: true (default: optional content groups become layers with their visibility, print state and lock — art that is off comes in as a hidden layer; other art goes to a layer per page; a PSD file's layers become layers holding their pixels, with their names, visibility, opacity and blend modes, groups as layers of sublayers, layer masks as opacity masks, clipped layers and layers in blend modes VectorCraft doesn't have merged with the layers below) | false (one layer per page, without the art that is off; Save then asks for a name; a PSD file opens as its merged image), hiddenLayers?: false (a PSD file's hidden layers come in hidden instead of being left out), importSlices?: true (a PSD file's slices become user slices over its canvas, with its layers or its merged image; slices the file generated automatically are left out, and slices that can't be read are left out with a warning), editingData?: true (default: an EPS, .ai or PDF that carries its editor's own copy of the art opens from it, with its layers, hidden objects, guides, artboards and the art outside them; a .ai or PDF whose type shows opens from its PDF part with textAs: outlines) | \"always\" (as true, and a .ai's editing copy is used even where it draws differently from its PDF part, which can be older; the warnings say so) | false (only what its page or PDF part prints, for print pipelines; a .ai saved without PDF compatibility then can't be opened), legacyNameEncoding?: windows-1252 (default) | macintosh | windows-949 (also euc-kr) | shift_jis | gbk | big5 (the code page names in the editing data of a .ai or an EPS are read in when they aren't UTF-8: layers, objects, artboards, colors, gradients, patterns, graphic styles, swatches, brushes, symbols, variables and data sets, and data sets' text values; warnings list the first three such names as read, and count the rest), colorMode?: rgb|cmyk (the mode the document opens in, its colours converted as file.documentColorMode does, through the profiles the document keeps after the color management policies of edit.colorSettings, grays? as there; default: the file's — a PDF keeps CMYK, Gray and spot inks (spot swatches at a tint) and opens in CMYK when painted mostly in CMYK), grays?: as file.documentColorMode, dxf?: {layout?: \"Model\" (default) | a paper layout's name (document.dxfInfo lists them), unit?, scale? (the ratio: 1 unit of the art = scale drawing units; default: the drawing at 1:1 in its own unit), fit?: false (scale to fit an artboard of fitTo?: [612, 792], turned to the art's orientation), scaleLineweights?: false (lineweights scale with the art), center?: true (false: the drawing's origin on the artboard's bottom-left corner; fitted art's bottom-left corner), mergeLayers?: false (all art on one layer)} (DXF), crop?: as cropTo (its older name), linkPages?: false (true: each page `pages` picks of a PDF or PDF-compatible .ai opens as a placed document linked to that page of the file, as file.place with link places one, on an artboard of its cropTo box (bounding: its art's bounds; a blank page: its crop box; a file with that PieceInfo key: its trim box when no box is named, its crop box with cropTo: crop or crop: crop; on its trim box a page shows its bleed box round the artboard and gives the document its bleed), in a row 36 pt apart (on trim boxes, plus the bleed on both sides), and a layer named after the page; links.embed makes a page editable art; refused for any other file, without a path, with a password or with textAs: outlines; Save then asks for a name), profileChoice?: \"useEmbedded\"|\"convert\"|\"discard\" (the profile of the document's color mode is not the working space: keep it, convert that model's colors into the working space and take it off, or take it off and keep the numbers) | \"leave\"|\"assignWorking\"|\"assign\" (the document has no profile of its color mode: leave it untagged, tag it with the working space, or with assignPro
Line truncated
|
||||
always,
|
||||
load::open
|
||||
),
|
||||
|
||||
@@ -176,8 +176,8 @@ impl LoadOptions {
|
||||
self.pages.is_some() || self.crop != CropTo::default() || self.password.is_some() || !self.layers || !self.native || self.link_pages
|
||||
}
|
||||
|
||||
/// The PDF import options: `pages` resolved against the file's page count. A PDF-compatible
|
||||
/// `.ai`, or a PDF saved with its editing data, opens on its trim boxes by default,
|
||||
/// The PDF import options: `pages` resolved against the file's page count. A PDF or PDF-compatible
|
||||
/// `.ai` with Illustrator private data opens on its trim boxes by default,
|
||||
/// with the bleed around them. An explicit crop-box request uses its crop box.
|
||||
fn import_options(&self, opened: &vectorcraft_pdf::Opened, editor_document: bool) -> Result<ImportOptions> {
|
||||
let pages = match &self.pages {
|
||||
@@ -257,7 +257,7 @@ pub fn pages_can_link(name: &str, bytes: &[u8]) -> bool {
|
||||
/// `.ait`) `name`, read from `path`, as a document holding one placed document per page, linked to
|
||||
/// that page of the file as File › Place with Link places one ([`document::source`]). Each page
|
||||
/// gets an artboard of its `o.crop` box (its art's bounds for `bounding`, a blank page's crop box;
|
||||
/// a PDF-compatible `.ai` asked for its crop box gets its trim box, as it opens), in a row from the
|
||||
/// a PDF-compatible `.ai` that names no box gets its trim box, as it opens), in a row from the
|
||||
/// left with the gap a PDF's artboards open with, and a layer named after the page. On its trim box,
|
||||
/// a page shows its bleed box round the artboard, and the document's bleed is the pages' bleed (the
|
||||
/// widest on each side); the artboards are then the gap apart plus the bleed on both sides. The document opens
|
||||
@@ -289,8 +289,9 @@ pub(super) fn linked_pages(name: &str, bytes: &[u8], path: Option<&str>, o: &Loa
|
||||
Some(range) => parse_range(range, count).map_err(|e| err(format!("pages: {e}")))?,
|
||||
};
|
||||
let bounding = o.crop == CropTo::Bounding;
|
||||
// A PDF-compatible `.ai` asked for its crop box opens on its trim boxes ([`LoadOptions::import_options`]).
|
||||
let crop = if o.crop == CropTo::Crop && opened.has_illustrator_data() { CropTo::Trim } else { o.crop };
|
||||
// A PDF-compatible `.ai` that names no box opens on its trim boxes ([`LoadOptions::import_options`]);
|
||||
// an explicit crop-box request keeps its crop boxes.
|
||||
let crop = if !o.explicit_crop_box && o.crop == CropTo::Crop && opened.has_illustrator_data() { CropTo::Trim } else { o.crop };
|
||||
let mut doc = Document::new(1.0, 1.0);
|
||||
let board = doc.artboards.first().cloned().ok_or_else(|| err("a new document has no artboard"))?;
|
||||
doc.artboards.clear();
|
||||
|
||||
@@ -89,6 +89,8 @@ fn versions_3_and_4_open_and_place_as_editable_art() {
|
||||
assert_eq!(r["format"], "cdr", "{version} {name}");
|
||||
let w: Vec<&str> = r["warnings"].as_array().unwrap().iter().filter_map(|w| w.as_str()).collect();
|
||||
assert!(w.iter().any(|w| w.contains("text, bitmaps")) && !w.iter().any(|w| w.contains("damaged")), "{version}: {w:?}");
|
||||
// The reader opens PowerClip frames from version 4 on.
|
||||
assert_eq!(w.iter().any(|w| w.contains("PowerClip")), version >= 400, "{version}: {w:?}");
|
||||
}
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
assert_eq!((doc.artboards[0].rect.width().round(), doc.artboards[0].rect.height().round()), (612.0, 792.0), "{version}");
|
||||
@@ -535,6 +537,35 @@ fn containers_open_as_clipping_groups() {
|
||||
assert!(children[1..].iter().all(|n| matches!(n.kind, NodeKind::Path { clipping: false, .. })));
|
||||
}
|
||||
|
||||
/// A container whose clipped group holds only objects the reader leaves out (a bitmap here), or
|
||||
/// whose group holds a container of that same group, opens as a plain shape, and the warnings
|
||||
/// say that such frames opened empty.
|
||||
#[test]
|
||||
fn containers_whose_contents_were_left_out_are_named_in_the_warnings() {
|
||||
let v = V(1100);
|
||||
let rect = |w: f64, extra: Vec<(u32, Vec<u8>)>| {
|
||||
let mut args = vec![(30, v.rect(w, w, 0.0))];
|
||||
args.extend(extra);
|
||||
synth::object(v, 1, &args, None)
|
||||
};
|
||||
let open = |clipped: Vec<synth::Node>| {
|
||||
let doc = list(b"doc ", vec![synth::clpt(vec![(5, clipped)])]);
|
||||
let page = synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![rect(40.0, vec![synth::container(5)])])]);
|
||||
super::cdr::import(&synth::riff(1100, &[chunk(b"vrsn", 1100u16.to_le_bytes().to_vec()), doc, page])).unwrap()
|
||||
};
|
||||
let frames = "PowerClip frames whose contents were left out opened empty";
|
||||
let (doc, warnings) = open(vec![synth::object(v, 5, &[(30, v.rect(10.0, 10.0, 0.0))], None)]);
|
||||
let p = paths(&doc);
|
||||
let [frame] = p.as_slice() else { panic!("{p:?}") };
|
||||
assert!(matches!(frame.kind, NodeKind::Path { clipping: false, .. }), "{:?}", frame.kind);
|
||||
assert!(warnings.iter().any(|w| w.contains("text, bitmaps")), "{warnings:?}");
|
||||
assert!(warnings.iter().any(|w| w.contains(frames)), "{warnings:?}");
|
||||
// The inner container names the group already being read, so it is left out at the limit.
|
||||
let (_, warnings) = open(vec![rect(10.0, vec![synth::container(5)])]);
|
||||
assert!(warnings.iter().any(|w| w.contains("past the import limits")), "{warnings:?}");
|
||||
assert!(warnings.iter().any(|w| w.contains(frames)), "{warnings:?}");
|
||||
}
|
||||
|
||||
/// An object with a lens or transparency opens opaque, and the warnings say so.
|
||||
#[test]
|
||||
fn lenses_and_transparency_are_named_in_the_warnings() {
|
||||
|
||||
@@ -377,6 +377,11 @@ impl DocSettings {
|
||||
/// `artboardLayout: {layout?, columns?, rows?, spacing?, rightToLeft?}` or just a layout id.
|
||||
fn layout_params(&mut self, l: &Value, cmd: &str, replaying: bool) -> Result<()> {
|
||||
let bad_layout = || bad(cmd, "artboardLayout.layout must be gridByRow, gridByColumn, row or column");
|
||||
// The columns that rows give the artboards as they are now, which a layout that replaces the
|
||||
// rows without its own `columns` keeps.
|
||||
if self.grid_rows().is_some() {
|
||||
self.columns = u32::try_from(self.grid_columns()).unwrap_or(u32::MAX);
|
||||
}
|
||||
if let Some(id) = l.as_str() {
|
||||
self.layout = ArtboardLayout::parse(id).ok_or_else(bad_layout)?;
|
||||
if self.layout != ArtboardLayout::GridByColumn {
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -32,7 +32,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Run Script",
|
||||
[],
|
||||
None,
|
||||
"{path?: a script file (.js, .mjs or .jsx) | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), module?: true or false (default true for a path ending in .mjs, false otherwise; true runs the file or source as a .mjs file runs, as a module, and a source run this way imports no files), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt|window, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt) | [{control, event: click} | {control, event: change, value: text, number, item index or null} | {event: close}] (window: the steps of one show(), control being a control's name, or the text of a control without a name)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), actions?: [{set, name, steps: [{command, params?, step?: the step's place in the action, a whole number from 1 (default its place in the list)}]}] (the actions app.doScript(action, set, dialogs?) plays, matched by their exact names; a command.batch step gives its own steps; at most 4096 actions, 10000 steps an action, 100000 steps in all and 16 MiB as JSON; in the app, the Actions panel's actions with their included steps, which a caller's list replaces), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); Document.rasterize, Document.imageCapture, Document.saveAs and Document.exportFile forward command warnings to the Script Console with the method name; app.open reads ancillary files only within the script's read grants, without inherited link permissions; $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), an absolute path in a File's URI notation is read too, with escapes decoded and /c/... naming drive C: on Windows, $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; new Window(\"dialog\", title) builds a ScriptUI dialog with add(type, bounds, text or items or value, properties) for group, panel, statictext, edittext, button, checkbox, radiobutton, dropdownlist, listbox (one selection), slider and progressbar (a group takes properties third, or fourth after a third that is not an object, and a list may take them there with properties.items), at most 512 controls 16 deep, 1024 list items and 16 KiB a text (other types and windows throw that they are not available yet); new Window and add also take a resource string such as \"dialog { g: Group { b: Button { text: 'OK' } } }\" in place of the type, which adds each control it lists through add and sets it and each other value as the property of its name (properties gives the creation properti
Line truncated
|
||||
"{path?: a script file (.js, .mjs or .jsx) | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), module?: true or false (default true for a path ending in .mjs, false otherwise; true runs the file or source as a .mjs file runs, as a module, and a source run this way imports no files), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt|window|colorPicker, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt) | [{control, event: click} | {control, event: change, value: text, number, item index or null} | {event: close}] (window: the steps of one show(), control being a control's name, or the text of a control without a name) | a color as paint.setFill takes it, with each component in its range (a color key such as \"rgb 300 0 0\" is refused, not clamped), or null (colorPicker)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), actions?: [{set, name, steps: [{command, params?, step?: the step's place in the action, a whole number from 1 (default its place in the list)}]}] (the actions app.doScript(action, set, dialogs?) plays, matched by their exact names; a command.batch step gives its own steps; at most 4096 actions, 10000 steps an action, 100000 steps in all and 16 MiB as JSON; in the app, the Actions panel's actions with their included steps, which a caller's list replaces), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); Document.rasterize, Document.imageCapture, Document.saveAs and Document.exportFile forward command warnings to the Script Console with the method name; app.open reads ancillary files only within the script's read grants, without inherited link permissions; $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), an absolute path in a File's URI notation is read too, with escapes decoded and /c/... naming drive C: on Windows, $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; app.showColorPicker(color) opens the Color Picker on an RGBColor, CMYKColor, GrayColor or LabColor (anything else throws a TypeError) and returns the color picked for OK (in the app an RGB pick is CMYK when the run's active document is CMYK), or a new object of the color given for Cancel and for OK with both the color and its model unchanged; it waits and takes answers as the dialogs above do, and has no Stop button; new Window(\"dialog\", title) builds a ScriptUI dialog with add(type, bounds, text or items or value, properties) for group, panel, statictext, edittext, button, checkbox, radiobutton, dropdownlist,
Line truncated
|
||||
always,
|
||||
run
|
||||
),
|
||||
@@ -77,7 +77,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Script Palette Event",
|
||||
[],
|
||||
None,
|
||||
"{palette: an id script.palettes lists, event: click|change|close, control?: a control (its index, name or text; click and change), value?: the new value (an edit field's text, a slider's number, or a list's item index or null; change)} give a shown palette a click, a change or a close, as the person does: it runs as a run of its own in the palette's engine, with its report like script.run's, once no run is going, oldest first; a newer click on the same control, change of it or close of the same palette replaces the most recent waiting event of that kind for that control or palette only when it has the same file access roots; otherwise the new event waits at the end of the line (merged: false); a click or close takes its place only if no change of its palette waits after it, and a change only if no click or close of its palette waits after it, otherwise it waits as a new event (merged: false); a list's change ends its run with an error when a script added or removed the list's items, or changed an item's text, by then, even if the list again holds the same texts; dialogs throw in the handler in the app, and with nobody to ask the run ends at one; a hidden palette, a control that is disabled, hidden or cannot take the event, and a 65th waiting event are refused, and with nobody to ask so is an event while an undo group or a drag in a document other than the active one is open → in the app {waiting: true, merged: whether it took the place of a waiting event, waitingEvents}, and the report later in ui.inspect's scriptReport; with nobody to ask, the waiting events run in order and the answer is the report of the run that handled this event (or its error): its own run, or a run of the same engine whose own code took it with update(), which gives it no report or undo step of its own; an event dropped without a run, because an earlier handler disabled, hid or removed its control or hid or closed its palette, ends with an error; an event whose run starts and finds its control, or a group above it, disabled or hidden by a getter read for the palette, or whose `enabled` or `visible` state a getter gives, runs no handler",
|
||||
"{palette: an id script.palettes lists, event: click|change|close, control?: a control (its index, name or text; click and change), value?: the new value (an edit field's text, a slider's number, or a list's item index or null; change)} give a shown palette a click, a change or a close, as the person does: it runs as a run of its own in the palette's engine, with its report like script.run's, once no run is going, oldest first; a newer click on the same control, change of it or close of the same palette replaces the most recent waiting event of that kind for that control or palette only when it has the same file access roots; otherwise the new event waits at the end of the line (merged: false); a click or close takes its place only if no change of its palette waits after it, and a change only if no click or close of its palette waits after it, otherwise it waits as a new event (merged: false); a list's change ends its run with an error when a script added or removed the list's items, or changed an item's text, by then, even if the list again holds the same texts; dialogs throw in the handler in the app, and with nobody to ask the run ends at one; a hidden palette, a control that is disabled, hidden or cannot take the event, and a 65th waiting event are refused, and with nobody to ask so is an event while an undo group or a drag in a document other than the active one is open → in the app {waiting: true, merged: whether it took the place of a waiting event, waitingEvents}, and the report later in ui.inspect's scriptReport; when a waiting event's run cannot begin in the app, the status bar shows the error and the events in line wait until the next input in the window, another script.palette.event, or a change to a document's unsaved state, drag or undo group, to the active document, or to the recoveryFolder or recoveryOffForComplex preference; with nobody to ask, the waiting events run in order and the answer is the report of the run that handled this event (or its error): its own run, or a run of the same engine whose own code took it with update(), which gives it no report or undo step of its own; an event dropped without a run, because an earlier handler disabled, hid or removed its control or hid or closed its palette, ends with an error; an event whose run starts and finds its control, or a group above it, disabled or hidden by a getter read for the palette, or whose `enabled` or `visible` state a getter gives, runs no handler",
|
||||
always,
|
||||
palette_event
|
||||
),
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -5,12 +5,14 @@
|
||||
//! it is left out or `undefined` ([`DEFAULT_TITLE`]), and `errorIcon` and `noAsDflt` as the
|
||||
//! boolean `Boolean(value)` gives. `alert` returns `undefined`, `confirm` `true` for Yes and
|
||||
//! `false` for No, and `prompt` the text in its field for OK and `null` for Cancel.
|
||||
//! `app.showColorPicker(color)` ([`show_color_picker`]) opens the Color Picker on a color and
|
||||
//! returns the color picked for OK, or a new object of the color it was given for Cancel.
|
||||
//!
|
||||
//! In the app the run waits at the call for the person's answer, and spends no fuel while it
|
||||
//! waits; every dialog also has Stop, which ends the run and puts everything back. A run with
|
||||
//! nobody to ask takes its answers, in order, from `script.run`'s `answers`; a call with no
|
||||
//! answer left, or with the next answer for another kind of dialog, ends the run. The report's
|
||||
//! `dialogs` lists each dialog and its answer.
|
||||
//! waits; every dialog but the Color Picker also has Stop, which ends the run and puts
|
||||
//! everything back. A run with nobody to ask takes its answers, in order, from `script.run`'s
|
||||
//! `answers`; a call with no answer left, or with the next answer for another kind of dialog,
|
||||
//! ends the run. The report's `dialogs` lists each dialog and its answer.
|
||||
//!
|
||||
//! The values here are VectorCraft's own limits: [`MAX_MESSAGE_BYTES`], [`MAX_TITLE_BYTES`],
|
||||
//! [`MAX_PROMPT_BYTES`], [`MAX_ANSWERS`], [`MAX_ANSWERS_BYTES`], [`MAX_RECORDS`] and
|
||||
@@ -21,6 +23,7 @@ use std::collections::VecDeque;
|
||||
use std::rc::Rc;
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
use vectorcraft_color::Color;
|
||||
use vectorcraft_js::{Arg, Data, HostError, HostFunction, LimitKind, Realm, RunError, RunErrorKind};
|
||||
|
||||
use super::scriptui::{self, ScriptUiDialog, Showing, UiEvent, UiStep};
|
||||
@@ -51,22 +54,34 @@ pub enum DialogKind {
|
||||
Prompt,
|
||||
/// A ScriptUI dialog's `show()` ([`super::scriptui`]).
|
||||
Window,
|
||||
/// `app.showColorPicker`.
|
||||
ColorPicker,
|
||||
}
|
||||
|
||||
impl DialogKind {
|
||||
/// The function's name, which is also the `kind` of an answer and of a report's dialog.
|
||||
/// The `kind` of an answer and of a report's dialog, which is also the function's name for
|
||||
/// `alert`, `confirm` and `prompt`.
|
||||
pub fn id(self) -> &'static str {
|
||||
match self {
|
||||
Self::Alert => "alert",
|
||||
Self::Confirm => "confirm",
|
||||
Self::Prompt => "prompt",
|
||||
Self::Window => "window",
|
||||
Self::ColorPicker => "colorPicker",
|
||||
}
|
||||
}
|
||||
|
||||
/// The function's name, as its errors give it.
|
||||
fn function(self) -> &'static str {
|
||||
match self {
|
||||
Self::ColorPicker => "showColorPicker",
|
||||
k => k.id(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A dialog a script opened, which waits for its answer.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct ScriptDialog {
|
||||
pub kind: DialogKind,
|
||||
pub message: String,
|
||||
@@ -78,10 +93,15 @@ pub struct ScriptDialog {
|
||||
pub no_as_default: bool,
|
||||
/// `prompt`: the text its field starts with.
|
||||
pub preset: String,
|
||||
/// `showColorPicker`: the color the picker starts with. `None` for the other dialogs.
|
||||
pub color: Option<Color>,
|
||||
/// `showColorPicker`: the run's active document is in CMYK when the picker opens, so the app
|
||||
/// gives an RGB pick back as CMYK. False for the other dialogs.
|
||||
pub cmyk_document: bool,
|
||||
}
|
||||
|
||||
/// The answer to a [`ScriptDialog`].
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum DialogAnswer {
|
||||
/// OK, for `alert`.
|
||||
Ok,
|
||||
@@ -91,6 +111,8 @@ pub enum DialogAnswer {
|
||||
Prompt(Option<String>),
|
||||
/// What happens in a ScriptUI dialog, step by step, for a run with nobody to ask.
|
||||
Window(Vec<UiStep>),
|
||||
/// OK with the color picked, or Cancel (`None`), for `showColorPicker`.
|
||||
ColorPicker(Option<Color>),
|
||||
}
|
||||
|
||||
impl DialogAnswer {
|
||||
@@ -100,30 +122,101 @@ impl DialogAnswer {
|
||||
Self::Confirm(_) => DialogKind::Confirm,
|
||||
Self::Prompt(_) => DialogKind::Prompt,
|
||||
Self::Window(_) => DialogKind::Window,
|
||||
Self::ColorPicker(_) => DialogKind::ColorPicker,
|
||||
}
|
||||
}
|
||||
|
||||
/// What the function returns.
|
||||
fn data(&self) -> Data {
|
||||
/// What the function returns for dialog `d`: for Cancel in the Color Picker, the color it
|
||||
/// started with.
|
||||
fn data(&self, d: &ScriptDialog) -> Data {
|
||||
match self {
|
||||
Self::Ok | Self::Window(_) => Data::Undefined,
|
||||
Self::Confirm(b) => Data::Bool(*b),
|
||||
Self::Prompt(Some(t)) => Data::String(t.clone()),
|
||||
Self::Prompt(None) => Data::Null,
|
||||
Self::ColorPicker(picked) => picked.or(d.color).as_ref().map_or(Data::Null, super::dom::color_data),
|
||||
}
|
||||
}
|
||||
|
||||
/// The answer as a report gives it: `"ok"`, a boolean, a string or `null`.
|
||||
/// The answer as a report gives it: `"ok"`, a boolean, a string, a color as the paint commands
|
||||
/// take it, or `null`.
|
||||
fn json(&self) -> Value {
|
||||
match self {
|
||||
Self::Ok => json!("ok"),
|
||||
Self::Confirm(b) => json!(b),
|
||||
Self::Prompt(t) => json!(t),
|
||||
Self::Window(steps) => json!(steps.len()),
|
||||
Self::ColorPicker(c) => c.as_ref().map_or(Value::Null, color_json),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `c` as the paint commands take it.
|
||||
fn color_json(c: &Color) -> Value {
|
||||
serde_json::to_value(c).unwrap_or(Value::Null)
|
||||
}
|
||||
|
||||
/// Are `c`'s components in their ranges: 0 to 1, and for Lab, L from 0 to 100 and a and b from
|
||||
/// -128 to 128, as a script's `LabColor` takes them?
|
||||
fn in_range(c: &Color) -> bool {
|
||||
let unit = |v: &[f32]| v.iter().all(|x| (0.0..=1.0).contains(x));
|
||||
match *c {
|
||||
Color::Rgb { r, g, b } => unit(&[r, g, b]),
|
||||
Color::Cmyk { c, m, y, k } => unit(&[c, m, y, k]),
|
||||
Color::Gray { k } => unit(&[k]),
|
||||
Color::Lab { l, a, b } => (0.0..=100.0).contains(&l) && [a, b].iter().all(|x| (-128.0..=128.0).contains(x)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The color of a `colorPicker` answer, each component in its range ([`in_range`]). A color key
|
||||
/// such as `"rgb 300 0 0"` is checked as written, since reading it as a key puts its components
|
||||
/// into their ranges. An array or object is checked as written too, in f64 and with the scale
|
||||
/// [`crate::cmd::color_value`] reads it in, so that a component just past a limit is not rounded
|
||||
/// onto it when it narrows to f32.
|
||||
fn answer_color(v: &Value) -> Option<Color> {
|
||||
// Parsed as f64, so that a value just past a limit is not rounded onto it.
|
||||
let within = |v: &[f64], lo: f64, hi: f64| v.iter().all(|x| (lo..=hi).contains(x));
|
||||
let num = |o: &serde_json::Map<String, Value>, key: &str| o.get(key).and_then(Value::as_f64);
|
||||
let written_in_range = match v {
|
||||
Value::String(s) if Color::from_hex(s).is_none() => {
|
||||
let mut it = s.split_whitespace();
|
||||
let model = it.next()?.to_ascii_lowercase();
|
||||
let n: Vec<f64> = it.map(|t| t.parse::<f64>().ok().filter(|x| x.is_finite())).collect::<Option<_>>()?;
|
||||
match (model.as_str(), n.as_slice()) {
|
||||
("rgb", [_, _, _]) => within(&n, 0.0, 255.0),
|
||||
("cmyk", [_, _, _, _]) | ("gray", [_]) => within(&n, 0.0, 100.0),
|
||||
("lab", [l, a, b]) => within(&[*l], 0.0, 100.0) && within(&[*a, *b], -128.0, 128.0),
|
||||
_ => return None,
|
||||
}
|
||||
}
|
||||
Value::Array(a) if a.len() >= 3 => within(&[a[0].as_f64()?, a[1].as_f64()?, a[2].as_f64()?], 0.0, 1.0),
|
||||
Value::Object(o) => {
|
||||
if let (Some(c), Some(m), Some(y), Some(k)) = (num(o, "c"), num(o, "m"), num(o, "y"), num(o, "k")) {
|
||||
let scale = if [c, m, y, k].iter().any(|x| *x > 1.0) { 100.0 } else { 1.0 };
|
||||
within(&[c, m, y, k], 0.0, scale)
|
||||
} else if let Some(g) = o.get("gray") {
|
||||
let g = g.as_f64()?;
|
||||
within(&[if g > 1.0 { g / 100.0 } else { g }], 0.0, 1.0)
|
||||
} else if let (Some(l), Some(a), Some(b), None) = (num(o, "l"), num(o, "a"), num(o, "b"), o.get("model")) {
|
||||
within(&[l], 0.0, 100.0) && within(&[a, b], -128.0, 128.0)
|
||||
} else {
|
||||
match o.get("model").and_then(Value::as_str) {
|
||||
Some("rgb") => within(&[num(o, "r")?, num(o, "g")?, num(o, "b")?], 0.0, 1.0),
|
||||
Some("cmyk") => within(&[num(o, "c")?, num(o, "m")?, num(o, "y")?, num(o, "k")?], 0.0, 1.0),
|
||||
Some("gray") => within(&[num(o, "k")?], 0.0, 1.0),
|
||||
Some("lab") => within(&[num(o, "l")?], 0.0, 100.0) && within(&[num(o, "a")?, num(o, "b")?], -128.0, 128.0),
|
||||
_ => true,
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => true,
|
||||
};
|
||||
if !written_in_range {
|
||||
return None;
|
||||
}
|
||||
crate::cmd::color_value(v).filter(in_range)
|
||||
}
|
||||
|
||||
/// `text` as a dialog shows it. With `lines`, a line feed, a carriage return or the two together
|
||||
/// is a line break; every other control character, and with `lines` false every line break too,
|
||||
/// shows as its Unicode Control Picture, as the Script Console shows it.
|
||||
@@ -156,9 +249,10 @@ pub fn cut_to(text: &str, max: usize) -> &str {
|
||||
}
|
||||
|
||||
/// `script.run`'s `answers`: a list of `{kind: "alert", value: "ok"}`, `{kind: "confirm", value:
|
||||
/// true | false}`, `{kind: "prompt", value: text | null}` and `{kind: "window", value: [step, ...]}`
|
||||
/// ([`super::scriptui`]). An empty object, which the parameter took before dialogs existed, is an
|
||||
/// empty list.
|
||||
/// true | false}`, `{kind: "prompt", value: text | null}`, `{kind: "window", value: [step, ...]}`
|
||||
/// ([`super::scriptui`]) and `{kind: "colorPicker", value: color | null}`, the color in any form
|
||||
/// the paint commands take. An empty object, which the parameter took before dialogs existed, is
|
||||
/// an empty list.
|
||||
pub(crate) fn parse_answers(v: Option<&Value>) -> Result<Vec<DialogAnswer>, String> {
|
||||
let list = match v {
|
||||
None => return Ok(Vec::new()),
|
||||
@@ -196,7 +290,12 @@ fn known_answer(o: &Map<String, Value>) -> Result<DialogAnswer, &'static str> {
|
||||
(Some("prompt"), Value::String(s)) if s.len() <= MAX_PROMPT_BYTES => Ok(DialogAnswer::Prompt(Some(s.clone()))),
|
||||
(Some("prompt"), Value::String(_)) => Err("is longer than 16 KiB"),
|
||||
(Some("prompt"), _) => Err("is a prompt's answer, whose `value` must be a string or null"),
|
||||
_ => Err("must have `kind` alert, confirm, prompt or window"),
|
||||
(Some("colorPicker"), Value::Null) => Ok(DialogAnswer::ColorPicker(None)),
|
||||
(Some("colorPicker"), v) => match answer_color(v) {
|
||||
Some(c) => Ok(DialogAnswer::ColorPicker(Some(c))),
|
||||
None => Err("is a color picker's answer, whose `value` must be a color or null"),
|
||||
},
|
||||
_ => Err("must have `kind` alert, confirm, prompt, window or colorPicker"),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -465,9 +564,10 @@ impl Dialogs {
|
||||
}
|
||||
let Some(d) = waiting.take() else { return false };
|
||||
drop(waiting);
|
||||
let data = answer.data(&d);
|
||||
let on_yes = self.on_yes.take();
|
||||
// A confirm the app opened returns `undefined` to the call that opened it.
|
||||
let data = if on_yes.is_some() { Data::Undefined } else { answer.data() };
|
||||
let data = if on_yes.is_some() { Data::Undefined } else { data };
|
||||
if answer == DialogAnswer::Confirm(true) {
|
||||
self.approved.set(on_yes);
|
||||
}
|
||||
@@ -523,13 +623,16 @@ impl Dialogs {
|
||||
fn record(&self, d: &ScriptDialog, answer: Value) {
|
||||
let mut r = Map::new();
|
||||
r.insert("kind".into(), json!(d.kind.id()));
|
||||
r.insert("message".into(), json!(d.message));
|
||||
r.insert("title".into(), json!(d.title.as_deref().unwrap_or(DEFAULT_TITLE)));
|
||||
if d.kind != DialogKind::ColorPicker {
|
||||
r.insert("message".into(), json!(d.message));
|
||||
r.insert("title".into(), json!(d.title.as_deref().unwrap_or(DEFAULT_TITLE)));
|
||||
}
|
||||
match d.kind {
|
||||
DialogKind::Alert => r.insert("errorIcon".into(), json!(d.error_icon)),
|
||||
DialogKind::Confirm => r.insert("noAsDefault".into(), json!(d.no_as_default)),
|
||||
DialogKind::Prompt => r.insert("preset".into(), json!(d.preset)),
|
||||
DialogKind::Window => None,
|
||||
DialogKind::ColorPicker => r.insert("color".into(), d.color.as_ref().map_or(Value::Null, color_json)),
|
||||
};
|
||||
r.insert("answer".into(), answer);
|
||||
self.push_record(Value::Object(r));
|
||||
@@ -584,7 +687,8 @@ fn open(host: &Host, kind: DialogKind, args: &[Data]) -> Result<Data, HostError>
|
||||
host.charge_call(args.iter().map(super::data_size).sum())?;
|
||||
let Some(message) = text(args, 0) else { return Err(HostError::Type(format!("{name}: give a message"))) };
|
||||
let (title, error_icon, no_as_default, preset) = match kind {
|
||||
DialogKind::Alert => (text(args, 1), flag(args, 2), false, String::new()),
|
||||
// `showColorPicker` opens through `show_color_picker`, not here.
|
||||
DialogKind::Alert | DialogKind::ColorPicker => (text(args, 1), flag(args, 2), false, String::new()),
|
||||
DialogKind::Confirm => (text(args, 2), false, flag(args, 1), String::new()),
|
||||
DialogKind::Prompt => {
|
||||
let Some(preset) = text(args, 1) else { return Err(HostError::Type(format!("{name}: give the text the field starts with"))) };
|
||||
@@ -601,7 +705,33 @@ fn open(host: &Host, kind: DialogKind, args: &[Data]) -> Result<Data, HostError>
|
||||
if preset.len() > MAX_PROMPT_BYTES {
|
||||
return Err(HostError::Range(format!("{name}: the text the field starts with is longer than 16 KiB")));
|
||||
}
|
||||
let dialog = ScriptDialog { kind, message, title, error_icon, no_as_default, preset };
|
||||
wait_or_answer(host, ScriptDialog { kind, message, title, error_icon, no_as_default, preset, color: None, cmyk_document: false })
|
||||
}
|
||||
|
||||
/// `app.showColorPicker(color)`: the Color Picker on `color`. It returns the color picked for OK,
|
||||
/// and a new object of `color` for Cancel.
|
||||
pub(super) fn show_color_picker(host: &Host, color: Color) -> Result<Data, HostError> {
|
||||
// During a slice the session holds the run's working copy, whose active document may be one
|
||||
// the script made; between slices the app sees the documents as they were before the run.
|
||||
let cmyk_document = host.session.borrow().active().is_some_and(|s| s.doc.color_mode == crate::doc::ColorMode::Cmyk);
|
||||
let dialog = ScriptDialog {
|
||||
kind: DialogKind::ColorPicker,
|
||||
message: String::new(),
|
||||
title: None,
|
||||
error_icon: false,
|
||||
no_as_default: false,
|
||||
preset: String::new(),
|
||||
color: Some(color),
|
||||
cmyk_document,
|
||||
};
|
||||
wait_or_answer(host, dialog)
|
||||
}
|
||||
|
||||
/// Opens `dialog`: in the app the run waits at it, and a run with nobody to ask takes the next of
|
||||
/// `answers`.
|
||||
fn wait_or_answer(host: &Host, dialog: ScriptDialog) -> Result<Data, HostError> {
|
||||
let kind = dialog.kind;
|
||||
let name = kind.function();
|
||||
let d = &host.dialogs;
|
||||
if d.framed {
|
||||
if !d.can_wait.get() {
|
||||
@@ -616,11 +746,11 @@ fn open(host: &Host, kind: DialogKind, args: &[Data]) -> Result<Data, HostError>
|
||||
match next {
|
||||
Some(a) if a.kind() == kind => {
|
||||
d.record(&dialog, a.json());
|
||||
Ok(a.data())
|
||||
Ok(a.data(&dialog))
|
||||
}
|
||||
Some(a) => {
|
||||
d.record(&dialog, json!("missing"));
|
||||
Err(HostError::Abort(format!("{name}: the next answer in `answers` is for {}, not {name}", a.kind().id())))
|
||||
Err(HostError::Abort(format!("{name}: the next answer in `answers` is for {}, not {}", a.kind().id(), kind.id())))
|
||||
}
|
||||
None => {
|
||||
d.record(&dialog, json!("missing"));
|
||||
|
||||
@@ -117,6 +117,7 @@ mod tracing;
|
||||
mod transform;
|
||||
mod variables;
|
||||
|
||||
pub(super) use colors::of_color as color_data;
|
||||
#[cfg(test)]
|
||||
pub(crate) use paths::POINT_LOOKS;
|
||||
|
||||
@@ -1155,6 +1156,13 @@ fn app_set_coords(h: &Host, a: &[Data]) -> Answer {
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
/// `app.showColorPicker(color)`: the Color Picker on `color`, which must be an `RGBColor`,
|
||||
/// `CMYKColor`, `GrayColor` or `LabColor` ([`super::dialogs::show_color_picker`]).
|
||||
fn app_show_color_picker(h: &Host, a: &[Data]) -> Answer {
|
||||
let color = colors::solid(arg(a, 1), "showColorPicker's color")?;
|
||||
super::dialogs::show_color_picker(h, color)
|
||||
}
|
||||
|
||||
/// A path as `getIsFileOpen` compares it. A Windows path (any path on Windows, or one that starts
|
||||
/// with a drive letter) takes `\` and `/` alike and letters in one case. On other systems `\` is a
|
||||
/// character of a file name, so `/work/a\b.ai` and `/work/a/b.ai` are different files.
|
||||
@@ -3381,6 +3389,7 @@ fn classes(link: &Link) -> Vec<HostClass> {
|
||||
("selection", property(l, app_selection, app_set_selection), typed("*")),
|
||||
("coordinateSystem", property(l, app_coords, app_set_coords), typed("CoordinateSystem")),
|
||||
("getIsFileOpen", method(l, app_is_open), returns("boolean", &[("filePath", "string")])),
|
||||
("showColorPicker", method(l, app_show_color_picker), returns("Color", &[("color", "Color")])),
|
||||
("redraw", method(l, app_redraw), returns("undefined", &[])),
|
||||
("selectTool", method(l, app_select_tool), returns("boolean", &[("toolName", "string")])),
|
||||
("undo", method(l, app_undo), returns("undefined", &[])),
|
||||
|
||||
@@ -13,7 +13,10 @@
|
||||
//! VectorCraft's own rules, which the help pages do not state: components left out count as 0;
|
||||
//! `new cmykColor()` is the same as `new CMYKColor()`; `LabColor.l` is 0 to 100 and `a` and `b`
|
||||
//! are -128 to 128. `GrayColor.gray` runs from 0 (black) to 100 (white), as the GrayColor page
|
||||
//! says. `GradientColor`, `SpotColor` and `PatternColor` can be read from an object but not
|
||||
//! says. A color read from an object gives that object the same color when it is assigned back.
|
||||
//! A gray within about 1e-14 % of white reads as 100, since one number cannot hold it; assigning it
|
||||
//! to a fill or stroke whose gray also reads as 100 leaves that paint as it is, and assigning it to
|
||||
//! any other paint gives white. `GradientColor`, `SpotColor` and `PatternColor` can be read from an object but not
|
||||
//! assigned yet.
|
||||
|
||||
use std::rc::Rc;
|
||||
@@ -66,7 +69,7 @@ fn shown(v: f32, scale: f64) -> f64 {
|
||||
}
|
||||
|
||||
/// The color object for a solid color.
|
||||
fn of_color(c: &Color) -> Data {
|
||||
pub(in crate::script) fn of_color(c: &Color) -> Data {
|
||||
match *c {
|
||||
Color::Rgb { r, g, b } => color_object("RGBColor", &[("red", shown(r, 255.0)), ("green", shown(g, 255.0)), ("blue", shown(b, 255.0))]),
|
||||
Color::Cmyk { c, m, y, k } => color_object(
|
||||
@@ -149,6 +152,18 @@ pub(super) fn assigned(d: &Data, what: &str) -> std::result::Result<Option<Color
|
||||
}))
|
||||
}
|
||||
|
||||
/// The solid color a script gave `what`, checked as [`assigned`] checks it: a `NoColor`, a
|
||||
/// `GradientColor`, a `SpotColor` or a `PatternColor` throws a `TypeError`.
|
||||
pub(super) fn solid(d: &Data, what: &str) -> std::result::Result<Color, HostError> {
|
||||
let not_solid = || HostError::Type(format!("{what} must be an RGBColor, CMYKColor, GrayColor or LabColor"));
|
||||
match assigned(d, what) {
|
||||
Ok(Some(c)) => Ok(c),
|
||||
// A NoColor, or one of the LATER classes, which `assigned` refuses with a plain error.
|
||||
Ok(None) | Err(HostError::Error(_)) => Err(not_solid()),
|
||||
Err(e) => Err(e),
|
||||
}
|
||||
}
|
||||
|
||||
/// `color` as `paint.setFill` and `paint.setStroke` take it.
|
||||
pub(super) fn param(color: &Color) -> Value {
|
||||
serde_json::to_value(color).unwrap_or(Value::Null)
|
||||
|
||||
@@ -839,7 +839,8 @@ fn art_index(h: &Host, a: &[Data], kind: Kind) -> Answer {
|
||||
/// `removeAll()`: deletes every object the collection lists (those inside another listed one go
|
||||
/// with it) in one command. A hidden or locked one, one in a hidden or locked layer or group, or
|
||||
/// one on a locked artboard stops it before anything is deleted, as the document's
|
||||
/// `pageItems.removeAll()` is stopped.
|
||||
/// `pageItems.removeAll()` is stopped, and so does an image the deletion would leave first in an
|
||||
/// ordinary group named as a tracing.
|
||||
fn art_remove_all(h: &Host, a: &[Data], kind: Kind) -> Answer {
|
||||
let (doc, c) = art_scope(h, arg(a, 0), kind.class())?;
|
||||
let (ids, refused, on_locked, masks) = with_doc(h, doc, |_, st| {
|
||||
|
||||
@@ -170,6 +170,8 @@ fn path_ref(h: &super::Host, item: Item) -> Data {
|
||||
|
||||
/// 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)]
|
||||
crate::script::LAYOUTS_BUILT.with(|n| n.set(n.get() + 1));
|
||||
let mut out = Vec::with_capacity(subs.len() + 1);
|
||||
let mut n = 0;
|
||||
for sp in subs {
|
||||
@@ -1902,18 +1904,17 @@ fn path_selected_points(h: &super::Host, a: &[Data]) -> Answer {
|
||||
.filter_map(|&(s, i)| pd.subpaths.get(s).filter(|sp| !sp.anchors.is_empty()).map(|sp| [(s, i), (s, (i + 1) % sp.anchors.len())]))
|
||||
.flatten()
|
||||
.collect();
|
||||
let partial = sel.partial(item.id).filter(|_| !held);
|
||||
let mut picked = Vec::new();
|
||||
let mut offset = 0;
|
||||
for (s, sp) in pd.subpaths.iter().enumerate() {
|
||||
for j in 0..sp.anchors.len() {
|
||||
if partial.is_none_or(|a| a.contains(&(s, j)) && !ends.contains(&(s, j))) {
|
||||
picked.push(offset + j);
|
||||
}
|
||||
}
|
||||
offset += sp.anchors.len();
|
||||
let firsts = starts(&pd.subpaths);
|
||||
match sel.partial(item.id).filter(|_| !held) {
|
||||
// Direct-selected anchors that no selected segment ends at, in subpath and anchor
|
||||
// order, which is the order of `pathPoints`.
|
||||
Some(anchors) => anchors
|
||||
.iter()
|
||||
.filter(|&&(s, j)| pd.subpaths.get(s).is_some_and(|sp| j < sp.anchors.len()) && !ends.contains(&(s, j)))
|
||||
.filter_map(|(s, j)| firsts.get(*s).map(|first| first + j))
|
||||
.collect(),
|
||||
None => (0..firsts.last().copied().unwrap_or(0)).collect(),
|
||||
}
|
||||
picked
|
||||
})?;
|
||||
h.charge_call(picked.len() as u64)?;
|
||||
let points = picked.into_iter().map(|i| point_ref(h, item, i)).collect();
|
||||
|
||||
@@ -279,6 +279,8 @@ fn set_warning(h: &Host, on: bool) -> Answer {
|
||||
error_icon: false,
|
||||
no_as_default: true,
|
||||
preset: String::new(),
|
||||
color: None,
|
||||
cmyk_document: false,
|
||||
};
|
||||
if !h.dialogs.ask(question, OnYes::ExternalScriptWarningOff) {
|
||||
return Err(HostError::Error(WARNING_OFF_NEEDS_A_PERSON.into()));
|
||||
|
||||
@@ -3188,6 +3188,9 @@ thread_local! {
|
||||
pub(crate) static TEST_GROWTH_BYTES: Cell<Option<u64>> = const { Cell::new(None) };
|
||||
/// Tests: the data a run may pass to and from commands in place of [`MAX_BRIDGE_BYTES`].
|
||||
pub(crate) static TEST_BRIDGE_BYTES: Cell<Option<u64>> = const { Cell::new(None) };
|
||||
/// Tests: how many times the object model worked out where the points of each subpath of a
|
||||
/// path start.
|
||||
pub(crate) static LAYOUTS_BUILT: Cell<u64> = const { Cell::new(0) };
|
||||
/// Tests: the heap of a named engine in place of [`ENGINE_HEAP_BYTES`].
|
||||
pub(crate) static TEST_ENGINE_HEAP: Cell<Option<usize>> = const { Cell::new(None) };
|
||||
/// Tests: the bytes of source maps a named engine keeps, in place of [`KEPT_MAP_BYTES`].
|
||||
|
||||
@@ -236,6 +236,17 @@ impl Palettes {
|
||||
None
|
||||
}
|
||||
|
||||
/// Drops the events at the front of the line that [`Palettes::next`] would drop, so that the
|
||||
/// line is empty or starts with an event that can still run.
|
||||
fn drop_stale(&mut self) {
|
||||
while let Some(q) = self.waiting.front() {
|
||||
if self.resolved(q.clone()).is_some() {
|
||||
break;
|
||||
}
|
||||
self.waiting.pop_front();
|
||||
}
|
||||
}
|
||||
|
||||
/// As [`Palettes::next`], for the palettes of the engine `engine` only: the events of other
|
||||
/// engines' palettes keep their places in line. Events whose file access scopes do not cover
|
||||
/// the run's scope wait for runs of their own ([`Queued::scope`]). Eligible events run oldest
|
||||
@@ -252,7 +263,13 @@ impl Palettes {
|
||||
|
||||
/// The taken event `q` given to its control in its palette, and that palette, or `None` when it
|
||||
/// is dropped ([`Palettes::next`]).
|
||||
fn checked(&self, mut q: Queued) -> Option<(ScriptPalette, Queued)> {
|
||||
fn checked(&self, q: Queued) -> Option<(ScriptPalette, Queued)> {
|
||||
let (p, q) = self.resolved(q)?;
|
||||
Some((p.clone(), q))
|
||||
}
|
||||
|
||||
/// [`Palettes::checked`] without the copy of the palette.
|
||||
fn resolved(&self, mut q: Queued) -> Option<(&ScriptPalette, Queued)> {
|
||||
let p = self.list.iter().find(|p| p.id == q.palette && p.visible)?;
|
||||
if let Some(c) = control_of(&mut q.event) {
|
||||
*c = p.dialog.index_of(q.element?)?;
|
||||
@@ -271,7 +288,7 @@ impl Palettes {
|
||||
} else {
|
||||
q.event = scriptui::check_event(&p.dialog, q.event).ok()?;
|
||||
}
|
||||
Some((p.clone(), q))
|
||||
Some((p, q))
|
||||
}
|
||||
|
||||
/// The oldest waiting event for a palette of the engine `engine`, which a palette's `update()`
|
||||
@@ -414,6 +431,12 @@ impl Session {
|
||||
self.script_palettes.waiting.len()
|
||||
}
|
||||
|
||||
/// The number of the last palette event put in line, which an event added, or merged into a
|
||||
/// waiting one, changes.
|
||||
pub fn script_palette_last_ticket(&self) -> u64 {
|
||||
self.script_palettes.last_ticket
|
||||
}
|
||||
|
||||
/// The changes that wait for a run, as (palette id, the id of the control they change).
|
||||
pub fn script_palette_changes_waiting(&self) -> Vec<(u64, u64)> {
|
||||
self.script_palettes
|
||||
@@ -456,7 +479,12 @@ impl Session {
|
||||
/// run is going or no event waits; otherwise the run's name, or the error that ended it before
|
||||
/// it began. An open edit that cannot be settled gives its error, and the events keep waiting.
|
||||
pub fn script_palette_start(&mut self) -> Option<Result<String>> {
|
||||
if self.script_running() || self.script_palettes.waiting.is_empty() {
|
||||
if self.script_running() {
|
||||
return None;
|
||||
}
|
||||
// Events that can no longer run do not settle the open edit.
|
||||
self.script_palettes.drop_stale();
|
||||
if self.script_palettes.waiting.is_empty() {
|
||||
return None;
|
||||
}
|
||||
// An event waits while a drag or an undo group is open, which a run cannot start in.
|
||||
@@ -507,6 +535,9 @@ impl Session {
|
||||
let want = self.script_palettes.last_ticket;
|
||||
let mut mine = None;
|
||||
loop {
|
||||
if !self.script_running() {
|
||||
self.script_palettes.drop_stale();
|
||||
}
|
||||
if !self.script_running()
|
||||
&& !self.script_palettes.waiting.is_empty()
|
||||
&& let Err(e) = self.settle_for_script()
|
||||
|
||||
@@ -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() {
|
||||
|
||||
@@ -731,6 +731,68 @@ fn linked_pages_share_one_copy_of_the_file_and_open_in_the_pages_color_mode() {
|
||||
assert_eq!(s.doc().unwrap().doc.color_mode, vectorcraft_doc::ColorMode::Rgb, "colorMode wins");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn linked_pages_of_a_file_with_editing_data_keep_an_explicit_crop_box() {
|
||||
let dir = Folder::new("open-pdf-link-pages-explicit-crop");
|
||||
let src = dir.file("editable.ai");
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 50})).unwrap();
|
||||
s.execute(
|
||||
"file.saveAs",
|
||||
&json!({"path": src, "format": "ai", "preserveEditing": true,
|
||||
"bleed": {"useDocument": false, "top": 10, "bottom": 10, "left": 10, "right": 10}}),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(vectorcraft_pdf::has_illustrator_data(&std::fs::read(&src).unwrap(), None));
|
||||
let board = |s: &Session| {
|
||||
let r = s.doc().unwrap().doc.artboards[0].rect;
|
||||
(r.width(), r.height())
|
||||
};
|
||||
// No box named: the trim box, as the file opens as art.
|
||||
s.execute("document.open", &json!({"path": src, "linkPages": true})).unwrap();
|
||||
assert_eq!(board(&s), (100.0, 50.0));
|
||||
s.execute("document.open", &json!({"path": src, "linkPages": true, "cropTo": "trim"})).unwrap();
|
||||
assert_eq!(board(&s), (100.0, 50.0));
|
||||
// An explicit crop box is the crop box, which takes in the bleed.
|
||||
s.execute("document.open", &json!({"path": src, "linkPages": true, "cropTo": "crop"})).unwrap();
|
||||
let (w, h) = board(&s);
|
||||
assert!(w > 100.0 && h > 50.0, "{w} x {h}");
|
||||
s.execute("document.open", &json!({"path": src, "linkPages": true, "crop": "crop"})).unwrap();
|
||||
assert_eq!(board(&s), (w, h));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn linked_pages_with_only_a_native_attachment_default_to_crop_boxes() {
|
||||
let dir = Folder::new("open-pdf-link-pages-native-crop");
|
||||
let src = dir.file("editable.pdf");
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 50})).unwrap();
|
||||
s.execute(
|
||||
"document.exportPdf",
|
||||
&json!({"path": src, "preserveEditing": true,
|
||||
"bleed": {"useDocument": false, "top": 10, "bottom": 10, "left": 10, "right": 10}}),
|
||||
)
|
||||
.unwrap();
|
||||
let bytes = std::fs::read(&src).unwrap();
|
||||
assert!(vectorcraft_pdf::editing(&bytes).is_some_and(|e| e.intact));
|
||||
assert!(!vectorcraft_pdf::has_illustrator_data(&bytes, None));
|
||||
let board = |s: &Session| {
|
||||
let r = s.doc().unwrap().doc.artboards[0].rect;
|
||||
(r.width(), r.height())
|
||||
};
|
||||
s.execute("document.open", &json!({"path": src, "linkPages": true})).unwrap();
|
||||
let (w, h) = board(&s);
|
||||
assert!(w > 100.0 && h > 50.0, "{w} x {h}");
|
||||
for key in ["cropTo", "crop"] {
|
||||
let mut params = json!({"path": src, "linkPages": true});
|
||||
params[key] = json!("crop");
|
||||
s.execute("document.open", ¶ms).unwrap();
|
||||
assert_eq!(board(&s), (w, h), "{key}");
|
||||
}
|
||||
s.execute("document.open", &json!({"path": src, "linkPages": true, "cropTo": "trim"})).unwrap();
|
||||
assert_eq!(board(&s), (100.0, 50.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn linked_pages_read_the_file_once_and_a_blank_page_keeps_its_crop_box() {
|
||||
use vectorcraft_testkit::pdf::{PdfPage, pdf};
|
||||
|
||||
@@ -177,6 +177,8 @@ fn a_framed_run_waits_at_each_dialog_and_takes_the_persons_answer() {
|
||||
error_icon: false,
|
||||
no_as_default: true,
|
||||
preset: String::new(),
|
||||
color: None,
|
||||
cmyk_document: false,
|
||||
};
|
||||
assert_eq!(s.script_dialog(), Some(want));
|
||||
assert!(!s.script_answer(DialogAnswer::Ok), "an answer for another kind of dialog is refused");
|
||||
@@ -343,3 +345,103 @@ fn a_dialog_in_a_callback_throws_in_the_app() {
|
||||
assert!(r["log"][0].as_str().unwrap().contains("callback"), "{r}");
|
||||
assert_eq!(r["dialogCount"], 0);
|
||||
}
|
||||
|
||||
/// `showColorPicker` with an RGB red, the answer, and the run's log line for the color it returns.
|
||||
const PICK_RED: &str = "var c = new RGBColor(); c.red = 255; var p = app.showColorPicker(c); vc.log([p.typename, p.red, p.green, p.blue].join());";
|
||||
|
||||
#[test]
|
||||
fn a_run_with_nobody_to_ask_takes_the_picked_color_from_answers() {
|
||||
let mut s = one_doc();
|
||||
let source = format!("{PICK_RED} var g = new GrayColor(); g.gray = 40; var q = app.showColorPicker(g); vc.log([q.typename, q.gray].join());");
|
||||
let r = headless(&mut s, &source, answers(&[json!({"kind": "colorPicker", "value": "#00FF00"}), json!({"kind": "colorPicker", "value": null})]))
|
||||
.unwrap();
|
||||
assert_eq!(r["log"], json!(["RGBColor,0,255,0", "GrayColor,40"]), "OK gives the picked color, Cancel the color given: {r}");
|
||||
let dialogs = r["dialogs"].as_array().unwrap();
|
||||
assert_eq!(dialogs.len(), 2);
|
||||
assert!(dialogs.iter().all(|d| d["kind"] == "colorPicker" && d["color"].is_object() && d.get("message").is_none()), "{r}");
|
||||
assert_eq!(dialogs[1]["answer"], Value::Null, "Cancel is listed as null");
|
||||
let cmyk = headless(
|
||||
&mut s,
|
||||
"var c = new CMYKColor(); c.cyan = 20; vc.log(app.showColorPicker(c).typename);",
|
||||
answers(&[json!({"kind": "colorPicker", "value": {"c": 0, "m": 100, "y": 100, "k": 0}})]),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(cmyk["log"], json!(["CMYKColor"]), "the picked color keeps its own model: {cmyk}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_color_picker_ends_the_run_when_no_answer_is_left() {
|
||||
let mut s = one_doc();
|
||||
let before = art(&s);
|
||||
let edit = "vc.run('shape.rectangle', {x: 20, y: 0, width: 5, height: 5});";
|
||||
for (given, says) in [(json!([]), "no answer left"), (answers(&[json!({"kind": "prompt", "value": "x"})]), "is for prompt, not colorPicker")] {
|
||||
let source = format!("{edit} try {{ {PICK_RED} }} catch (e) {{ vc.log('caught'); }}");
|
||||
let e = headless(&mut s, &source, given).unwrap_err().to_string();
|
||||
assert!(e.contains("showColorPicker") && e.contains(says), "{e}");
|
||||
assert_eq!(art(&s), before, "the run's edit goes back");
|
||||
let report = s.script_report().unwrap();
|
||||
assert_eq!(report["log"], json!([]), "a missing answer cannot be caught");
|
||||
assert_eq!(report["dialogs"][0]["answer"], "missing", "{report}");
|
||||
}
|
||||
let a = headless(&mut s, "alert('x');", answers(&[json!({"kind": "colorPicker", "value": null})])).unwrap_err().to_string();
|
||||
assert!(a.contains("is for colorPicker, not alert"), "{a}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_color_picker_refuses_what_is_not_a_solid_color() {
|
||||
let mut s = one_doc();
|
||||
let source = "var out = []; [undefined, 'red', new NoColor(), {typename: 'SpotColor', tint: 100}].forEach(function (c) {\
|
||||
try { app.showColorPicker(c); out.push('opened'); } catch (e) { out.push(e.name); } });\
|
||||
try { var big = new RGBColor(); big.red = 300; app.showColorPicker(big); } catch (e) { out.push(e.name); } vc.log(out.join());";
|
||||
let r = headless(&mut s, source, json!([])).unwrap();
|
||||
assert_eq!(r["log"], json!(["TypeError,TypeError,TypeError,TypeError,RangeError"]), "{r}");
|
||||
assert_eq!(r["dialogCount"], 0, "no picker opened");
|
||||
for bad in [
|
||||
json!("not a color"),
|
||||
json!([255, 0, 0]),
|
||||
json!({"model": "lab", "l": 120, "a": 0, "b": 0}),
|
||||
json!(true),
|
||||
json!("rgb 300 0 0"),
|
||||
json!("cmyk 0 0 0 101"),
|
||||
json!("gray -1"),
|
||||
json!("lab 50 200 0"),
|
||||
json!("rgb 255.000001 0 0"),
|
||||
json!([1.00000001, 0, 0]),
|
||||
json!({"c": 100.000001, "m": 0, "y": 0, "k": 0}),
|
||||
json!({"gray": 100.000001}),
|
||||
json!({"l": 100.000001, "a": 0, "b": 0}),
|
||||
json!({"model": "rgb", "r": 1.00000001, "g": 0, "b": 0}),
|
||||
json!({"model": "lab", "l": 50, "a": -128.000001, "b": 0}),
|
||||
] {
|
||||
let e = headless(&mut s, PICK_RED, answers(&[json!({"kind": "colorPicker", "value": bad})])).unwrap_err().to_string();
|
||||
assert!(e.contains("color picker's answer"), "{bad}: {e}");
|
||||
}
|
||||
for good in [
|
||||
json!("rgb 255 0 0"),
|
||||
json!("cmyk 0 100 100 0"),
|
||||
json!("gray 100"),
|
||||
json!("lab 50 -128 128"),
|
||||
json!([1, 0, 0]),
|
||||
json!({"c": 0, "m": 100, "y": 100, "k": 0}),
|
||||
json!({"gray": 100}),
|
||||
json!({"l": 100, "a": -128, "b": 128}),
|
||||
json!({"model": "rgb", "r": 1, "g": 0, "b": 0}),
|
||||
] {
|
||||
assert!(headless(&mut s, PICK_RED, answers(&[json!({"kind": "colorPicker", "value": good})])).is_ok(), "{good}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_framed_run_waits_at_the_color_picker() {
|
||||
let mut s = one_doc();
|
||||
framed(&mut s, &format!("{PICK_RED} var q = app.showColorPicker(p); vc.log(q.green);"));
|
||||
let d = s.script_dialog().unwrap();
|
||||
assert_eq!((d.kind, d.color), (DialogKind::ColorPicker, Some(vectorcraft_color::Color::rgb(1.0, 0.0, 0.0))));
|
||||
assert!(!s.script_answer(DialogAnswer::Ok), "an answer for another kind of dialog is refused");
|
||||
assert!(s.script_answer(DialogAnswer::ColorPicker(Some(vectorcraft_color::Color::rgb(0.0, 0.0, 1.0)))));
|
||||
assert!(pump(&mut s).is_none());
|
||||
assert_eq!(s.script_dialog().unwrap().color, Some(vectorcraft_color::Color::rgb(0.0, 0.0, 1.0)), "it opens on the color it is given");
|
||||
assert!(s.script_answer(DialogAnswer::ColorPicker(None)));
|
||||
let r = pump(&mut s).unwrap().unwrap();
|
||||
assert_eq!(r["log"], json!(["RGBColor,0,0,255", 0]), "{r}");
|
||||
}
|
||||
@@ -1541,6 +1541,22 @@ fn a_listed_preset_keeps_more_rows_than_artboards() {
|
||||
assert_eq!(more.boards().iter().filter(|b| b.x0 == more.boards()[0].x0).count(), 4);
|
||||
}
|
||||
|
||||
/// A layout that replaces the rows keeps the columns the rows gave the artboards there are now,
|
||||
/// whether or not the change of artboards came with a layout of its own.
|
||||
#[test]
|
||||
fn replacing_rows_keeps_the_columns_of_the_artboards_there_are_now() {
|
||||
use crate::cmd::newdoc::{ArtboardLayout, DocSettings};
|
||||
let settings = DocSettings { artboards: 2, layout: ArtboardLayout::GridByColumn, ..DocSettings::default() };
|
||||
let settings = settings.with_params(&json!({"artboardLayout": {"rows": 4}}), "file.new").unwrap();
|
||||
for change in [json!({"artboards": 9}), json!({"artboards": 9, "artboardLayout": {"spacing": 20}})] {
|
||||
let more = settings.clone().with_params(&change, "file.new").unwrap();
|
||||
for layout in [json!("gridByRow"), json!({"layout": "gridByRow"})] {
|
||||
let by_row = more.clone().with_params(&json!({"artboardLayout": layout}), "file.new").unwrap();
|
||||
assert_eq!(by_row.grid_columns(), 3, "{change} then {layout}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stale_documents_throw_on_every_member() {
|
||||
let (mut s, _, _) = doc();
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::{LineCap, LineJoin};
|
||||
use vectorcraft_geom::Point;
|
||||
use vectorcraft_geom::path::AnchorKind;
|
||||
|
||||
use crate::*;
|
||||
@@ -420,6 +421,9 @@ fn path_point_setters_edit_one_anchor() {
|
||||
for i in [0, 2, 3] {
|
||||
assert_eq!(anchors[i], anchors_before[i], "point {i} did not change");
|
||||
}
|
||||
// The 300 pt tall document's y runs down, so script y 285 is document y 15.
|
||||
let edited = &anchors[1];
|
||||
assert_eq!((edited.p, edited.h_in, edited.h_out), (Point::new(45.0, 15.0), Point::new(35.0, 15.0), Point::new(55.0, 15.0)));
|
||||
assert!(failure(&mut s, "app.activeDocument.pathItems[0].pathPoints.index('a');").contains("Not found"));
|
||||
assert!(failure(&mut s, "app.activeDocument.pathItems[0].pathPoints[0].pointType = 'SMOOTH';").contains("PointType"));
|
||||
assert!(failure(&mut s, "app.activeDocument.pathItems[0].pathPoints[0].anchor = [1, 'x'];").contains("finite"));
|
||||
@@ -2385,6 +2389,95 @@ fn assigning_guides_throws_in_both_directions_while_guides_are_locked() {
|
||||
assert_eq!((is_guide(&s, a), is_guide(&s, b), undo_steps(&s)), (true, false, steps), "a value the path has runs no command");
|
||||
}
|
||||
|
||||
/// Reading and moving each point of a path with many subpaths works out where the subpaths' points
|
||||
/// start a few times for the whole loop, not once or more for each point.
|
||||
#[test]
|
||||
fn reading_and_moving_points_counts_the_subpaths_a_few_times() {
|
||||
let (mut s, _, _) = doc();
|
||||
let d: String = (0..500).map(|i| format!("M{x} 10 L{x} 20 ", x = i % 300)).collect();
|
||||
let id = NodeId(s.execute("path.create", &json!({"d": d})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
crate::script::LAYOUTS_BUILT.with(|n| n.set(0));
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var pp = app.activeDocument.pathItems[0].pathPoints;\
|
||||
for (var i = 0; i < pp.length; i++) { var q = pp[i]; q.anchor = [q.anchor[0], q.anchor[1] + 1]; }\
|
||||
vc.log(pp.length);",
|
||||
);
|
||||
assert_eq!(out, vec![json!(1000)]);
|
||||
let built = crate::script::LAYOUTS_BUILT.with(std::cell::Cell::get);
|
||||
assert!(built < 10, "{built} layouts for 1000 points");
|
||||
let n = node(&s, id);
|
||||
let ys: Vec<f64> = n.path_data().unwrap().subpaths.iter().flat_map(|sp| &sp.anchors).map(|an| an.p.y).collect();
|
||||
assert_eq!(ys.len(), 1000);
|
||||
assert!(ys.iter().all(|&y| y == 9.0 || y == 19.0), "every point moved up");
|
||||
}
|
||||
|
||||
/// `selectedPathPoints` lists the direct-selected anchors of a path with several subpaths in the
|
||||
/// order of `pathPoints`, whatever order they were selected in.
|
||||
#[test]
|
||||
fn selected_path_points_follow_the_order_of_path_points_across_subpaths() {
|
||||
let (mut s, _, _) = doc();
|
||||
let id = NodeId(s.execute("path.create", &json!({"d": "M0 0 L10 0 L10 10 M20 0 L30 0"})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("select.anchors", &json!({"id": id.0, "anchors": [[1, 1], [0, 2], [0, 0]], "mode": "set"})).unwrap();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var sp = app.activeDocument.pathItems[0].selectedPathPoints, x = [];\
|
||||
for (var i = 0; i < sp.length; i++) x.push(sp[i].anchor[0]); vc.log(x);",
|
||||
);
|
||||
assert_eq!(out, vec![json!([0, 10, 30])]);
|
||||
}
|
||||
|
||||
/// `pageItems` and `pathItems` find a name that reads as a number but is not an index, and such a
|
||||
/// key that nothing has reads as `undefined`.
|
||||
#[test]
|
||||
fn collections_find_names_that_read_as_numbers() {
|
||||
let (mut s, a, b) = doc();
|
||||
s.execute("object.setProps", &json!({"ids": [a.0], "name": "-1"})).unwrap();
|
||||
s.execute("object.setProps", &json!({"ids": [b.0], "name": "1.5"})).unwrap();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var d = app.activeDocument, g = d.pageItems, p = d.pathItems;\
|
||||
vc.log([g['-1'].name, g[1.5].name, '-1' in g, p['-1'].name, p[-1].name, '1.5' in p]);\
|
||||
vc.log([g[-2] === undefined, '-2' in p, p[2.5] === undefined, p[0].name, p[1].name]);",
|
||||
);
|
||||
assert_eq!(out, vec![json!(["-1", "1.5", true, "-1", "-1", true]), json!([true, false, true, "-1", "1.5"])]);
|
||||
}
|
||||
|
||||
/// `typename` of a point or a point list throws for one that is stale, as the other members do.
|
||||
#[test]
|
||||
fn stale_points_throw_on_typename() {
|
||||
let (mut s, _, _) = doc();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var pp = app.activeDocument.pathItems[0].pathPoints, q = pp[3]; vc.log(q.typename); pp[0].remove();\
|
||||
try { q.typename; vc.log('read'); } catch (e) { vc.log(e.message); }\
|
||||
var p = app.activeDocument.pathItems[0], ps = p.pathPoints; vc.log(ps.typename); p.remove();\
|
||||
try { ps.typename; vc.log('read'); } catch (e) { vc.log(e.message); }",
|
||||
);
|
||||
assert_eq!(out, vec![json!("PathPoint"), json!("Stale path point"), json!("PathPoints"), json!("Stale page item")]);
|
||||
}
|
||||
|
||||
/// A path the creators make in a document whose ids are past 2^53 is the new path, not one whose
|
||||
/// id a double rounds to.
|
||||
#[test]
|
||||
fn made_paths_keep_ids_past_two_to_the_53() {
|
||||
let (mut s, _, _) = doc();
|
||||
let big = 1u64 << 53;
|
||||
s.edit("Raise Ids", |d, _| {
|
||||
d.raise_next_id(big);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let old = rect(&mut s, 200.0, 200.0, 10.0, 10.0);
|
||||
assert_eq!(old.0, big);
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
log(&mut s, "var p = app.activeDocument.pathItems; p.add().name = 'made'; p.rectangle(50, 50, 10, 10, true).name = 'reversed';");
|
||||
assert_eq!(node(&s, old).name, None);
|
||||
assert_eq!(node(&s, NodeId(big + 1)).name.as_deref(), Some("made"));
|
||||
assert_eq!(node(&s, NodeId(big + 2)).name.as_deref(), Some("reversed"));
|
||||
}
|
||||
|
||||
/// A point change made before a call that fails and is put back, here a new document whose
|
||||
/// profile cannot be read, is kept.
|
||||
#[test]
|
||||
|
||||
@@ -104,6 +104,8 @@ fn yes_to_the_confirm_turns_the_warning_off() {
|
||||
error_icon: false,
|
||||
no_as_default: true,
|
||||
preset: String::new(),
|
||||
color: None,
|
||||
cmyk_document: false,
|
||||
};
|
||||
assert_eq!(s.script_dialog(), Some(want));
|
||||
assert!(s.script_dialog_turns_warning_off());
|
||||
|
||||
@@ -135,6 +135,45 @@ fn added_group_named_as_seam_fills_is_counted() {
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// `groupItems.removeAll()` of a group and the document's `compoundPathItems.removeAll()` refuse
|
||||
/// to leave an image at the bottom of an ordinary group named as a tracing, before the document
|
||||
/// changes.
|
||||
#[test]
|
||||
fn group_and_compound_remove_all_cannot_leave_an_image_first_in_a_group_named_as_a_tracing() {
|
||||
let compound = "(function () { d.selection = [d.pathItems.rectangle(10, 10, 20, 20), d.pathItems.rectangle(40, 40, 5, 5)];\
|
||||
vc.run('object.compoundPath.make'); return d.pageItems[0]; })()";
|
||||
let group = "(function () { d.selection = [d.pathItems.rectangle(10, 10, 20, 20)]; vc.run('object.group'); return d.pageItems[0]; })()";
|
||||
for (name, bottom, list) in
|
||||
[("group-remove-all-groups", group, "groupItems[0].groupItems"), ("remove-all-compounds", compound, "compoundPathItems")]
|
||||
{
|
||||
let base = folder(name);
|
||||
let (mut s, _) = session(&base, false);
|
||||
log(
|
||||
&mut s,
|
||||
&base,
|
||||
&format!(
|
||||
"var d = app.activeDocument; d.selection = [{bottom}]; vc.run('object.group');\
|
||||
var g = d.pageItems[0]; g.name = 'Image Trace'; d.rasterItems[0].move(g, ElementPlacement.PLACEATBEGINNING);"
|
||||
),
|
||||
);
|
||||
let before = vectorcraft_format::save(&s.active().unwrap().doc, false);
|
||||
let steps = undo_steps(&s);
|
||||
let out = log(
|
||||
&mut s,
|
||||
&base,
|
||||
&format!(
|
||||
"var d = app.activeDocument, m = ''; try {{ d.{list}.removeAll(); }} catch (e) {{ m = e.message; }}\
|
||||
vc.log(m); vc.log(d.pageItems[0].typename);"
|
||||
),
|
||||
);
|
||||
assert_eq!(out, [json!("Only Image Trace can make a tracing"), json!("GroupItem")], "{list}");
|
||||
assert!(traces(&s).is_empty(), "{list}");
|
||||
assert_eq!(vectorcraft_format::save(&s.active().unwrap().doc, false), before, "{list}");
|
||||
assert_eq!(undo_steps(&s), steps, "{list}");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trace_image_resolution_is_one_number_or_none() {
|
||||
let base = folder("resolution");
|
||||
|
||||
@@ -563,6 +563,32 @@ fn a_waiting_click_on_a_button_a_handler_disabled_is_dropped() {
|
||||
assert_eq!(s.script_palette_events_waiting(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_line_of_clicks_that_can_no_longer_run_does_not_settle_the_open_edit() {
|
||||
let mut s = one_doc();
|
||||
run_in_app(
|
||||
&mut s,
|
||||
"#targetengine switches\nvar p = new Window('palette'); var off = p.add('button', undefined, 'Off'); \
|
||||
var go = p.add('button', undefined, 'Go'); off.onClick = function () { go.enabled = false; vc.log('off'); }; \
|
||||
go.onClick = function () { vc.log('go'); }; p.show();",
|
||||
);
|
||||
let id = only_palette(&s);
|
||||
assert_eq!(run(&mut s, "confirm('Go?');").unwrap()["running"], true);
|
||||
assert!(pump(&mut s).is_none());
|
||||
assert_eq!(s.script_palette_event(id, UiEvent::Click(1)), Ok(Waiting::Added));
|
||||
assert_eq!(s.script_palette_event(id, UiEvent::Click(2)), Ok(Waiting::Added));
|
||||
assert!(s.script_answer(DialogAnswer::Confirm(true)));
|
||||
pump(&mut s).unwrap().unwrap();
|
||||
assert!(s.script_palette_start().expect("the first click starts its run").is_ok());
|
||||
assert_eq!(pump(&mut s).unwrap().unwrap()["log"], json!(["off"]));
|
||||
// Settling would fail here, so a start that tries to settle gives an error.
|
||||
SETTLE_FAILS.with(|f| f.set(true));
|
||||
let started = s.script_palette_start();
|
||||
SETTLE_FAILS.with(|f| f.set(false));
|
||||
assert!(started.is_none(), "the stale click does not settle the open edit: {:?}", started.map(|r| r.map_err(|e| e.to_string())));
|
||||
assert_eq!(s.script_palette_events_waiting(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_palette_click_during_another_run_runs_after_it() {
|
||||
let mut s = one_doc();
|
||||
|
||||
+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
|
||||
|
||||
@@ -112,7 +112,8 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
concatenateTranslationMatrix constructor coordinateSystem coordinateSystem= copy cut documents doScript \
|
||||
executeMenuCommand getIdentityMatrix getIsFileOpen getRotationMatrix getScaleMatrix getTranslationMatrix \
|
||||
invertMatrix isEqualMatrix isSingularMatrix loadAction loadAction= open paste PPDFileList preferences printPresetsList \
|
||||
printerList redo redraw selection selection= selectTool textFonts toString typename undo unloadAction unloadAction= \
|
||||
printerList redo redraw selection selection= selectTool showColorPicker textFonts toString typename undo unloadAction \
|
||||
unloadAction= \
|
||||
userInteractionLevel \
|
||||
userInteractionLevel=",
|
||||
),
|
||||
|
||||
@@ -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};
|
||||
|
||||
@@ -22,7 +22,7 @@ flate2 = { workspace = true }
|
||||
# file's access ACL on Linux (`keep_permissions`). Already in Cargo.lock (tempfile), so this adds
|
||||
# no new crate.
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
rustix = { workspace = true, features = ["std", "fs"] }
|
||||
rustix = { workspace = true, features = ["std", "fs", "process"] }
|
||||
|
||||
[dev-dependencies]
|
||||
vectorcraft-testkit = { workspace = true }
|
||||
|
||||
+115
-6
@@ -153,13 +153,19 @@ pub fn write_atomic_checked(
|
||||
flushed.map_err(|e| io::Error::new(io::Error::from(e).kind(), WrittenError { path: now(&name), error: e.into() }))
|
||||
};
|
||||
let open_target = |write: bool| -> io::Result<File> {
|
||||
// A missing target is created by `create_target`, after the last check. An existing one is
|
||||
// opened with `O_CREAT` as before, so Linux's `fs.protected_regular` still applies to it.
|
||||
if write && matches!(rustix::fs::statat(&dir, &name, AtFlags::SYMLINK_NOFOLLOW), Err(e) if e == rustix::io::Errno::NOENT) {
|
||||
return Err(io::ErrorKind::NotFound.into());
|
||||
// Opened without `O_CREAT`: a missing target, one removed meanwhile included, is created
|
||||
// only by `create_target`, after the last check.
|
||||
#[cfg(test)]
|
||||
if write && let Some(hook) = BEFORE_TARGET_OPEN.with(|h| h.borrow_mut().take()) {
|
||||
hook();
|
||||
}
|
||||
let flags = if write { OFlags::WRONLY | OFlags::CREATE } else { OFlags::RDONLY };
|
||||
Ok(File::from(rustix::fs::openat(&dir, &name, flags | OFlags::NOFOLLOW | OFlags::CLOEXEC, mode)?))
|
||||
// `O_NONBLOCK`: a FIFO at the name fails the regular-file check instead of waiting for a reader.
|
||||
let flags = if write { OFlags::WRONLY | OFlags::NONBLOCK } else { OFlags::RDONLY };
|
||||
let file = File::from(rustix::fs::openat(&dir, &name, flags | OFlags::NOFOLLOW | OFlags::CLOEXEC, mode)?);
|
||||
if write {
|
||||
protected_regular(&dir, &file)?;
|
||||
}
|
||||
Ok(file)
|
||||
};
|
||||
let create_target = || -> io::Result<File> { Ok(File::from(rustix::fs::openat(&dir, &name, new_file, mode)?)) };
|
||||
match rustix::fs::openat(&dir, &tmp_name, new_file, mode).map(File::from) {
|
||||
@@ -265,6 +271,31 @@ pub fn write_atomic_checked(
|
||||
}
|
||||
}
|
||||
|
||||
/// The target [`write_atomic_checked`] opened without `O_CREAT`, checked as Linux's strictest
|
||||
/// `fs.protected_regular` checks an `O_CREAT` open of an existing file: anything but a regular
|
||||
/// file is refused, and so is a file in a sticky folder that others or the group can write to
|
||||
/// when neither this process nor the folder's owner owns it.
|
||||
#[cfg(unix)]
|
||||
fn protected_regular(dir: &std::os::fd::OwnedFd, file: &File) -> io::Result<()> {
|
||||
let (folder, opened) = (rustix::fs::fstat(dir)?, rustix::fs::fstat(file)?);
|
||||
if rustix::fs::FileType::from_raw_mode(opened.st_mode) != rustix::fs::FileType::RegularFile {
|
||||
return Err(io::Error::new(io::ErrorKind::InvalidInput, "not a regular file"));
|
||||
}
|
||||
if refused_in_sticky_folder(rustix::fs::Mode::from_raw_mode(folder.st_mode), folder.st_uid, opened.st_uid, rustix::process::geteuid().as_raw()) {
|
||||
return Err(io::ErrorKind::PermissionDenied.into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Whether a file owned by `owner` in a folder with mode `folder_mode` owned by `folder_owner` is
|
||||
/// refused to the user `me`: the folder is sticky, others or the group can write to it, and
|
||||
/// neither `me` nor `folder_owner` owns the file.
|
||||
#[cfg(unix)]
|
||||
fn refused_in_sticky_folder(folder_mode: rustix::fs::Mode, folder_owner: u32, owner: u32, me: u32) -> bool {
|
||||
use rustix::fs::Mode;
|
||||
folder_mode.contains(Mode::SVTX) && folder_mode.intersects(Mode::WGRP | Mode::WOTH) && owner != me && owner != folder_owner
|
||||
}
|
||||
|
||||
/// See the Unix version. Here `allowed(path)` runs before the file is written and again after it is
|
||||
/// filled, right before it is put in place; a refusal then removes the temporary file and leaves
|
||||
/// `path` unchanged.
|
||||
@@ -784,6 +815,9 @@ thread_local! {
|
||||
/// Tests: [`write_atomic_checked`]'s folder refuses the rename.
|
||||
#[cfg(unix)]
|
||||
static RENAME_REFUSED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
|
||||
/// Tests: run once right before [`write_atomic_checked`] opens its target for writing.
|
||||
#[cfg(unix)]
|
||||
static BEFORE_TARGET_OPEN: std::cell::RefCell<Option<Box<dyn FnOnce()>>> = const { std::cell::RefCell::new(None) };
|
||||
}
|
||||
|
||||
/// A symbolic link keeps pointing at its file: write the file it names.
|
||||
@@ -1282,6 +1316,81 @@ mod tests {
|
||||
let _ = std::fs::remove_dir_all(d);
|
||||
}
|
||||
|
||||
/// A target removed after the write starts is not created again before the last check: when its
|
||||
/// folder has moved outside by then, nothing is left there.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_checked_write_creates_no_target_removed_while_it_is_opened() {
|
||||
let (d, root, outside) = checked_folders("checked-removed-target");
|
||||
let path = root.join("inside/doc.txt");
|
||||
std::fs::write(&path, b"old").unwrap();
|
||||
let (inside, moved) = (root.join("inside"), outside.join("inside"));
|
||||
let (from, to) = (inside.clone(), moved.clone());
|
||||
BEFORE_TARGET_OPEN.with(|h| {
|
||||
*h.borrow_mut() = Some(Box::new(move || {
|
||||
std::fs::remove_file(from.join("doc.txt")).unwrap();
|
||||
std::fs::rename(&from, &to).unwrap();
|
||||
}))
|
||||
});
|
||||
RENAME_REFUSED.with(|c| c.set(true));
|
||||
let r = write_atomic_checked(&path, |f| f.write_all(b"new"), under(&root));
|
||||
RENAME_REFUSED.with(|c| c.set(false));
|
||||
BEFORE_TARGET_OPEN.with(|h| h.borrow_mut().take());
|
||||
assert!(r.is_err(), "{r:?}");
|
||||
assert!(!moved.join("doc.txt").exists(), "the removed target was created again");
|
||||
assert!(!inside.exists());
|
||||
let _ = std::fs::remove_dir_all(d);
|
||||
}
|
||||
|
||||
/// An existing regular file this process owns passes the check.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn protected_regular_allows_a_file_this_process_owns() {
|
||||
let d = std::fs::canonicalize(dir("protected-regular")).unwrap();
|
||||
std::fs::write(d.join("doc.txt"), b"old").unwrap();
|
||||
let folder: std::os::fd::OwnedFd = File::open(&d).unwrap().into();
|
||||
let file = OpenOptions::new().write(true).open(d.join("doc.txt")).unwrap();
|
||||
protected_regular(&folder, &file).unwrap();
|
||||
let _ = std::fs::remove_dir_all(d);
|
||||
}
|
||||
|
||||
/// A FIFO at the name is not written into when the rename is refused: without a reader the
|
||||
/// write fails at once instead of waiting for one (without `O_NONBLOCK` this test does not
|
||||
/// return), and with a reader nothing reaches it.
|
||||
#[cfg(target_os = "linux")]
|
||||
#[test]
|
||||
fn a_checked_write_does_not_write_into_a_fifo_at_its_name() {
|
||||
use rustix::fs::{Mode, OFlags};
|
||||
use std::io::Read as _;
|
||||
let (d, root, _) = checked_folders("checked-fifo");
|
||||
let path = root.join("inside/doc.txt");
|
||||
rustix::fs::mknodat(rustix::fs::CWD, &path, rustix::fs::FileType::Fifo, Mode::RUSR | Mode::WUSR, 0).unwrap();
|
||||
RENAME_REFUSED.with(|c| c.set(true));
|
||||
let alone = write_atomic_checked(&path, |f| f.write_all(b"new"), under(&root));
|
||||
let reader = File::from(rustix::fs::open(&path, OFlags::RDONLY | OFlags::NONBLOCK, Mode::empty()).unwrap());
|
||||
let read = write_atomic_checked(&path, |f| f.write_all(b"new"), under(&root));
|
||||
RENAME_REFUSED.with(|c| c.set(false));
|
||||
assert!(alone.is_err() && read.is_err(), "{alone:?} {read:?}");
|
||||
let mut got = [0u8; 8];
|
||||
assert!((&reader).read(&mut got).map_or(true, |n| n == 0), "nothing is written into the FIFO");
|
||||
let _ = std::fs::remove_dir_all(d);
|
||||
}
|
||||
|
||||
/// A file in a sticky folder that others or the group can write to is refused when neither this
|
||||
/// user nor the folder's owner owns it.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_file_owned_by_someone_else_in_a_shared_sticky_folder_is_refused() {
|
||||
let (me, folder_owner, other) = (1000, 0, 2000);
|
||||
let mode = rustix::fs::Mode::from_raw_mode;
|
||||
assert!(refused_in_sticky_folder(mode(0o1777), folder_owner, other, me));
|
||||
assert!(refused_in_sticky_folder(mode(0o1770), folder_owner, other, me));
|
||||
assert!(!refused_in_sticky_folder(mode(0o1755), folder_owner, other, me));
|
||||
assert!(!refused_in_sticky_folder(mode(0o0777), folder_owner, other, me));
|
||||
assert!(!refused_in_sticky_folder(mode(0o1777), folder_owner, me, me));
|
||||
assert!(!refused_in_sticky_folder(mode(0o1777), folder_owner, folder_owner, me));
|
||||
}
|
||||
|
||||
/// A file created by another writer at the final check is preserved whether that check succeeds or fails.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
|
||||
@@ -33,6 +33,13 @@ use pattern::Mode;
|
||||
/// enough for a 1 MiB stack.
|
||||
pub(crate) const MAX_DEPTH: u32 = 600;
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// Tests: the top-level function names that deciding the variables of block functions has
|
||||
/// gathered or looked up.
|
||||
pub(crate) static FUN_DECL_CHECKS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// Why code could not be compiled.
|
||||
#[derive(Debug)]
|
||||
pub(crate) enum CompileFail {
|
||||
@@ -409,6 +416,7 @@ impl<'a> FnCompiler<'a> {
|
||||
| Stmt::DefaultXmlNamespace(_) => {}
|
||||
}
|
||||
}
|
||||
let mut top_names: Option<HashSet<&Key>> = None;
|
||||
for (k, scope, id) in annex {
|
||||
let mut cur = Some(scope);
|
||||
let mut clash = params.contains(&k) || *k == *key_of("arguments");
|
||||
@@ -422,7 +430,18 @@ impl<'a> FnCompiler<'a> {
|
||||
}
|
||||
if !clash {
|
||||
self.annex.insert(id);
|
||||
if !seen.contains(&k) && !out.fun_decls.iter().any(|(name, _)| *name == k) && annex_seen.insert(k.clone()) {
|
||||
if seen.contains(&k) {
|
||||
continue;
|
||||
}
|
||||
// The top-level function names, gathered the first time a block function needs them.
|
||||
let top = top_names.get_or_insert_with(|| {
|
||||
#[cfg(test)]
|
||||
FUN_DECL_CHECKS.with(|c| c.set(c.get() + out.fun_decls.len() as u64));
|
||||
out.fun_decls.iter().map(|(name, _)| name).collect::<HashSet<&Key>>()
|
||||
});
|
||||
#[cfg(test)]
|
||||
FUN_DECL_CHECKS.with(|c| c.set(c.get() + 1));
|
||||
if !top.contains(&k) && annex_seen.insert(k.clone()) {
|
||||
out.annex_vars.push(k);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -203,6 +203,19 @@ fn a_block_function_whose_variable_cannot_be_declared_stays_in_its_block() {
|
||||
assert_eq!(realm.run("(0, eval)('{ function m() { return 7; } out = m(); }'); out + typeof m"), Ok(JsValue::String("7undefined".into())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn block_function_variables_look_up_each_top_level_function_name_once() {
|
||||
// 1,000 top-level functions and 1,000 block functions: each block function's variable is
|
||||
// decided with one lookup in the names gathered once, not by comparing it with every
|
||||
// top-level function.
|
||||
let top = (0..1_000).map(|i| format!("function t{i}() {{ return {i}; }}")).collect::<String>();
|
||||
let blocks = (0..1_000).map(|i| format!("{{ function b{i}() {{ return {i}; }} }}")).collect::<String>();
|
||||
crate::compiler::FUN_DECL_CHECKS.with(|c| c.set(0));
|
||||
assert_eq!(run(&format!("{top}{blocks}t999() + b999()")), JsValue::Number(1_998.0));
|
||||
let checks = crate::compiler::FUN_DECL_CHECKS.with(std::cell::Cell::get);
|
||||
assert_eq!(checks, 2_000, "top-level function names gathered and looked up for 1,000 block functions");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_block_function_in_eval_in_a_default_parameter_leaves_a_parameter_of_its_name_alone() {
|
||||
// A parameter between the eval code and its variable environment has the name, so the block
|
||||
|
||||
@@ -1802,7 +1802,13 @@ fn update_palette(i: &mut Interp, win: ObjId) -> JsResult<()> {
|
||||
if !slot(i, win, SHOWN)?.truthy() {
|
||||
return Ok(());
|
||||
}
|
||||
let hides = number_slot(i, win, HIDES)?;
|
||||
let (desc, ..) = describe(i, win)?;
|
||||
// A getter that hid or closed the palette leaves the host the controls it had then.
|
||||
let same = matches!(slot(i, win, PALETTE_ID)?, Value::Number(now) if now == id);
|
||||
if !same || !slot(i, win, SHOWN)?.truthy() || number_slot(i, win, HIDES)? != hides {
|
||||
return Ok(());
|
||||
}
|
||||
let f = host_fn(i, "paletteUpdate")?;
|
||||
i.rooted(std::slice::from_ref(&desc), |i| i.call(&f, &Value::Undefined, &[desc.clone(), Value::Number(id)]))?;
|
||||
Ok(())
|
||||
|
||||
@@ -1250,6 +1250,22 @@ fn a_hidden_palette_is_not_described_after_the_run() {
|
||||
assert_eq!(updates(&calls), before, "the host is not given a hidden palette's controls");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_palette_a_title_getter_hides_is_not_described_after_the_run() {
|
||||
let (mut r, calls) = palette_realm(Vec::new());
|
||||
r.run(
|
||||
"var p = new Window('palette', 'T'); p.add('button', undefined, 'Go'); p.show(); var hiding = false; \
|
||||
Object.defineProperty(p, 'text', {get: function () { if (hiding) { hiding = false; p.hide(); return 'New'; } return 'T'; }});",
|
||||
)
|
||||
.unwrap();
|
||||
let updates = |calls: &Calls| calls.borrow().iter().filter(|(n, _)| n == "paletteUpdate").count();
|
||||
let before = updates(&calls);
|
||||
r.run("hiding = true;").unwrap();
|
||||
r.refresh_script_ui().expect("the refresh reads the title");
|
||||
assert_eq!(r.run("[hiding, p.visible].join()").unwrap(), JsValue::String("false,false".into()), "the getter ran and hid the palette");
|
||||
assert_eq!(updates(&calls), before, "the host keeps the controls the palette had when it was hidden");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_palette_event_does_not_run_a_handler_whose_getter_closed_the_palette() {
|
||||
let (mut r, calls) = palette_realm(vec![palette_event(1.0, click(1))]);
|
||||
@@ -1339,19 +1355,24 @@ fn a_palette_list_change_runs_no_on_change_once_an_item_s_text_getter_removed_th
|
||||
|
||||
#[test]
|
||||
fn a_palette_list_change_throws_when_a_later_item_s_text_getter_changes_an_earlier_item_s_text() {
|
||||
let (mut r, _) = palette_realm(vec![seen_list_change(0.0)]);
|
||||
// The second read of the second item's text, which compares it with the items the person saw,
|
||||
// changes the first item's text, which that comparison already took.
|
||||
r.run(
|
||||
"var p = new Window('palette'); var l = p.add('listbox', undefined, ['a', 'b']); var got = []; \
|
||||
l.onChange = function () { got.push(String(l.selection)); }; var reads = -1; \
|
||||
Object.defineProperty(l.items[1], 'text', {get: function () { if (reads >= 0 && ++reads == 2) { l.items[0].text = 'z'; } return 'b'; }}); \
|
||||
p.show();",
|
||||
)
|
||||
.unwrap();
|
||||
let e = r.run("reads = 0; try { Window.__vcPaletteEvent(); 'none'; } catch (e) { e.message; }").unwrap();
|
||||
assert_eq!(e, JsValue::String("a palette's list changed before the person's choice was taken".into()));
|
||||
assert_eq!(r.run("got.join()").unwrap(), JsValue::String("".into()));
|
||||
// changes the first item's text, which that comparison already took. It also puts back a plain
|
||||
// `b` in place of its getter, so that only the first item's change can end the choice: without
|
||||
// that change, the same choice reaches `onChange`.
|
||||
for (mutate, error, got) in [(true, "a palette's list changed before the person's choice was taken", ""), (false, "none", "a")] {
|
||||
let (mut r, _) = palette_realm(vec![seen_list_change(0.0)]);
|
||||
r.run(&format!(
|
||||
"var mutate = {mutate}; var p = new Window('palette'); var l = p.add('listbox', undefined, ['a', 'b']); var got = []; \
|
||||
l.onChange = function () {{ got.push(String(l.selection)); }}; var reads = -1; var second = l.items[1]; \
|
||||
Object.defineProperty(second, 'text', {{configurable: true, get: function () {{ if (reads >= 0 && ++reads == 2) {{ \
|
||||
if (mutate) {{ l.items[0].text = 'z'; }} Object.defineProperty(second, 'text', {{value: 'b', writable: true, configurable: true}}); }} \
|
||||
return 'b'; }}}}); p.show();"
|
||||
))
|
||||
.unwrap();
|
||||
let e = r.run("reads = 0; try { Window.__vcPaletteEvent(); 'none'; } catch (e) { e.message; }").unwrap();
|
||||
assert_eq!(e, JsValue::String(error.into()), "mutate: {mutate}");
|
||||
assert_eq!(r.run("got.join()").unwrap(), JsValue::String(got.into()), "mutate: {mutate}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -1144,7 +1144,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"ui.sampleScreenColor",
|
||||
"Sample Color from Screen",
|
||||
"",
|
||||
"{} or {stroke?: bool (default: the active proxy), picker?: bool (the open Color Picker instead)} show the system's color sampler (macOS; Linux through the XDG desktop portal's PickColor; Windows, a still copy of every monitor under a crosshair; browsers with an EyeDropper) and answer at once; the color the person picks anywhere on the screen then runs paint.setFill / paint.setStroke (one undo step) or becomes the Color Picker's color (field `color`), converted from display sRGB into the working RGB space; a cancel (Escape on macOS, Windows and in browsers; also a click of another mouse button or switching to another window on Windows) leaves the colors as they were. ui.inspect reports `screenSampler: true` until it answers; on Windows, a screen that can't be copied ends the wait with a status message; on Linux, a session without a portal that has PickColor, a portal that does not return from the call within 25 seconds (VectorCraft's own limit) or leaves the bus before it answers, and a portal that ends the request another way end the wait with a status message. An error without a sampler, while one is open, or with `picker` and no Color Picker open",
|
||||
"{} or {stroke?: bool (default: the active proxy), picker?: bool (the open Color Picker instead)} show the system's color sampler (macOS; Linux through the XDG desktop portal's PickColor; Windows, a still copy of every monitor under a crosshair; browsers with an EyeDropper) and answer at once; the color the person picks anywhere on the screen then runs paint.setFill / paint.setStroke (one undo step) or becomes the Color Picker's color (field `color`), converted from display sRGB into the working RGB space; a cancel (Escape on macOS, Windows and in browsers; also a click of another mouse button or switching to another window on Windows) leaves the colors as they were. Closing the Color Picker a `picker` sample is for, or stopping the script that opened it, ends the sample. ui.inspect reports `screenSampler: true` until it answers; on Windows, a screen that can't be copied ends the wait with a status message; on Linux, a session without a portal that has PickColor, a portal that does not return from the call within 25 seconds (VectorCraft's own limit) or leaves the bus before it answers, and a portal that ends the request another way end the wait with a status message. An error without a sampler, while one is open, or with `picker` and no Color Picker open",
|
||||
),
|
||||
(
|
||||
"ui.newBrush",
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
@@ -863,6 +863,8 @@ impl VectorcraftApp {
|
||||
toast::post(&ctx, &WindowKey::main(), Toast::new(t.message).tone(tone(t.level)).timeout(Some(t.seconds as f32)));
|
||||
}
|
||||
menus::native::sync(self, &ctx);
|
||||
// A palette event whose start failed tries again after this pass's input.
|
||||
crate::script_palettes::clear_failed_start(self, &ctx);
|
||||
// A palette event that waited for an undo group this pass ended starts its run next frame.
|
||||
if crate::script_palettes::can_start(self) {
|
||||
ctx.request_repaint();
|
||||
|
||||
@@ -308,6 +308,13 @@ pub struct SymbolInstances {
|
||||
/// One of them has a scale, rotation or shear that Reset Transformation would change; measured
|
||||
/// on the first read.
|
||||
pub transformed: Option<bool>,
|
||||
/// The names of the symbols they are instances of, each once and sorted; found on the first
|
||||
/// read.
|
||||
pub names: Option<Vec<String>>,
|
||||
/// The symbol the selected objects share when every one is a symbol instance, blank when they
|
||||
/// are instances of different symbols, and `None` inside when nothing is selected or one is not
|
||||
/// an instance; found on the first read.
|
||||
pub shared: Option<Option<String>>,
|
||||
}
|
||||
|
||||
/// [`CanvasCache::print_tiling`]: the print tiling of (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"
|
||||
);
|
||||
}
|
||||
@@ -31,6 +31,7 @@ use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::ColorMode;
|
||||
use vectorcraft_engine::cmd::color_value;
|
||||
use vectorcraft_engine::cmd::swatchlib;
|
||||
use vectorcraft_engine::script::DialogAnswer;
|
||||
|
||||
use super::preview::LivePreview;
|
||||
use crate::panels::color::{WorkingRgb, color_of_values, gamut, model_values};
|
||||
@@ -49,6 +50,9 @@ pub(crate) enum Target {
|
||||
Artboard { document: u64, reverts: u64, index: usize },
|
||||
/// A colour row `key` of the open dialog `parent`.
|
||||
Answer { parent: DialogId, key: String },
|
||||
/// The answer to a running script's `app.showColorPicker`, which opened it on `color`; `cmyk`:
|
||||
/// the run's active document is in CMYK.
|
||||
Script { color: Color, cmyk: bool },
|
||||
}
|
||||
|
||||
impl Target {
|
||||
@@ -60,7 +64,8 @@ impl Target {
|
||||
let (document, reverts) = match self {
|
||||
Self::Fill { document, reverts } | Self::Stroke { document, reverts } => (*document, *reverts),
|
||||
Self::Artboard { document, reverts, .. } => (Some(*document), *reverts),
|
||||
Self::Answer { .. } => return None,
|
||||
// A script's picker answers the run whichever document is active.
|
||||
Self::Answer { .. } | Self::Script { .. } => return None,
|
||||
};
|
||||
match (app.session.active(), document) {
|
||||
(None, None) => None,
|
||||
@@ -261,28 +266,13 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
|
||||
};
|
||||
let dialogs = app.dialogs().ok_or("no window")?;
|
||||
let start = srgba(&color);
|
||||
let mut dialog = ColorPickerDialog::new(
|
||||
match (artboard, stroke) {
|
||||
(Some(_), _) => "artboard",
|
||||
(None, true) => "stroke",
|
||||
(None, false) => "fill",
|
||||
},
|
||||
tl!("Color Picker"),
|
||||
start,
|
||||
)
|
||||
.eyedropper(true)
|
||||
.add_to_swatches(false)
|
||||
.gamut(gamut(app))
|
||||
.working_rgb(WorkingRgb)
|
||||
.swatch_view(swatch_view(app));
|
||||
if app.session.active().is_some_and(|s| s.doc.color_mode == ColorMode::Cmyk)
|
||||
&& let Some(converter) = working_cmyk()
|
||||
{
|
||||
dialog = dialog.cmyk(&converter);
|
||||
}
|
||||
if matches!(color, Color::Cmyk { .. } | Color::Lab { .. }) {
|
||||
dialog = dialog.kept(model_values(&color));
|
||||
}
|
||||
let key = match (artboard, stroke) {
|
||||
(Some(_), _) => "artboard",
|
||||
(None, true) => "stroke",
|
||||
(None, false) => "fill",
|
||||
};
|
||||
let cmyk = app.session.active().is_some_and(|s| s.doc.color_mode == ColorMode::Cmyk);
|
||||
let mut dialog = picker(app, key, &color, cmyk);
|
||||
// The host replaces a picker only for the same document and artboard.
|
||||
if let Some((document, _, index, _)) = artboard {
|
||||
dialog = dialog.instance((document, index));
|
||||
@@ -313,6 +303,69 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
|
||||
Ok(Value::Null)
|
||||
}
|
||||
|
||||
/// The Color Picker with `key` on `color`, with the eyedropper, the gamut warning, the document's
|
||||
/// swatches and libraries, and with `cmyk` (a CMYK document) the working CMYK inks.
|
||||
fn picker(app: &VectorcraftApp, key: &str, color: &Color, cmyk: bool) -> ColorPickerDialog {
|
||||
let mut dialog = ColorPickerDialog::new(key, tl!("Color Picker"), srgba(color))
|
||||
.eyedropper(true)
|
||||
.add_to_swatches(false)
|
||||
.gamut(gamut(app))
|
||||
.working_rgb(WorkingRgb)
|
||||
.swatch_view(swatch_view(app));
|
||||
if cmyk && let Some(converter) = working_cmyk() {
|
||||
dialog = dialog.cmyk(&converter);
|
||||
}
|
||||
if matches!(color, Color::Cmyk { .. } | Color::Lab { .. }) {
|
||||
dialog = dialog.kept(model_values(color));
|
||||
}
|
||||
dialog
|
||||
}
|
||||
|
||||
/// Opens the Color Picker a running script's `app.showColorPicker` waits at, on `color`; `cmyk`:
|
||||
/// the run's own active document is in CMYK, which the session does not show between slices. It
|
||||
/// previews nothing; its OK and Cancel answer the run ([`finish`]).
|
||||
pub(crate) fn open_for_script(app: &mut VectorcraftApp, color: Color, cmyk: bool) {
|
||||
let Some(dialogs) = app.dialogs() else { return };
|
||||
// The given colour's own values, so that OK can tell an untouched pick from another model's.
|
||||
// The Only Web Colors setting of earlier pickers is not recalled, so the colour opens as given.
|
||||
let dialog = picker(app, SCRIPT_KEY, &color, cmyk).kept(model_values(&color)).web_colors_remembered(false);
|
||||
let id = dialogs.with(|h| h.open(dialog));
|
||||
app.color_dialogs.pickers.retain(|o| o.id != id);
|
||||
let target = Target::Script { color, cmyk };
|
||||
app.color_dialogs.pickers.push(Open {
|
||||
id,
|
||||
target,
|
||||
start: srgba(&color),
|
||||
keep: false,
|
||||
preview: LivePreview::default(),
|
||||
view: Vec::new(),
|
||||
row: None,
|
||||
});
|
||||
}
|
||||
|
||||
/// The key of the Color Picker a script opens.
|
||||
pub(crate) const SCRIPT_KEY: &str = "script";
|
||||
|
||||
/// The id of the Color Picker a running script waits at, while it is open or its answer is not
|
||||
/// yet given.
|
||||
pub(crate) fn script_picker(app: &VectorcraftApp) -> Option<DialogId> {
|
||||
app.color_dialogs.pickers.iter().find(|o| matches!(o.target, Target::Script { .. })).map(|o| o.id)
|
||||
}
|
||||
|
||||
/// Closes the script's Color Picker once the run no longer waits at it, and drops its answer. A
|
||||
/// screen pick the picker started ends with it; a pick another owner started keeps running.
|
||||
pub(crate) fn forget_script(app: &mut VectorcraftApp, ctx: &egui::Context) {
|
||||
let Some(id) = script_picker(app) else { return };
|
||||
app.color_dialogs.pickers.retain(|o| o.id != id);
|
||||
screen_color::cancel_for(app, ctx, owner(id));
|
||||
if let Some(dialogs) = app.dialogs() {
|
||||
dialogs.with(|h| {
|
||||
h.cancel_by_id(ctx, id);
|
||||
let _ = h.take_by_id::<ColorPickerDialog>(id);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// The reason `ui.dialog.confirm` with `params` fails, when it would confirm a picker whose Recolor
|
||||
/// Artwork row changed since the picker opened (OK would then answer nothing). The picker stays open.
|
||||
pub(crate) fn check_confirm(app: &VectorcraftApp, host: &craft::ui::dialog::DialogHost, params: &Value) -> Result<(), String> {
|
||||
@@ -394,6 +447,7 @@ fn settle(app: &mut VectorcraftApp, ctx: &egui::Context, dialogs: &craft::ui::sh
|
||||
})
|
||||
});
|
||||
let Some((current, gesture)) = live else {
|
||||
screen_color::cancel_for(app, ctx, owner(open.id));
|
||||
let result = dialogs.with(|h| h.take_by_id::<ColorPickerDialog>(open.id));
|
||||
finish(app, dialogs, open, result);
|
||||
return false;
|
||||
@@ -448,6 +502,15 @@ fn finish(
|
||||
dialogs.with(|h| h.answer_color(*parent, key, r.picked.color));
|
||||
}
|
||||
}
|
||||
// OK on the colour it opened with, in the model it opened with, gives that colour back.
|
||||
(Some(DialogResult::Ok(r)), Target::Script { color: given, cmyk }) => {
|
||||
let untouched = r.picked.color == open.start && r.picked.model == Some(model_values(given));
|
||||
let picked = if untouched { *given } else { in_model(*cmyk, color_of(&r.picked)) };
|
||||
app.session.script_answer(DialogAnswer::ColorPicker(Some(picked)));
|
||||
}
|
||||
(_, Target::Script { .. }) => {
|
||||
app.session.script_answer(DialogAnswer::ColorPicker(None));
|
||||
}
|
||||
(Some(DialogResult::Ok(r)), _) => {
|
||||
if let Err(e) = commit(app, open, preview, &r.picked) {
|
||||
app.status(e);
|
||||
@@ -462,14 +525,19 @@ fn paint_command(target: &Target, c: Color) -> (&'static str, Value) {
|
||||
match target {
|
||||
Target::Artboard { index, .. } => ("artboard.setProps", json!({ "index": index, "color": color_json(&c) })),
|
||||
Target::Stroke { .. } => ("paint.setStroke", json!({ "color": color_json(&c) })),
|
||||
Target::Fill { .. } | Target::Answer { .. } => ("paint.setFill", json!({ "color": color_json(&c) })),
|
||||
Target::Fill { .. } | Target::Answer { .. } | Target::Script { .. } => ("paint.setFill", json!({ "color": color_json(&c) })),
|
||||
}
|
||||
}
|
||||
|
||||
/// The picked colour as the document takes it: an RGB colour is CMYK in a CMYK document; CMYK,
|
||||
/// grey and Lab colours stay as they are.
|
||||
/// The picked colour as the active document takes it ([`in_model`]).
|
||||
fn in_document_model(app: &VectorcraftApp, c: Color) -> Color {
|
||||
if matches!(c, Color::Rgb { .. }) && app.session.active().is_some_and(|s| s.doc.color_mode == ColorMode::Cmyk) {
|
||||
in_model(app.session.active().is_some_and(|s| s.doc.color_mode == ColorMode::Cmyk), c)
|
||||
}
|
||||
|
||||
/// The picked colour as a document takes it: an RGB colour is CMYK in a CMYK document (`cmyk`);
|
||||
/// CMYK, grey and Lab colours stay as they are.
|
||||
fn in_model(cmyk: bool, c: Color) -> Color {
|
||||
if cmyk && matches!(c, Color::Rgb { .. }) {
|
||||
let [cy, m, y, k] = c.to_cmyk_managed(cms::active().settings().intent);
|
||||
return Color::cmyk(cy, m, y, k);
|
||||
}
|
||||
@@ -480,8 +548,9 @@ fn in_document_model(app: &VectorcraftApp, c: Color) -> Color {
|
||||
/// preview. Nothing previews until the colour first changes, nor without a selection (the colour
|
||||
/// then only becomes the default paint, on OK). An artboard shows it with or without a selection.
|
||||
fn preview(app: &mut VectorcraftApp, open: &mut Open, picked: &PickedColor) {
|
||||
// A picker over a command dialog only fills a row; the dialog previews it.
|
||||
if matches!(open.target, Target::Answer { .. }) || !open.target.in_active_document(app) {
|
||||
// A picker over a command dialog only fills a row; the dialog previews it. A script's picker
|
||||
// only answers the script.
|
||||
if matches!(open.target, Target::Answer { .. } | Target::Script { .. }) || !open.target.in_active_document(app) {
|
||||
return;
|
||||
}
|
||||
let (cmd, params) = paint_command(&open.target, in_document_model(app, color_of(picked)));
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -55,6 +55,7 @@
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
|
||||
use craft::color_ui::ui::ColorPickerDialog;
|
||||
use craft::host::{PickRequest, Picked};
|
||||
use craft::keymap::Key;
|
||||
use craft::theme::variant::Tone;
|
||||
@@ -78,6 +79,7 @@ use vectorcraft_engine::script::files::{MAX_ENTRIES, PickAnswer, PickerKind, Scr
|
||||
use vectorcraft_engine::script::printing::PreparedPrint;
|
||||
use vectorcraft_engine::script::{DialogAnswer, MAX_SOURCE_BYTES, ScriptDialog};
|
||||
|
||||
use super::color_picker;
|
||||
use super::script_window::{self, ScriptWindow};
|
||||
use crate::VectorcraftApp;
|
||||
use crate::file_asks::{self, Owner};
|
||||
@@ -580,6 +582,22 @@ pub(crate) fn forget<D: StackDialog>(app: &VectorcraftApp) {
|
||||
});
|
||||
}
|
||||
|
||||
/// [`forget`] for the Color Picker a script's `app.showColorPicker` opened.
|
||||
pub(crate) fn forget_color_picker(app: &mut VectorcraftApp) {
|
||||
let Some(ctx) = app.ui_ctx.clone() else { return };
|
||||
if color_picker::script_picker(app).is_none() {
|
||||
return;
|
||||
}
|
||||
let asking = with_host(app, |host, _| host.is_open::<CloseQuestion>()).unwrap_or(false);
|
||||
color_picker::forget_script(app, &ctx);
|
||||
if asking {
|
||||
with_host(app, |host, _| {
|
||||
let _ = host.take::<CloseQuestion>();
|
||||
host.open(close_question());
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// `ui.runScript`: the script at `path` or given as `source`; without either, pick a file.
|
||||
pub(crate) fn command(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
|
||||
if p.get("path").is_some() || p.get("source").is_some() {
|
||||
@@ -760,11 +778,13 @@ pub(crate) fn open_picker(app: &VectorcraftApp, p: ScriptPicker) {
|
||||
/// Cancel shows again as it was, with the events a ScriptUI dialog has not given the script yet and
|
||||
/// the text typed in its fields. Any other open dialog stays, and quitting asks nothing yet.
|
||||
pub(crate) fn ask_to_close(app: &mut VectorcraftApp) {
|
||||
let picker = color_picker::script_picker(app);
|
||||
with_host(app, |host, _| {
|
||||
let own = [
|
||||
host.get::<ScriptNotice>().map(StackDialog::id),
|
||||
host.get::<ScriptFiles>().map(StackDialog::id),
|
||||
host.get::<ScriptWindow>().map(StackDialog::id),
|
||||
picker.filter(|&id| host.get_by_id::<ColorPickerDialog>(id).is_some()),
|
||||
];
|
||||
match own.into_iter().flatten().find(|id| host.stack().is_top(*id)) {
|
||||
Some(parent) => {
|
||||
@@ -887,6 +907,7 @@ fn answer_close(app: &mut VectorcraftApp, close: Option<DialogResult<<CloseQuest
|
||||
forget::<ScriptNotice>(app);
|
||||
forget::<ScriptFiles>(app);
|
||||
forget::<ScriptWindow>(app);
|
||||
forget_color_picker(app);
|
||||
app.sync_views();
|
||||
}
|
||||
}
|
||||
@@ -1199,6 +1220,8 @@ mod tests {
|
||||
error_icon: false,
|
||||
no_as_default: true,
|
||||
preset: String::new(),
|
||||
color: None,
|
||||
cmyk_document: false,
|
||||
};
|
||||
let ctx = egui::Context::default();
|
||||
// A script's own confirm with the same text takes Yes.
|
||||
|
||||
@@ -218,6 +218,18 @@ pub(crate) fn keep_fields(w: &ScriptUiDialog, drafts: &mut BTreeMap<u64, String>
|
||||
/// as the script in `w` would check it first; when one is refused, every field keeps its text,
|
||||
/// `events` stays as it was and the error is returned.
|
||||
pub(crate) fn commit_texts(w: &ScriptUiDialog, drafts: &mut BTreeMap<u64, String>, events: &mut Vec<UiEvent>) -> Result<(), String> {
|
||||
commit_texts_over(w, drafts, events, &[])
|
||||
}
|
||||
|
||||
/// [`commit_texts`] for fields whose earlier changes still wait to be delivered: a draft of a field
|
||||
/// whose id is in `queued` is given even when it matches the field's text, since the script reads the
|
||||
/// waiting change's text first.
|
||||
pub(crate) fn commit_texts_over(
|
||||
w: &ScriptUiDialog,
|
||||
drafts: &mut BTreeMap<u64, String>,
|
||||
events: &mut Vec<UiEvent>,
|
||||
queued: &[u64],
|
||||
) -> Result<(), String> {
|
||||
let mut given = Vec::new();
|
||||
let mut changes = Vec::new();
|
||||
for (i, n) in w.nodes.iter().enumerate() {
|
||||
@@ -230,7 +242,7 @@ pub(crate) fn commit_texts(w: &ScriptUiDialog, drafts: &mut BTreeMap<u64, String
|
||||
continue;
|
||||
}
|
||||
if let Some(text) = drafts.get(&n.id) {
|
||||
if *text != n.text {
|
||||
if *text != n.text || queued.contains(&n.id) {
|
||||
changes.push(check_event(w, UiEvent::Change(i, UiValue::Text(text.clone())))?);
|
||||
}
|
||||
given.push(n.id);
|
||||
@@ -336,7 +348,7 @@ impl StackDialog for ScriptWindow {
|
||||
let dialog = Dialog::new(heading).buttons(buttons).initial_focus(initial).opened(Bind::bound(open));
|
||||
// The body can run twice in a pass (measure, then paint), so it only reports what the
|
||||
// person did; the dialog applies the last run's report after the container.
|
||||
let shown = dialog.show(ui, |ui, _| controls(ui, window, drafts, waiting));
|
||||
let shown = dialog.show(ui, |ui, _| controls(ui, window, drafts, waiting, &[]));
|
||||
let pass = shown.inner.unwrap_or_default();
|
||||
if pass.layer.is_some() {
|
||||
self.layer = pass.layer;
|
||||
@@ -416,7 +428,7 @@ pub(crate) fn heading(w: &ScriptUiDialog) -> String {
|
||||
|
||||
/// Draws the visible controls of the ScriptUI window `w` at the places the engine laid them out,
|
||||
/// with the text typed in its edit fields (`drafts`); none can be used unless `usable`.
|
||||
pub(crate) fn controls(ui: &mut Ui, w: &ScriptUiDialog, drafts: &BTreeMap<u64, String>, usable: bool) -> Pass {
|
||||
pub(crate) fn controls(ui: &mut Ui, w: &ScriptUiDialog, drafts: &BTreeMap<u64, String>, usable: bool, queued: &[u64]) -> Pass {
|
||||
let (width, height) = w.size();
|
||||
let size = egui::vec2(width.max(1.0), height.max(1.0));
|
||||
let mut pass = Pass { layer: overlay::drawing_parent(ui.ctx()), ..Pass::default() };
|
||||
@@ -432,7 +444,13 @@ pub(crate) fn controls(ui: &mut Ui, w: &ScriptUiDialog, drafts: &BTreeMap<u64, S
|
||||
continue;
|
||||
}
|
||||
let parent = containers.get(n.parent).copied().flatten();
|
||||
let place = Place { origin, enabled: usable && n.enabled, default: w.default_element == Some(i), parent };
|
||||
let place = Place {
|
||||
origin,
|
||||
enabled: usable && n.enabled,
|
||||
default: w.default_element == Some(i),
|
||||
parent,
|
||||
queued_text: queued.contains(&n.id),
|
||||
};
|
||||
let shown = control(ui, drafts, &place, (i, n, prompt_of(w, i)));
|
||||
if let Some(slot) = containers.get_mut(i) {
|
||||
*slot = shown.container;
|
||||
@@ -453,6 +471,7 @@ struct Place {
|
||||
enabled: bool,
|
||||
default: bool,
|
||||
parent: Option<egui::Id>,
|
||||
queued_text: bool,
|
||||
}
|
||||
|
||||
/// What drawing a control gave: the event it gives, whether an edit field has the keyboard focus,
|
||||
@@ -531,7 +550,7 @@ fn control(ui: &mut Ui, drafts: &BTreeMap<u64, String>, place: &Place, (i, n, pr
|
||||
shown.event = Some(UiEvent::Click(i));
|
||||
}
|
||||
}
|
||||
UiKind::EditText => shown = edit(ui, rect, drafts, enabled, (i, n, prompt)),
|
||||
UiKind::EditText => shown = edit(ui, rect, drafts, enabled, place.queued_text, (i, n, prompt)),
|
||||
UiKind::DropDownList => {
|
||||
let entries: Vec<Entry<Option<usize>>> = n.items.iter().enumerate().map(|(k, item)| Entry::new(Some(k), item.clone())).collect();
|
||||
let out = Select::new(list_name(n, prompt), Bind::given(n.selection), &entries).id_salt(salt).enabled(enabled).show_at(ui, rect);
|
||||
@@ -634,9 +653,15 @@ pub(crate) fn screen_reader_name(n: &UiNode, prompt: &str) -> String {
|
||||
/// accepts, so that a text that is too long can still be typed, refused and shortened.
|
||||
pub(crate) const DRAFT_CHARS: usize = 2 * MAX_TEXT_BYTES;
|
||||
|
||||
/// The change an edit field `n` at index `i` gives when its text `text` is committed: none for a
|
||||
/// read-only field, or for the field's own text unless a change of the field waits (`queued`).
|
||||
pub(crate) fn text_change(i: usize, n: &UiNode, text: String, queued: bool) -> Option<UiEvent> {
|
||||
(!n.readonly && (text != n.text || queued)).then_some(UiEvent::Change(i, UiValue::Text(text)))
|
||||
}
|
||||
|
||||
/// An edit field: its text is kept in the dialog while it is typed and given to the script when
|
||||
/// the field loses the focus, or at Enter in a one-line field.
|
||||
fn edit(ui: &mut Ui, rect: egui::Rect, drafts: &BTreeMap<u64, String>, enabled: bool, (i, n, prompt): (usize, &UiNode, &str)) -> Shown {
|
||||
fn edit(ui: &mut Ui, rect: egui::Rect, drafts: &BTreeMap<u64, String>, enabled: bool, queued: bool, (i, n, prompt): (usize, &UiNode, &str)) -> Shown {
|
||||
let mut text = drafts.get(&n.id).cloned().unwrap_or_else(|| n.text.clone());
|
||||
let mut field = TextField::new(screen_reader_name(n, prompt), Bind::bound(&mut text))
|
||||
.limit(DRAFT_CHARS)
|
||||
@@ -648,13 +673,15 @@ fn edit(ui: &mut Ui, rect: egui::Rect, drafts: &BTreeMap<u64, String>, enabled:
|
||||
}
|
||||
let out = field.show_at(ui, rect);
|
||||
let focused = out.response.has_focus();
|
||||
let mut draft = (out.events.value().is_some() || text != n.text).then(|| Some(text.clone()));
|
||||
let committed = out.submitted || out.events.committed().is_some() || out.response.lost_focus();
|
||||
if committed && text != n.text && !n.readonly {
|
||||
return Shown { event: Some(UiEvent::Change(i, UiValue::Text(text))), typing: true, container: None, draft: Some(None) };
|
||||
let queued = queued && (drafts.contains_key(&n.id) || out.events.value().is_some());
|
||||
let mut draft = (out.events.value().is_some() || text != n.text || queued).then(|| Some(text.clone()));
|
||||
// The focus is on the field's text part, so the text part's focus loss is the one that counts.
|
||||
let committed = out.submitted || out.events.committed().is_some() || out.text_lost_focus;
|
||||
if committed && let Some(event) = text_change(i, n, text.clone(), queued) {
|
||||
return Shown { event: Some(event), typing: true, container: None, draft: Some(None) };
|
||||
}
|
||||
// A text the script refused stays in the field until the person changes it.
|
||||
if !focused && text == n.text {
|
||||
if !focused && text == n.text && !queued {
|
||||
draft = Some(None);
|
||||
}
|
||||
Shown { event: None, typing: focused || committed, container: None, draft }
|
||||
|
||||
@@ -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)]
|
||||
|
||||
@@ -1145,7 +1145,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"ui.sampleScreenColor",
|
||||
"Sample Color from Screen",
|
||||
"",
|
||||
"{} or {stroke?: bool (default: the active proxy), picker?: bool (the open Color Picker instead)} show the system's color sampler (macOS; Linux through the XDG desktop portal's PickColor; Windows, a still copy of every monitor under a crosshair; browsers with an EyeDropper) and answer at once; the color the person picks anywhere on the screen then runs paint.setFill / paint.setStroke (one undo step) or becomes the Color Picker's color (field `color`), converted from display sRGB into the working RGB space; a cancel (Escape on macOS, Windows and in browsers; also a click of another mouse button or switching to another window on Windows) leaves the colors as they were. ui.inspect reports `screenSampler: true` until it answers; on Windows, a screen that can't be copied ends the wait with a status message; on Linux, a session without a portal that has PickColor, a portal that does not return from the call within 25 seconds (VectorCraft's own limit) or leaves the bus before it answers, and a portal that ends the request another way end the wait with a status message. An error without a sampler, while one is open, or with `picker` and no Color Picker open",
|
||||
"{} or {stroke?: bool (default: the active proxy), picker?: bool (the open Color Picker instead)} show the system's color sampler (macOS; Linux through the XDG desktop portal's PickColor; Windows, a still copy of every monitor under a crosshair; browsers with an EyeDropper) and answer at once; the color the person picks anywhere on the screen then runs paint.setFill / paint.setStroke (one undo step) or becomes the Color Picker's color (field `color`), converted from display sRGB into the working RGB space; a cancel (Escape on macOS, Windows and in browsers; also a click of another mouse button or switching to another window on Windows) leaves the colors as they were. Closing the Color Picker a `picker` sample is for, or stopping the script that opened it, ends the sample. ui.inspect reports `screenSampler: true` until it answers; on Windows, a screen that can't be copied ends the wait with a status message; on Linux, a session without a portal that has PickColor, a portal that does not return from the call within 25 seconds (VectorCraft's own limit) or leaves the bus before it answers, and a portal that ends the request another way end the wait with a status message. An error without a sampler, while one is open, or with `picker` and no Color Picker open",
|
||||
),
|
||||
(
|
||||
"ui.newBrush",
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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)))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -323,12 +323,9 @@ fn instance_flags(app: &VectorcraftApp) -> InstanceFlags {
|
||||
}
|
||||
}
|
||||
|
||||
/// The names of the symbols the selected instances are instances of, each once.
|
||||
fn linked_symbols(app: &mut VectorcraftApp) -> Vec<String> {
|
||||
let Some(doc) = app.session.active().map(|st| st.doc.clone()) else { return vec![] };
|
||||
let Some(found) = selected_instances(app) else { return vec![] };
|
||||
let mut names: Vec<String> = found
|
||||
.ids
|
||||
/// The names of the symbols the instances `ids` of `doc` are instances of, each once and sorted.
|
||||
fn symbol_names(doc: &Document, ids: &[NodeId]) -> Vec<String> {
|
||||
let mut names: Vec<String> = ids
|
||||
.iter()
|
||||
.filter_map(|id| match doc.node(*id).map(|n| &n.kind) {
|
||||
Some(NodeKind::SymbolInstance { symbol, .. }) => Some(symbol.clone()),
|
||||
@@ -340,6 +337,15 @@ fn linked_symbols(app: &mut VectorcraftApp) -> Vec<String> {
|
||||
names
|
||||
}
|
||||
|
||||
/// The names of the symbols the selected instances are instances of, each once, looked up once per
|
||||
/// (document uid, revision) ([`SymbolInstances::names`]).
|
||||
fn linked_symbols(app: &mut VectorcraftApp) -> Vec<String> {
|
||||
let Some(doc) = app.session.active().map(|st| st.doc.clone()) else { return vec![] };
|
||||
let Some(found) = selected_instances(app) else { return vec![] };
|
||||
let ids = &found.ids;
|
||||
found.names.get_or_insert_with(|| symbol_names(&doc, ids)).clone()
|
||||
}
|
||||
|
||||
/// Collect the IDs of selected instances of symbol `name` (including inside groups).
|
||||
fn selected_symbol_instances(app: &VectorcraftApp, name: &str) -> Vec<u64> {
|
||||
let mut ids = vec![];
|
||||
@@ -431,19 +437,40 @@ fn transformed_instances_selected(app: &mut VectorcraftApp) -> bool {
|
||||
*found.transformed.get_or_insert_with(|| transformed(&doc, ids))
|
||||
}
|
||||
|
||||
/// The symbols of the selected objects when every one is a symbol instance; `None` otherwise.
|
||||
fn selected_instance_symbols(app: &VectorcraftApp) -> Option<Vec<String>> {
|
||||
/// The symbol the selected objects of `st` share when every one is a symbol instance, blank when
|
||||
/// they are instances of different symbols; `None` when nothing is selected or one is not an
|
||||
/// instance.
|
||||
fn shared_symbol(st: &DocState) -> Option<String> {
|
||||
let mut shared: Option<&str> = None;
|
||||
for id in &st.selection.objects {
|
||||
let Some(NodeKind::SymbolInstance { symbol, .. }) = st.doc.node(*id).map(|n| &n.kind) else { return None };
|
||||
if shared.is_some_and(|s| s != symbol) {
|
||||
shared = Some("");
|
||||
} else if shared.is_none() {
|
||||
shared = Some(symbol);
|
||||
}
|
||||
}
|
||||
shared.map(str::to_string)
|
||||
}
|
||||
|
||||
/// [`shared_symbol`] of the active document, kept in [`SymbolInstances::shared`] once per
|
||||
/// (document uid, revision). While that version's selection has not been walked for its instances,
|
||||
/// the walk runs only when instances alone are selected, so a selected group is not walked for the
|
||||
/// Control bar.
|
||||
fn selected_shared_symbol(app: &mut VectorcraftApp) -> Option<String> {
|
||||
let st = app.session.active()?;
|
||||
let symbols: Option<Vec<String>> = st
|
||||
.selection
|
||||
.objects
|
||||
.iter()
|
||||
.map(|id| match st.doc.node(*id).map(|n| &n.kind) {
|
||||
Some(NodeKind::SymbolInstance { symbol, .. }) => Some(symbol.clone()),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
symbols.filter(|s| !s.is_empty())
|
||||
let walked = match &app.canvas.symbol_instances {
|
||||
Some((key, found)) if *key == (st.uid, st.revision) => match &found.shared {
|
||||
Some(shared) => return shared.clone(),
|
||||
None => true,
|
||||
},
|
||||
_ => false,
|
||||
};
|
||||
let shared = shared_symbol(st);
|
||||
if walked || shared.is_some() {
|
||||
selected_instances(app)?.shared = Some(shared.clone());
|
||||
}
|
||||
shared
|
||||
}
|
||||
|
||||
/// The Control bar's Replace menu while symbol instances alone are selected: the document's
|
||||
@@ -456,10 +483,9 @@ fn selected_instance_symbols(app: &VectorcraftApp) -> Option<Vec<String>> {
|
||||
/// by its rank before the Transform link. Returns whether it drew them (symbol instances alone are
|
||||
/// selected).
|
||||
pub(crate) fn control_bar(app: &mut VectorcraftApp, ui: &mut Ui) -> bool {
|
||||
let Some(symbols) = selected_instance_symbols(app) else { return false };
|
||||
let Some(shared) = selected_shared_symbol(app) else { return false };
|
||||
let Some(st) = app.session.active() else { return false };
|
||||
let entries: Vec<Entry<String>> = st.doc.symbols.iter().map(|s| Entry::new(s.name.clone(), s.name.clone())).collect();
|
||||
let shared = symbols.first().filter(|first| symbols.iter().all(|s| s == *first)).cloned().unwrap_or_default();
|
||||
// Reset: Reset Transformation, enabled while an instance's scale, rotation or shear differs
|
||||
// from its symbol's.
|
||||
let transformed = transformed_instances_selected(app);
|
||||
|
||||
@@ -1173,6 +1173,127 @@ fn properties_and_symbols_panels_walk_the_selection_once_per_revision() {
|
||||
assert_eq!(scans(), before + 1);
|
||||
}
|
||||
|
||||
/// The names of the symbols the selected instances are instances of, each once, found by walking
|
||||
/// every selected subtree on each call: what the cached list must match.
|
||||
fn walked_names(app: &VectorcraftApp) -> Vec<String> {
|
||||
let Some(st) = app.session.active() else { return vec![] };
|
||||
let mut names = vec![];
|
||||
for n in st.selection.objects.iter().filter_map(|id| st.doc.node(*id)) {
|
||||
n.walk(&mut |c| {
|
||||
if let NodeKind::SymbolInstance { symbol, .. } = &c.kind {
|
||||
names.push(symbol.clone());
|
||||
}
|
||||
});
|
||||
}
|
||||
names.sort();
|
||||
names.dedup();
|
||||
names
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
/// [`panel_and_bar_lookups`] of this thread.
|
||||
static PANEL_AND_BAR_LOOKUPS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// The lookups by id that [`panel_and_bar`] has made on this thread, without those of the menus
|
||||
/// the harness's frames rebuild.
|
||||
fn panel_and_bar_lookups() -> u64 {
|
||||
PANEL_AND_BAR_LOOKUPS.with(std::cell::Cell::get)
|
||||
}
|
||||
|
||||
/// The Symbols panel and the symbol instances' controls of the Control bar.
|
||||
fn panel_and_bar(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
let before = vectorcraft_doc::path_lookups();
|
||||
show(app, ui);
|
||||
control_bar(app, ui);
|
||||
PANEL_AND_BAR_LOOKUPS.with(|n| n.set(n.get() + vectorcraft_doc::path_lookups() - before));
|
||||
}
|
||||
|
||||
/// The Symbols panel finds the names of the selected instances' symbols, and the Control bar the
|
||||
/// symbol they share, once per document revision: over idle frames with 1,024 instances selected,
|
||||
/// their draws look up at most one node per instance in all, and both follow a rename, Undo and a
|
||||
/// new selection.
|
||||
#[test]
|
||||
fn linked_symbol_names_are_found_once_per_revision() {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 400, "height": 200})).unwrap();
|
||||
for (x, name) in [(10, "S"), (60, "T")] {
|
||||
app.run("shape.rectangle", json!({"x": x, "y": 10, "width": 40, "height": 40})).unwrap();
|
||||
app.run("symbol.new", json!({"name": name})).unwrap();
|
||||
}
|
||||
// Two instances, doubled nine times.
|
||||
for _ in 0..9 {
|
||||
app.run("select.all", json!({})).unwrap();
|
||||
app.run("edit.duplicate", json!({})).unwrap();
|
||||
}
|
||||
app.run("select.all", json!({})).unwrap();
|
||||
let instances = app.session.active().map_or(0, |st| st.selection.objects.len()) as u64;
|
||||
assert_eq!(instances, 1024);
|
||||
let mut p = harness(app, panel_and_bar);
|
||||
assert_eq!(linked_symbols(&mut p.app()), ["S", "T"]);
|
||||
let before = panel_and_bar_lookups();
|
||||
for _ in 0..10 {
|
||||
p.frame();
|
||||
}
|
||||
let lookups = panel_and_bar_lookups() - before;
|
||||
assert!(lookups <= instances, "10 idle frames looked up {lookups} nodes for {instances} selected instances");
|
||||
let check = |p: &mut Panel, want: &[&str], shared: Option<&str>, what: &str| {
|
||||
p.frame();
|
||||
let mut app = p.app();
|
||||
assert_eq!(linked_symbols(&mut app), want, "{what}");
|
||||
assert_eq!(walked_names(&app), want, "{what}: a walk of the selection agrees");
|
||||
assert_eq!(selected_shared_symbol(&mut app).as_deref(), shared, "{what}: the Control bar's symbol");
|
||||
assert_eq!(app.session.active().and_then(shared_symbol).as_deref(), shared, "{what}: a walk of the selection agrees");
|
||||
};
|
||||
check(&mut p, &["S", "T"], Some(""), "two symbols' instances");
|
||||
p.app().run("symbol.options", json!({"name": "S", "newName": "R"})).unwrap();
|
||||
check(&mut p, &["R", "T"], Some(""), "after a rename");
|
||||
p.app().run("edit.undo", json!({})).unwrap();
|
||||
check(&mut p, &["S", "T"], Some(""), "after Undo");
|
||||
let t = instance_of(&p.app(), "T").expect("a T instance");
|
||||
p.app().run("select.set", json!({"ids": [t.0]})).unwrap();
|
||||
check(&mut p, &["T"], Some("T"), "one T instance selected");
|
||||
p.app().run("symbol.options", json!({"name": "T", "newName": "U"})).unwrap();
|
||||
check(&mut p, &["U"], Some("U"), "the selected instance's symbol renamed");
|
||||
let group = p.app().run("object.group", json!({})).unwrap()["id"].clone();
|
||||
p.app().run("select.set", json!({"ids": [group]})).unwrap();
|
||||
check(&mut p, &["U"], None, "the instance in a selected group");
|
||||
p.app().run("select.none", json!({})).unwrap();
|
||||
check(&mut p, &[], None, "nothing selected");
|
||||
}
|
||||
|
||||
/// The Control bar's symbol does not walk a selected group for its instances while no reader has
|
||||
/// walked that document version, as a group never shows the symbol controls; instances alone
|
||||
/// selected are walked once, and a version already walked keeps its answer.
|
||||
#[test]
|
||||
fn the_control_bar_walks_only_a_selection_of_instances() {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 200, "height": 100})).unwrap();
|
||||
app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap();
|
||||
let inst = app.run("symbol.new", json!({"name": "S"})).unwrap()["id"].clone();
|
||||
app.run("select.set", json!({"ids": [inst]})).unwrap();
|
||||
let group = app.run("object.group", json!({})).unwrap()["id"].clone();
|
||||
app.run("select.set", json!({"ids": [group]})).unwrap();
|
||||
let before = scans();
|
||||
for _ in 0..3 {
|
||||
assert_eq!(selected_shared_symbol(&mut app), None, "a selected group");
|
||||
}
|
||||
assert_eq!(scans(), before, "a selected group is not walked");
|
||||
assert!(has_instances_selected(&mut app), "the panel's readers walk the group");
|
||||
let lookups = vectorcraft_doc::path_lookups();
|
||||
for _ in 0..3 {
|
||||
assert_eq!(selected_shared_symbol(&mut app), None, "a walked group");
|
||||
}
|
||||
let lookups = vectorcraft_doc::path_lookups() - lookups;
|
||||
assert!(lookups <= 1, "3 reads of a walked group's symbol looked up {lookups} nodes");
|
||||
assert_eq!(scans(), before + 1, "one walk for the group");
|
||||
app.run("select.set", json!({"ids": [inst]})).unwrap();
|
||||
for _ in 0..3 {
|
||||
assert_eq!(selected_shared_symbol(&mut app).as_deref(), Some("S"), "a selected instance");
|
||||
}
|
||||
assert_eq!(scans(), before + 2, "one walk for the instance");
|
||||
}
|
||||
|
||||
/// The picture the panel's tile shows of an imported symbol frames the symbol's whole art.
|
||||
#[test]
|
||||
fn an_imported_symbols_thumbnail_frames_its_whole_art() {
|
||||
|
||||
@@ -433,9 +433,10 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
let states = row_states(st);
|
||||
let sort = st.variables_sort;
|
||||
let doc_uid = st.uid;
|
||||
let reverts = st.reverts;
|
||||
let (mut acts, mut pressed) = (Vec::new(), None);
|
||||
Stack::new().fill().footer(|ui, _| pressed = footer(ui, &states)).show(ui, |ui, _| {
|
||||
data_set_bar(ui, &rows.sets, &mut acts);
|
||||
data_set_bar(ui, &rows.sets, (doc_uid, reverts), &mut acts);
|
||||
variable_table(ui, &rows.vars, sort, &states, doc_uid, &mut acts);
|
||||
Text::new(tl!("Data Sets")).role(TypeRole::Heading).show(ui);
|
||||
data_set_list(ui, &rows.sets, &mut acts);
|
||||
@@ -463,9 +464,15 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
}
|
||||
}
|
||||
|
||||
/// The current data set across the top: its name in a box that renames it, the list that chooses
|
||||
/// another, and the arrows that step through them.
|
||||
fn data_set_bar(ui: &mut Ui, sets: &[SetRow], acts: &mut Vec<Act>) {
|
||||
/// The current data set across the top: its name in a box that renames it when the typed name is
|
||||
/// committed (Enter or leaving the box), the list that chooses another, and the arrows that step
|
||||
/// through them. `doc` is the document's uid and how many times File › Revert replaced its
|
||||
/// content. With the current data set's name, it is the box's edit target, so a name typed or
|
||||
/// being composed and not yet committed is dropped when another document, a reverted one or a data
|
||||
/// set with another name becomes current. Data sets have no identity besides their names, so a
|
||||
/// data set that replaces the current one under the same name in the same document takes the
|
||||
/// unfinished name.
|
||||
fn data_set_bar(ui: &mut Ui, sets: &[SetRow], doc: (u64, u64), acts: &mut Vec<Act>) {
|
||||
let current = sets.iter().find(|s| s.active).map(|s| s.name.as_str());
|
||||
Row::new().show(ui, |ui, _| {
|
||||
Field::new(tl!("Data Set")).show(ui, |ui, _| {
|
||||
@@ -477,9 +484,10 @@ fn data_set_bar(ui: &mut Ui, sets: &[SetRow], acts: &mut Vec<Act>) {
|
||||
}),
|
||||
)
|
||||
.enabled(current.is_some())
|
||||
.edit_target((doc, current))
|
||||
.show(ui)
|
||||
.events
|
||||
.landed()
|
||||
.committed()
|
||||
.cloned();
|
||||
if let (Some(from), Some(to)) = (current, typed) {
|
||||
acts.push(Act::Rename(from.to_owned(), to));
|
||||
@@ -1212,6 +1220,158 @@ mod tests {
|
||||
assert_eq!(undo_steps(&app), before + 1);
|
||||
}
|
||||
|
||||
/// A document whose one data set, "Spring", is current.
|
||||
fn add_spring(app: &mut VectorcraftApp) {
|
||||
let t = app.run("text.create", json!({"x": 10, "y": 40, "text": "Alice"})).unwrap()["id"].as_u64().unwrap();
|
||||
app.run("variable.define", json!({"name": "Name", "kind": "text"})).unwrap();
|
||||
app.run("variable.bind", json!({"variable": "Name", "ids": [t]})).unwrap();
|
||||
app.run("dataset.capture", json!({})).unwrap();
|
||||
app.run("dataset.rename", json!({"name": "Data Set 1", "newName": "Spring"})).unwrap();
|
||||
}
|
||||
|
||||
/// Clicks the Data Set box and types `text` over its name without pressing Enter.
|
||||
fn start_typing(panel: &mut crate::tests::panel_harness::Panel, text: &str) {
|
||||
panel.click_role(tl!("Data Set"), craft::ui::contract::Role::TEXT_INPUT);
|
||||
panel.key(egui::Key::A, egui::Modifiers::COMMAND);
|
||||
panel.type_text(text);
|
||||
}
|
||||
|
||||
/// A name typed into the Data Set box renames nothing until it is committed, and it is dropped
|
||||
/// when another document becomes current, even when that document's current data set has the
|
||||
/// same name: Enter there renames neither document's data set.
|
||||
#[test]
|
||||
fn an_unfinished_data_set_name_does_not_rename_another_documents_data_set() {
|
||||
use crate::tests::panel_harness::Panel;
|
||||
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
|
||||
for _ in 0..2 {
|
||||
app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
|
||||
add_spring(&mut app);
|
||||
}
|
||||
app.run("document.activate", json!({"index": 0})).unwrap();
|
||||
let steps = undo_steps(&app);
|
||||
let mut panel = Panel::new(app, show);
|
||||
let names = |panel: &Panel| -> Vec<Vec<String>> {
|
||||
panel.app().session.documents().iter().map(|st| st.doc.variables.datasets.iter().map(|d| d.name.clone()).collect()).collect()
|
||||
};
|
||||
start_typing(&mut panel, "Summer");
|
||||
assert_eq!(names(&panel), [["Spring"], ["Spring"]], "typing renames nothing before Enter");
|
||||
assert_eq!(undo_steps(&panel.app()), steps, "typing adds no undo step");
|
||||
panel.app().run("document.activate", json!({"index": 1})).unwrap();
|
||||
panel.frame();
|
||||
panel.frame();
|
||||
let field = craft::ui::contract::Role::TEXT_INPUT;
|
||||
assert!(panel.focused_nth(field, 0), "the box keeps the focus through the switch");
|
||||
assert_eq!(panel.value_role(tl!("Data Set"), field).as_deref(), Some("Spring"), "the box shows the other document's name");
|
||||
assert_eq!(names(&panel), [["Spring"], ["Spring"]], "switching documents renames nothing");
|
||||
panel.key(egui::Key::Enter, egui::Modifiers::NONE);
|
||||
assert_eq!(names(&panel), [["Spring"], ["Spring"]], "Enter in the other document renames neither data set");
|
||||
}
|
||||
|
||||
/// A name typed into the Data Set box and not yet committed is dropped by File › Revert, which
|
||||
/// restores a data set of the same name: Enter afterwards does not rename the restored one.
|
||||
#[test]
|
||||
fn an_unfinished_data_set_name_does_not_rename_the_data_set_file_revert_restores() {
|
||||
use crate::tests::panel_harness::Panel;
|
||||
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
|
||||
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.new", json!({"width": 300, "height": 200})).unwrap();
|
||||
add_spring(&mut app);
|
||||
let dir = vectorcraft_testkit::TempDir::new("variables-revert");
|
||||
app.run("file.saveAs", json!({"path": dir.join("Art.vectorcraft")})).unwrap();
|
||||
// An unsaved edit, so the revert has changes to throw away.
|
||||
app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 20, "height": 20})).unwrap();
|
||||
let mut panel = Panel::new(app, show);
|
||||
start_typing(&mut panel, "Summer");
|
||||
panel.app().run("file.revert", json!({"confirmed": true})).unwrap();
|
||||
assert_eq!(set_names(&mut panel.app()), ["Spring"], "the revert restores the data set");
|
||||
let steps = undo_steps(&panel.app());
|
||||
panel.frame();
|
||||
panel.frame();
|
||||
let field = craft::ui::contract::Role::TEXT_INPUT;
|
||||
assert!(panel.focused_nth(field, 0), "the box keeps the focus through the revert");
|
||||
assert_eq!(panel.value_role(tl!("Data Set"), field).as_deref(), Some("Spring"), "the box shows the restored name");
|
||||
panel.key(egui::Key::Enter, egui::Modifiers::NONE);
|
||||
assert_eq!(set_names(&mut panel.app()), ["Spring"], "the restored data set keeps its name");
|
||||
assert_eq!(undo_steps(&panel.app()), steps, "no rename runs");
|
||||
}
|
||||
|
||||
/// A name typed into the Data Set box and not yet committed is dropped when another data set of
|
||||
/// the same document becomes current: Enter afterwards renames neither data set. With the same
|
||||
/// data set current, Enter renames it.
|
||||
#[test]
|
||||
fn an_unfinished_data_set_name_does_not_rename_the_next_data_set() {
|
||||
use crate::tests::panel_harness::Panel;
|
||||
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
|
||||
add_spring(&mut app);
|
||||
app.run("dataset.capture", json!({"name": "Autumn"})).unwrap();
|
||||
app.run("dataset.select", json!({"name": "Spring"})).unwrap();
|
||||
let mut panel = Panel::new(app, show);
|
||||
start_typing(&mut panel, "Summer");
|
||||
panel.app().run("dataset.next", json!({})).unwrap();
|
||||
panel.frame();
|
||||
panel.frame();
|
||||
let field = craft::ui::contract::Role::TEXT_INPUT;
|
||||
assert_eq!(panel.value_role(tl!("Data Set"), field).as_deref(), Some("Autumn"), "the box shows the next data set's name");
|
||||
panel.key(egui::Key::Enter, egui::Modifiers::NONE);
|
||||
assert_eq!(set_names(&mut panel.app()), ["Spring", "Autumn"], "Enter renames neither data set");
|
||||
start_typing(&mut panel, "Winter");
|
||||
panel.key(egui::Key::Enter, egui::Modifiers::NONE);
|
||||
assert_eq!(set_names(&mut panel.app()), ["Spring", "Winter"], "Enter renames the data set the name was typed for");
|
||||
}
|
||||
|
||||
/// A name being composed with an input method in the Data Set box is dropped when another data
|
||||
/// set becomes current: the composition's commit and Enter rename neither data set.
|
||||
#[test]
|
||||
fn a_composed_data_set_name_does_not_rename_the_next_data_set() {
|
||||
use crate::tests::panel_harness::Panel;
|
||||
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
|
||||
add_spring(&mut app);
|
||||
app.run("dataset.capture", json!({"name": "Autumn"})).unwrap();
|
||||
app.run("dataset.select", json!({"name": "Spring"})).unwrap();
|
||||
let mut panel = Panel::new(app, show);
|
||||
panel.click_role(tl!("Data Set"), craft::ui::contract::Role::TEXT_INPUT);
|
||||
let preedit = |text: &str| egui::Event::Ime(egui::ImeEvent::Preedit { text: text.into(), active_range_chars: Some(0..text.chars().count()) });
|
||||
let field = craft::ui::contract::Role::TEXT_INPUT;
|
||||
panel.frame_with(vec![preedit("Sum")]);
|
||||
assert!(panel.value_role(tl!("Data Set"), field).is_some_and(|name| name.contains("Sum")), "the box shows the composition");
|
||||
panel.app().run("dataset.next", json!({})).unwrap();
|
||||
panel.frame();
|
||||
panel.frame();
|
||||
assert!(panel.focused_nth(field, 0), "the box keeps the focus through the switch");
|
||||
assert_eq!(panel.value_role(tl!("Data Set"), field).as_deref(), Some("Autumn"), "the box shows the next data set's name");
|
||||
panel.frame_with(vec![egui::Event::Ime(egui::ImeEvent::Commit("Summer".into()))]);
|
||||
assert_eq!(panel.value_role(tl!("Data Set"), field).as_deref(), Some("Autumn"), "the commit does not reach the box");
|
||||
panel.key(egui::Key::Enter, egui::Modifiers::NONE);
|
||||
assert_eq!(set_names(&mut panel.app()), ["Spring", "Autumn"], "the composition renames neither data set");
|
||||
}
|
||||
|
||||
/// Leaving the Data Set box with Tab commits the typed name as one undo step, and Escape puts
|
||||
/// the current name back without renaming anything.
|
||||
#[test]
|
||||
fn leaving_the_data_set_box_renames_once_and_escape_renames_nothing() {
|
||||
use crate::tests::panel_harness::Panel;
|
||||
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
|
||||
add_spring(&mut app);
|
||||
let steps = undo_steps(&app);
|
||||
let mut panel = Panel::new(app, show);
|
||||
let field = craft::ui::contract::Role::TEXT_INPUT;
|
||||
start_typing(&mut panel, "Summer");
|
||||
panel.key(egui::Key::Escape, egui::Modifiers::NONE);
|
||||
assert_eq!(panel.value_role(tl!("Data Set"), field).as_deref(), Some("Spring"), "Escape puts the name back");
|
||||
panel.key(egui::Key::Enter, egui::Modifiers::NONE);
|
||||
assert_eq!(set_names(&mut panel.app()), ["Spring"], "Escape renames nothing");
|
||||
assert_eq!(undo_steps(&panel.app()), steps, "Escape adds no undo step");
|
||||
start_typing(&mut panel, "Summer");
|
||||
assert_eq!(set_names(&mut panel.app()), ["Spring"], "typing renames nothing");
|
||||
panel.key(egui::Key::Tab, egui::Modifiers::NONE);
|
||||
assert_eq!(set_names(&mut panel.app()), ["Summer"], "Tab commits the typed name");
|
||||
assert_eq!(undo_steps(&panel.app()), steps + 1, "the rename is one undo step");
|
||||
}
|
||||
|
||||
/// A press on a column header sorts the list by that column, and a second press on it reverses
|
||||
/// the order, as `variable.list` reports it; sorting is not an edit.
|
||||
#[test]
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -347,9 +347,15 @@ pub(crate) const DESCRIPTIONS: &[(&str, &str)] = &[
|
||||
"When a document opens, a linked EPS image that shows its saved preview keeps it instead of reading the EPS file again; changed files still follow Update Links.",
|
||||
),
|
||||
("pdfImportEmbeddedFonts", "Uses a PDF's embedded glyphs for imported text when its font is missing; off, it uses the fallback font."),
|
||||
(
|
||||
"smoothBitmaps",
|
||||
"Smooths images unless Pixel Preview draws its own pixel raster and uses the setting below. \
|
||||
When off, image pixels have hard edges.",
|
||||
),
|
||||
(
|
||||
"antiAliasedBitmaps",
|
||||
"In Pixel Preview, images are drawn smoothed; off, their pixels show with hard edges. Outside Pixel Preview, images are always smoothed.",
|
||||
"Smooths images while Pixel Preview draws its own pixel raster; otherwise the setting above applies. \
|
||||
When off, image pixels have hard edges.",
|
||||
),
|
||||
(
|
||||
"updateLinks",
|
||||
|
||||
@@ -524,6 +524,19 @@ impl PreferencesDraft for Live<'_> {
|
||||
let read = self.w.source.get::<Map<String, Value>>(AGENTS_KEY).unwrap_or_default();
|
||||
let given: Map<String, Value> =
|
||||
agents.iter().filter(|(k, v)| *k != "allowAgentControl" && read.get(*k) != Some(*v)).map(|(k, v)| (k.clone(), v.clone())).collect();
|
||||
// Agents can't widen the folders they work in. Once automation drove the window, its agent settings are
|
||||
// put back as they were read for as long as it stays open (a field may still hold injected text), and OK
|
||||
// applies nothing. An OK automation sends is refused and leaves the draft as it is.
|
||||
if !given.is_empty() && self.app.automation_is_acting() {
|
||||
return Err(tl!("Agents can't change the agent settings: the person sets them in Preferences › AI Integrations.").into());
|
||||
}
|
||||
if !given.is_empty() && self.w.automated {
|
||||
self.w.draft.set(AGENTS_KEY, &read);
|
||||
return Err(tl!(
|
||||
"The agent settings were changed while automation used this window, so they were put back: only the person at the keyboard can change them. Close Preferences and open it again to change them."
|
||||
)
|
||||
.into());
|
||||
}
|
||||
if !given.is_empty() {
|
||||
self.app.run("prefs.agents", Value::Object(given))?;
|
||||
}
|
||||
|
||||
@@ -1616,6 +1616,83 @@ fn ai_integrations_page_saves_the_agent_settings_on_ok() {
|
||||
assert_eq!(saved[0].when_app_closed, craft::automation::agents::WhenAppClosed::Error);
|
||||
}
|
||||
|
||||
/// Once input injected through the control channel has reached the open window, OK does not save agent settings
|
||||
/// changed in it while it stays open: an edit made there (such as a folder typed on AI Integrations that lands in a
|
||||
/// later pass) is undone and OK says why. In a window the person opens again, OK saves what they enter.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn ok_does_not_save_agent_settings_edited_while_automation_drove_the_window() {
|
||||
use craft::automation::ControlRequest;
|
||||
use craft::automation::agents::{AgentSettings, AgentSwitch};
|
||||
use std::sync::{Arc, Mutex};
|
||||
let saved: Arc<Mutex<Vec<AgentSettings>>> = Arc::default();
|
||||
let into = saved.clone();
|
||||
let save: crate::agents::SaveFn = Box::new(move |s| {
|
||||
into.lock().unwrap().push(s.clone());
|
||||
Ok(())
|
||||
});
|
||||
let agents = crate::agents::Agents::new(None, "VectorCraft test".into(), AgentSwitch::fixed(true, false), AgentSettings::default(), save)
|
||||
.with_default_folder(None);
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
let mut a = crate::testing::windowed(VectorcraftApp::new(Session::new(), Services::default()).with_control(rx)).with_agents(agents);
|
||||
let ctx = crate::testing::ui_context();
|
||||
open(&mut a, Some(crate::agents::PAGE_TITLE));
|
||||
crate::testing::app_frame(&mut a, &ctx, egui::RawInput::default());
|
||||
let (req, _reply) = ControlRequest::new("ui.key", json!({"key": "A"}));
|
||||
tx.send(req).unwrap();
|
||||
a.run_control(&ctx);
|
||||
for _ in 0..3 {
|
||||
crate::testing::app_frame(&mut a, &ctx, egui::RawInput::default());
|
||||
}
|
||||
assert!(is_open(&a));
|
||||
let read_root = |a: &VectorcraftApp| a.prefs.as_ref().and_then(|w| w.draft.get::<String>("integrations.readRoot"));
|
||||
a.prefs.as_mut().unwrap().draft.set("integrations.readRoot", &"/everything");
|
||||
let refused = confirm(&mut a).expect_err("the agent folder edited while automation drove the window is not saved");
|
||||
assert!(refused.contains("person at the keyboard"), "{refused}");
|
||||
assert!(saved.lock().unwrap().is_empty(), "nothing saved");
|
||||
assert!(is_open(&a), "the window stays open");
|
||||
assert_ne!(read_root(&a).as_deref(), Some("/everything"), "the edit is undone in the window");
|
||||
a.prefs.as_mut().unwrap().draft.set("integrations.readRoot", &"/later");
|
||||
a.ui.answering_control = true;
|
||||
assert!(confirm(&mut a).is_err(), "an OK automation sends");
|
||||
a.ui.answering_control = false;
|
||||
assert_eq!(read_root(&a).as_deref(), Some("/later"), "an OK automation sends leaves the draft as it is");
|
||||
assert!(confirm(&mut a).is_err(), "the window stays guarded while it is open");
|
||||
assert!(saved.lock().unwrap().is_empty(), "still nothing saved");
|
||||
cancel(&mut a);
|
||||
open(&mut a, Some(crate::agents::PAGE_TITLE));
|
||||
a.prefs.as_mut().unwrap().draft.set("integrations.readRoot", &"/chosen");
|
||||
confirm(&mut a).unwrap();
|
||||
assert_eq!(saved.lock().unwrap().last().map(|s| s.read_root.clone()), Some("/chosen".to_string()), "the person's own edit");
|
||||
}
|
||||
|
||||
/// An OK a control request sends saves no agent setting the person changed, and leaves their edit in the window.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn ok_sent_by_automation_keeps_the_persons_agent_edit_unsaved_in_the_window() {
|
||||
use craft::automation::agents::{AgentSettings, AgentSwitch};
|
||||
use std::sync::{Arc, Mutex};
|
||||
let saved: Arc<Mutex<Vec<AgentSettings>>> = Arc::default();
|
||||
let into = saved.clone();
|
||||
let save: crate::agents::SaveFn = Box::new(move |s| {
|
||||
into.lock().unwrap().push(s.clone());
|
||||
Ok(())
|
||||
});
|
||||
let agents = crate::agents::Agents::new(None, "VectorCraft test".into(), AgentSwitch::fixed(true, false), AgentSettings::default(), save)
|
||||
.with_default_folder(None);
|
||||
let mut a = app().with_agents(agents);
|
||||
open(&mut a, Some(crate::agents::PAGE_TITLE));
|
||||
a.prefs.as_mut().unwrap().draft.set("integrations.readRoot", &"/mine");
|
||||
a.ui.answering_control = true;
|
||||
let r = confirm(&mut a);
|
||||
a.ui.answering_control = false;
|
||||
assert!(r.is_err(), "{r:?}");
|
||||
assert!(saved.lock().unwrap().is_empty());
|
||||
assert_eq!(a.prefs.as_ref().and_then(|w| w.draft.get::<String>("integrations.readRoot")).as_deref(), Some("/mine"));
|
||||
confirm(&mut a).unwrap();
|
||||
assert_eq!(saved.lock().unwrap().last().map(|s| s.read_root.clone()), Some("/mine".to_string()));
|
||||
}
|
||||
|
||||
/// OK sends only the agent settings changed in the window: one changed through `prefs.agents` while Preferences is
|
||||
/// open keeps its new value.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
|
||||
@@ -44,7 +44,8 @@ pub struct Done {
|
||||
/// The document rendered, and the options it was rendered with.
|
||||
pub doc: Arc<Document>,
|
||||
pub opts: RenderOptions,
|
||||
pub img: Rendered,
|
||||
/// The frame's pixels, a pixel a word ([`Renderer::render_words`]).
|
||||
pub img: Rendered<Vec<u32>>,
|
||||
pub ms: f64,
|
||||
/// [`vectorcraft_render::FrameStats::moved`] of the frame.
|
||||
pub moved: usize,
|
||||
|
||||
@@ -41,6 +41,33 @@ fn remember_doc(app: &VectorcraftApp, ctx: &egui::Context) {
|
||||
ctx.data_mut(|d| d.insert_temp(doc_key(), uid));
|
||||
}
|
||||
|
||||
/// Where the owner of the running pick is kept, as a hash of its key.
|
||||
fn owner_key() -> egui::Id {
|
||||
egui::Id::unique("screen-color-owner")
|
||||
}
|
||||
|
||||
fn owner_hash(owner: impl Hash) -> u64 {
|
||||
let mut hasher = std::collections::hash_map::DefaultHasher::new();
|
||||
owner.hash(&mut hasher);
|
||||
hasher.finish()
|
||||
}
|
||||
|
||||
fn remember_owner(ctx: &egui::Context, owner: impl Hash) {
|
||||
let key = owner_hash(owner);
|
||||
ctx.data_mut(|d| d.insert_temp(owner_key(), key));
|
||||
}
|
||||
|
||||
/// Ends the running pick when `owner` started it, and drops a color `owner` has not taken yet; a
|
||||
/// pick another owner started keeps running. The next pass finishes a capture the cancel ends.
|
||||
pub(crate) fn cancel_for(app: &mut VectorcraftApp, ctx: &egui::Context, owner: impl Hash) {
|
||||
let started_by = ctx.data(|d| d.get_temp::<u64>(owner_key()));
|
||||
if app.screen_pick.busy() && started_by == Some(owner_hash(&owner)) {
|
||||
app.screen_pick.cancel();
|
||||
ctx.request_repaint();
|
||||
}
|
||||
let _ = app.screen_pick.take(owner);
|
||||
}
|
||||
|
||||
/// The platform can capture the screen: the shell's capabilities say so and no capture has said it
|
||||
/// cannot. Without a window there is nothing to capture.
|
||||
pub fn available(app: &VectorcraftApp) -> bool {
|
||||
@@ -65,6 +92,10 @@ pub fn start(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
|
||||
}
|
||||
if let Some(ctx) = app.ui_ctx.clone() {
|
||||
remember_doc(app, &ctx);
|
||||
match picker {
|
||||
Some(id) => remember_owner(&ctx, crate::dialogs::color_picker::owner(id)),
|
||||
None => remember_owner(&ctx, if stroke { STROKE } else { FILL }),
|
||||
}
|
||||
}
|
||||
match picker {
|
||||
Some(id) => app.screen_pick.start(crate::dialogs::color_picker::owner(id)),
|
||||
@@ -78,6 +109,7 @@ pub fn start(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
|
||||
pub(crate) fn hold(app: &mut VectorcraftApp, ctx: &egui::Context, owner: impl Hash, gesture: ScreenPickGesture) -> Option<Srgba> {
|
||||
if !app.screen_pick.busy() {
|
||||
remember_doc(app, ctx);
|
||||
remember_owner(ctx, &owner);
|
||||
}
|
||||
app.screen_pick.hold(ctx, owner, gesture)
|
||||
}
|
||||
|
||||
@@ -89,6 +89,35 @@ fn the_color_pickers_eyedropper_samples_into_it() {
|
||||
assert_eq!(paints(&app).0, "#123456");
|
||||
}
|
||||
|
||||
/// Closing the Color Picker ends the sample its eyedropper started.
|
||||
#[test]
|
||||
fn closing_the_color_picker_ends_its_sample() {
|
||||
let (mut app, ctx) = app();
|
||||
app.run("ui.colorPicker", json!({})).unwrap();
|
||||
let id = app.color_dialogs.pickers.last().unwrap().id;
|
||||
assert_eq!(hold(&mut app, &ctx, crate::dialogs::color_picker::owner(id), ScreenPickGesture::Clicked), None);
|
||||
assert!(app.screen_pick.busy());
|
||||
assert!(app.dialogs().unwrap().with(|h| h.cancel_by_id(&ctx, id)));
|
||||
let mut out = ctx.run_ui(Default::default(), |ui| crate::dialogs::color_picker::pump(&mut app, ui.ctx()));
|
||||
out.textures_delta.clear();
|
||||
assert!(app.color_dialogs.pickers.is_empty());
|
||||
assert!(!app.screen_pick.busy(), "the sample ends with the picker");
|
||||
}
|
||||
|
||||
/// Ending a picker's pick drops the color it sampled and has not taken yet; another owner's color
|
||||
/// stays.
|
||||
#[test]
|
||||
fn ending_a_pick_drops_the_color_its_owner_has_not_taken() {
|
||||
let (mut app, ctx) = app();
|
||||
for own in [true, false] {
|
||||
assert_eq!(hold(&mut app, &ctx, "picker", ScreenPickGesture::Clicked), None);
|
||||
finish(&mut app, &ctx, Ok(srgba("#123456")));
|
||||
assert!(!app.screen_pick.busy(), "the capture finished");
|
||||
cancel_for(&mut app, &ctx, if own { "picker" } else { "other" });
|
||||
assert_eq!(take(&mut app, &ctx, "picker").is_some(), !own, "own {own}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A canceled capture changes nothing; a failed one reaches the status line.
|
||||
#[test]
|
||||
fn cancel_and_errors_leave_the_art_alone() {
|
||||
|
||||
@@ -55,12 +55,21 @@ pub(crate) struct PaletteWindow {
|
||||
/// field shows it until no change of that field waits, even while the palette's field holds the
|
||||
/// same text, since a run before the change may set the field to another one.
|
||||
pending: BTreeMap<u64, String>,
|
||||
queued_texts: Vec<u64>,
|
||||
open: bool,
|
||||
}
|
||||
|
||||
impl PaletteWindow {
|
||||
fn new(palette: ScriptPalette) -> Self {
|
||||
PaletteWindow { palette, drafts: BTreeMap::new(), draft_scopes: BTreeMap::new(), given: Vec::new(), pending: BTreeMap::new(), open: true }
|
||||
PaletteWindow {
|
||||
palette,
|
||||
drafts: BTreeMap::new(),
|
||||
draft_scopes: BTreeMap::new(),
|
||||
given: Vec::new(),
|
||||
pending: BTreeMap::new(),
|
||||
queued_texts: Vec::new(),
|
||||
open: true,
|
||||
}
|
||||
}
|
||||
|
||||
/// The palette as the session has it now. A typed text whose field the palette no longer has is
|
||||
@@ -68,6 +77,7 @@ impl PaletteWindow {
|
||||
/// [`vectorcraft_engine::Session::script_palette_changes_waiting`]).
|
||||
fn sync(&mut self, palette: ScriptPalette, waiting: &[(u64, u64)]) {
|
||||
self.palette = palette;
|
||||
self.queued_texts = waiting.iter().filter(|(id, _)| *id == self.palette.id).map(|(_, field)| *field).collect();
|
||||
script_window::keep_fields(&self.palette.dialog, &mut self.drafts);
|
||||
let (nodes, palette, given) = (&self.palette.dialog.nodes, self.palette.id, !self.given.is_empty());
|
||||
self.pending.retain(|id, _| (given || waiting.contains(&(palette, *id))) && nodes.iter().any(|n| n.id == *id));
|
||||
@@ -76,7 +86,7 @@ impl PaletteWindow {
|
||||
/// Draws the palette's controls in `ui` and takes what the person did, as its body does.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn paint(&mut self, ui: &mut Ui) {
|
||||
let pass = script_window::controls(ui, &shown_dialog(&self.palette.dialog, &self.pending), &self.drafts, true);
|
||||
let pass = script_window::controls(ui, &shown_dialog(&self.palette.dialog, &self.pending), &self.drafts, true, &self.queued_texts);
|
||||
self.take_pass(pass.drafts.into_iter().collect(), pass.events);
|
||||
}
|
||||
|
||||
@@ -105,8 +115,12 @@ impl PaletteWindow {
|
||||
/// the focus.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn commit_text(&mut self, i: usize, text: &str) {
|
||||
if let Some(n) = self.palette.dialog.nodes.get(i) {
|
||||
self.take_pass(vec![(n.id, None)], vec![UiEvent::Change(i, UiValue::Text(text.to_string()))]);
|
||||
let committed = shown_dialog(&self.palette.dialog, &self.pending)
|
||||
.nodes
|
||||
.get(i)
|
||||
.map(|n| (n.id, script_window::text_change(i, n, text.to_string(), self.queued_texts.contains(&n.id))));
|
||||
if let Some((id, event)) = committed {
|
||||
self.take_pass(vec![(id, None)], event.into_iter().collect());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -219,7 +233,7 @@ impl StackDialog for PaletteWindow {
|
||||
|
||||
fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option<DialogResult<()>> {
|
||||
let heading = script_window::heading(&self.palette.dialog);
|
||||
let PaletteWindow { palette, drafts, pending, open, .. } = self;
|
||||
let PaletteWindow { palette, drafts, pending, queued_texts, open, .. } = self;
|
||||
let dialog = shown_dialog(&palette.dialog, pending);
|
||||
let drafts_now = &*drafts;
|
||||
// The body can run twice in a pass (measure, then paint), so the last run's report is
|
||||
@@ -228,7 +242,7 @@ impl StackDialog for PaletteWindow {
|
||||
.modeless()
|
||||
.initial_focus(Initial::Keep)
|
||||
.opened(Bind::bound(open))
|
||||
.show(ui, |ui, _| script_window::controls(ui, &dialog, drafts_now, true));
|
||||
.show(ui, |ui, _| script_window::controls(ui, &dialog, drafts_now, true, queued_texts));
|
||||
let pass = shown.inner.unwrap_or_default();
|
||||
let mut events = pass.events;
|
||||
// The close box gives the script the close; the palette stays open until the script closes
|
||||
@@ -316,7 +330,7 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) {
|
||||
_ => true,
|
||||
});
|
||||
let before = at_pass.clone();
|
||||
let (batch, refused) = drafted(app, &p.dialog, &mut at_pass, &mut events, &scope, &pass_scope, &at_scopes);
|
||||
let (batch, refused) = drafted(app, p, &mut at_pass, &mut events, &scope, &pass_scope, &at_scopes);
|
||||
// A refused text keeps every later click and close out of line too.
|
||||
change_refused |= refused;
|
||||
// A text the click or close took leaves its field unless a later one was typed there.
|
||||
@@ -358,13 +372,14 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) {
|
||||
/// events with their scopes, and whether a text was refused.
|
||||
fn drafted(
|
||||
app: &mut VectorcraftApp,
|
||||
w: &ScriptUiDialog,
|
||||
p: &ScriptPalette,
|
||||
drafts: &mut BTreeMap<u64, String>,
|
||||
events: &mut Vec<UiEvent>,
|
||||
scope: &ScopeHandle,
|
||||
pass_scope: &ScopeHandle,
|
||||
draft_scopes: &BTreeMap<u64, ScopeHandle>,
|
||||
) -> (Vec<(ScopeHandle, UiEvent)>, bool) {
|
||||
let w = &p.dialog;
|
||||
let mut refused = false;
|
||||
if let Some(e) = script_window::keep_refused(w, drafts, events) {
|
||||
app.status(e);
|
||||
@@ -375,7 +390,10 @@ fn drafted(
|
||||
if events.iter().any(closing) {
|
||||
changes.extend(events.iter().filter(|e| !closing(e)).cloned());
|
||||
let existing = changes.len();
|
||||
match script_window::commit_texts(w, drafts, &mut changes) {
|
||||
// A draft that matches its field's text still goes in line when a change of that field
|
||||
// waits, so the click reads the draft and not the waiting change.
|
||||
let queued: Vec<u64> = app.session.script_palette_changes_waiting().into_iter().filter(|(id, _)| *id == p.id).map(|(_, e)| e).collect();
|
||||
match script_window::commit_texts_over(w, drafts, &mut changes, &queued) {
|
||||
Ok(()) => {
|
||||
drop(changes.drain(..existing));
|
||||
}
|
||||
@@ -465,10 +483,38 @@ pub(crate) fn with_palette<R>(app: &VectorcraftApp, id: u64, f: impl FnOnce(&mut
|
||||
}
|
||||
|
||||
/// Whether a waiting palette event's run can start now ([`vectorcraft_engine::Session::script_palette_can_start`]):
|
||||
/// it also waits while the last run's print jobs wait to be approved or canceled, and asks for no
|
||||
/// frame meanwhile.
|
||||
/// it also waits while the last run's print jobs wait to be approved or canceled, and after a start
|
||||
/// that failed until the person's next input or a change of the edit state ([`clear_failed_start`]),
|
||||
/// and asks for no frame meanwhile.
|
||||
pub(crate) fn can_start(app: &VectorcraftApp) -> bool {
|
||||
app.session.script_palette_can_start() && !crate::script_runs::waiting_for_print(app)
|
||||
app.ui.palette_start_failed.is_none_or(|at| at != edit_state(app))
|
||||
&& app.session.script_palette_can_start()
|
||||
&& !crate::script_runs::waiting_for_print(app)
|
||||
}
|
||||
|
||||
/// What a failed start may depend on: the documents, whether each has changes, an open drag or
|
||||
/// undo group, the active one, and the palette events in line.
|
||||
fn edit_state(app: &VectorcraftApp) -> u64 {
|
||||
use std::hash::{Hash, Hasher};
|
||||
let mut h = std::hash::DefaultHasher::new();
|
||||
for d in app.session.documents() {
|
||||
(d.uid, d.is_dirty(), d.interaction.is_some(), d.undo_group.is_some()).hash(&mut h);
|
||||
}
|
||||
app.session.active().map(|d| d.uid).hash(&mut h);
|
||||
app.session.script_copy_first.hash(&mut h);
|
||||
app.session.prefs.recovery_off_for_complex.hash(&mut h);
|
||||
app.session.prefs.recovery_folder.hash(&mut h);
|
||||
app.session.script_palette_events_waiting().hash(&mut h);
|
||||
app.session.script_palette_last_ticket().hash(&mut h);
|
||||
h.finish()
|
||||
}
|
||||
|
||||
/// Lets a waiting palette event whose start failed try again once the frame carries input, which
|
||||
/// may have changed the edit that kept it from starting.
|
||||
pub(crate) fn clear_failed_start(app: &mut VectorcraftApp, ctx: &egui::Context) {
|
||||
if app.ui.palette_start_failed.is_some() && ctx.input(|i| !i.events.is_empty()) {
|
||||
app.ui.palette_start_failed = None;
|
||||
}
|
||||
}
|
||||
|
||||
/// Starts the run of the oldest waiting palette event when no run is going. → whether one started.
|
||||
@@ -485,6 +531,7 @@ pub(crate) fn start_next(app: &mut VectorcraftApp) -> bool {
|
||||
None => false,
|
||||
Some(Ok(_)) => true,
|
||||
Some(Err(e)) => {
|
||||
app.ui.palette_start_failed = Some(edit_state(app));
|
||||
app.status(e.to_string());
|
||||
false
|
||||
}
|
||||
|
||||
@@ -1,15 +1,17 @@
|
||||
//! A running script, advanced one slice per frame: `script.run` starts it and [`poll`] takes it to
|
||||
//! its end, while the app goes on drawing the documents as they were before the run. The status bar
|
||||
//! shows it with a Stop button; a run that has added a great deal, or that opened a dialog with
|
||||
//! `alert`, `confirm`, `prompt`, a ScriptUI dialog's `show()` or a `File` or `Folder` file dialog,
|
||||
//! waits for the person's answer. A run that prepared jobs for a printer ends with the question
|
||||
//! before they are sent. With no run going, the oldest event a ScriptUI palette waits with starts
|
||||
//! its run ([`crate::script_palettes`]).
|
||||
//! `alert`, `confirm`, `prompt`, `app.showColorPicker`, a ScriptUI dialog's `show()` or a `File` or
|
||||
//! `Folder` file dialog, waits for the person's answer. A run that prepared jobs for a printer ends
|
||||
//! with the question before they are sent. With no run going, the oldest event a ScriptUI palette
|
||||
//! waits with starts its run ([`crate::script_palettes`]).
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_engine::WindowView;
|
||||
use vectorcraft_engine::script::DialogKind;
|
||||
|
||||
use crate::VectorcraftApp;
|
||||
use crate::dialogs::color_picker;
|
||||
use crate::dialogs::script_run::{self, GrowthQuestion, ScriptFiles, ScriptNotice};
|
||||
use crate::dialogs::script_window;
|
||||
|
||||
@@ -239,13 +241,22 @@ fn ask(app: &mut VectorcraftApp) -> bool {
|
||||
}
|
||||
script_run::forget::<ScriptFiles>(app);
|
||||
if let Some(dialog) = app.session.script_dialog() {
|
||||
if script_run::can_ask(app) {
|
||||
if dialog.kind == DialogKind::ColorPicker {
|
||||
// A picker that closed this frame answers the run in its own pump.
|
||||
if color_picker::script_picker(app).is_none()
|
||||
&& !script_run::busy(app)
|
||||
&& let Some(color) = dialog.color
|
||||
{
|
||||
color_picker::open_for_script(app, color, dialog.cmyk_document);
|
||||
}
|
||||
} else if script_run::can_ask(app) {
|
||||
script_run::open_notice(app, &dialog);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
// A run asked to stop no longer waits at its dialog.
|
||||
script_run::forget::<ScriptNotice>(app);
|
||||
script_run::forget_color_picker(app);
|
||||
// A run past its growth allowance asks about it first, also when its ScriptUI dialog waits
|
||||
// again.
|
||||
if app.session.script_waiting() {
|
||||
|
||||
@@ -724,6 +724,12 @@ pub struct UiState {
|
||||
#[serde(skip)]
|
||||
pub touch_drawing_tool: Option<String>,
|
||||
pub status: String,
|
||||
/// The edit state in which the last start of a waiting palette event's run failed
|
||||
/// ([`crate::script_palettes::start_next`]). The event then waits for the person's next input,
|
||||
/// or for that state to change, before it starts again, and asks for no frame meanwhile. Not
|
||||
/// saved.
|
||||
#[serde(skip)]
|
||||
pub palette_start_failed: Option<u64>,
|
||||
/// How many times [`crate::VectorcraftApp::status`] has set `status`, so that work finishing
|
||||
/// later can tell whether the line it started with is still the latest one. Not saved.
|
||||
#[serde(skip)]
|
||||
@@ -1553,6 +1559,7 @@ impl Default for UiState {
|
||||
group_tool: vectorcraft_tools::TOOL_GROUPS.iter().map(|g| g[0].id.to_string()).collect(),
|
||||
touch_drawing_tool: None,
|
||||
status: String::new(),
|
||||
palette_start_failed: None,
|
||||
status_sets: 0,
|
||||
script_print_failures: 0,
|
||||
script_print_failure_notes: Vec::new(),
|
||||
|
||||
@@ -75,6 +75,83 @@ fn samples_show_the_text_in_the_family_or_a_generic_sample() {
|
||||
assert_eq!(texts.iter().filter(|t| t.text == "Sample").count(), 2, "both runs are the generic sample: {texts:?}");
|
||||
}
|
||||
|
||||
/// A face with no hinting instructions draws a sample in a context the app has adopted, as the font list and the
|
||||
/// font picker draw each family's sample in its own face (a document face of the context): a Hebrew letter that is a
|
||||
/// bar 20 by 700 thousandths of an em, whose blue zones the automatic hinter of skrifa 0.44 never finishes measuring.
|
||||
/// The face is served to the fixture's context only, so the font database other tests read does not change. The
|
||||
/// sample is one rasterized glyph from that face. It is drawn 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_draws_its_sample() {
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use craft::ui::fonts::{FaceBytes, FaceState};
|
||||
use craft::ui::primitives::{ContentPainterCx, DocRun, DocText, FacesCx as _};
|
||||
use craft::ui::runtime::env::Env;
|
||||
use craft::ui::style::{DataColor, SurfaceKind};
|
||||
use craft::ui::testing::Fixture;
|
||||
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: Arc<[u8]> = Arc::from(build_file_font(&info, &[glyph]).unwrap());
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
std::thread::spawn(move || {
|
||||
let sample = Arc::new(Mutex::new((false, false)));
|
||||
let drawn_sample = Arc::clone(&sample);
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
*drawn_sample.lock().unwrap() = (false, false);
|
||||
let env = Env::of(ui);
|
||||
let cx = ContentPainterCx::new(ui.painter().clone(), &env, SurfaceKind::Panel.ink());
|
||||
let state = cx.document_face("font-sample/Unhinted Bar/Regular", || {
|
||||
let bytes = Arc::clone(&bytes);
|
||||
move || Some(FaceBytes::new(bytes, 0))
|
||||
});
|
||||
let FaceState::Ready(font) = state else { return };
|
||||
let color = DataColor::new(egui::Color32::BLACK);
|
||||
let runs = [DocRun::new("\u{5d1}", font, 16.0, color)];
|
||||
let layout = cx.layout(&DocText::new(&runs));
|
||||
let fixture_has_glyph = layout
|
||||
.galley
|
||||
.job
|
||||
.sections
|
||||
.first()
|
||||
.is_some_and(|section| ui.ctx().fonts_mut(|fonts| fonts.has_glyph(§ion.format.font_id, '\u{5d1}')));
|
||||
let mut glyphs = layout.galley.rows.iter().flat_map(|row| row.glyphs.iter());
|
||||
let nonempty_glyph =
|
||||
glyphs.next().is_some_and(|glyph| glyph.chr == '\u{5d1}' && glyph.uv_rect.size.x > 0.0 && glyph.uv_rect.size.y > 0.0)
|
||||
&& glyphs.next().is_none();
|
||||
*drawn_sample.lock().unwrap() = (fixture_has_glyph, nonempty_glyph);
|
||||
cx.painter.galley(ui.max_rect().min, layout.galley.clone(), color.0);
|
||||
});
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.adopt_context(fixture.ctx());
|
||||
fixture.settle();
|
||||
let texts = fixture.texts().iter().map(|t| t.text.clone()).collect::<Vec<_>>();
|
||||
let (fixture_has_glyph, nonempty_glyph) = *sample.lock().unwrap();
|
||||
let ctx = fixture.ctx();
|
||||
let hinting = [
|
||||
ctx.global_style().visuals.text_options.font_hinting,
|
||||
ctx.style_of(egui::Theme::Light).visuals.text_options.font_hinting,
|
||||
ctx.style_of(egui::Theme::Dark).visuals.text_options.font_hinting,
|
||||
];
|
||||
tx.send((texts, hinting, fixture_has_glyph, nonempty_glyph)).ok()
|
||||
});
|
||||
let (texts, [hinting, light_hinting, dark_hinting], fixture_has_glyph, nonempty_glyph) =
|
||||
rx.recv_timeout(std::time::Duration::from_secs(300)).unwrap_or_else(|e| panic!("drawing the sample: {e}"));
|
||||
assert!(texts.iter().any(|t| t == "\u{5d1}"), "the sample is the letter, in the face: {texts:?}");
|
||||
assert!(!hinting, "a context the app adopts draws text without hinting");
|
||||
assert!(!light_hinting, "the light theme draws text without hinting");
|
||||
assert!(!dark_hinting, "the dark theme draws text without hinting");
|
||||
assert!(fixture_has_glyph, "the sample's face maps U+05D1");
|
||||
assert!(nonempty_glyph, "the sample is one rasterized glyph for U+05D1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preview_changes_the_text_live_and_only_a_choice_is_a_step() {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
//! A script's `alert`, `confirm` and `prompt` in the app: the dialog the run waits at, its buttons,
|
||||
//! Enter and Escape, Stop, another dialog in the way, quitting while it waits, and the same answers
|
||||
//! given by a run with nobody to ask. The helpers over the dialog host are shared with the other
|
||||
//! script tests.
|
||||
//! given by a run with nobody to ask; and the Color Picker of `app.showColorPicker`. The helpers
|
||||
//! over the dialog host are shared with the other script tests.
|
||||
|
||||
use craft::color_ui::ui::{ColorPickerDialog, PickedColor};
|
||||
use craft::ui::dialog::{DialogId, StackDialog, StandardPrompt};
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_engine::Session;
|
||||
|
||||
use crate::dialogs::color_picker;
|
||||
use crate::dialogs::script_run::{self, CLOSE_KIND, CloseQuestion, NOTICE_KIND, ScriptNotice};
|
||||
use crate::{VectorcraftApp, menus, script_runs};
|
||||
|
||||
@@ -318,6 +320,196 @@ fn the_app_and_a_run_with_nobody_to_ask_give_the_same_results() {
|
||||
assert_eq!(framed["log"], json!([true, "p", "done"]));
|
||||
}
|
||||
|
||||
/// Is the Color Picker of the script's `app.showColorPicker` open?
|
||||
fn picker_open(app: &VectorcraftApp) -> bool {
|
||||
let id = color_picker::script_picker(app);
|
||||
id.is_some_and(|id| script_run::with_host(app, |host, _| host.get_by_id::<ColorPickerDialog>(id).is_some()).unwrap())
|
||||
}
|
||||
|
||||
/// Polls the run until it ends, or until its Color Picker is open (true).
|
||||
fn until_picker(app: &mut VectorcraftApp) -> bool {
|
||||
for _ in 0..10_000 {
|
||||
if !app.session.script_running() {
|
||||
return false;
|
||||
}
|
||||
script_runs::poll(app);
|
||||
if picker_open(app) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
panic!("the script neither ended nor opened the Color Picker");
|
||||
}
|
||||
|
||||
/// Answers the script's Color Picker with OK (or Cancel), then runs the frame's picker pump.
|
||||
fn answer_picker(app: &mut VectorcraftApp, ok: bool) {
|
||||
let id = color_picker::script_picker(app).unwrap();
|
||||
let ctx = app.ui_ctx.clone().unwrap();
|
||||
let done = script_run::with_host(app, |host, ctx| if ok { host.confirm_by_id(ctx, id) } else { host.cancel_by_id(ctx, id) }).unwrap();
|
||||
assert!(done);
|
||||
color_picker::pump(app, &ctx);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_color_picker_waits_and_answers_the_run() {
|
||||
let mut app = app();
|
||||
// A selected object, which a picker that previews would paint.
|
||||
app.run("shape.rectangle", json!({"x": 20, "y": 20, "width": 10, "height": 10})).unwrap();
|
||||
let gray = "var g = new GrayColor(); g.gray = 40;";
|
||||
start(
|
||||
&mut app,
|
||||
&format!(
|
||||
"{DRAW} var c = new RGBColor(); c.red = 255; var p = app.showColorPicker(c); vc.log([p.typename, p.red, p.green, p.blue].join()); \
|
||||
{gray} var q = app.showColorPicker(g); vc.log([q.typename, q.gray].join()); var r = app.showColorPicker(g); vc.log([r.typename, r.gray].join());"
|
||||
),
|
||||
);
|
||||
assert!(until_picker(&mut app));
|
||||
assert!(!is_open::<ScriptNotice>(&app), "the picker opens in place of a notice");
|
||||
set(&app, color_picker::SCRIPT_KEY, "color", json!("#00ff00")).unwrap();
|
||||
let ctx = app.ui_ctx.clone().unwrap();
|
||||
app.ui.status.clear();
|
||||
color_picker::pump(&mut app, &ctx);
|
||||
// A preview would begin an edit, which the running script refuses with a status message.
|
||||
assert_eq!(app.ui.status, "", "the picker starts no preview");
|
||||
assert_ne!(crate::panels::current_paints(&app).0.color().map(|c| c.to_hex()).as_deref(), Some("#00ff00"), "the selection shows no preview");
|
||||
answer_picker(&mut app, true);
|
||||
assert!(until_picker(&mut app), "the next call opens the picker again");
|
||||
answer_picker(&mut app, true);
|
||||
assert!(until_picker(&mut app));
|
||||
answer_picker(&mut app, false);
|
||||
assert!(!until_picker(&mut app));
|
||||
assert_eq!(
|
||||
log(&app),
|
||||
json!(["RGBColor,0,255,0", "GrayColor,40", "GrayColor,40"]),
|
||||
"OK gives the color picked, untouched its own color, Cancel the color given"
|
||||
);
|
||||
assert_ne!(crate::panels::current_paints(&app).0.color().map(|c| c.to_hex()).as_deref(), Some("#00ff00"), "OK paints nothing");
|
||||
let dialogs = app.session.script_report().unwrap()["dialogs"].clone();
|
||||
assert_eq!(dialogs[2]["answer"], Value::Null, "Cancel is listed as null");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_same_color_set_in_another_model_is_a_new_pick() {
|
||||
let mut app = app();
|
||||
start(&mut app, "var g = new GrayColor(); g.gray = 40; var p = app.showColorPicker(g); vc.log(p.typename);");
|
||||
assert!(until_picker(&mut app));
|
||||
// The gray's own sRGB, set as a plain color, as a screen sample sets one.
|
||||
let open = app.color_dialogs.pickers.iter().find(|o| Some(o.id) == color_picker::script_picker(&app)).map(|o| (o.id, o.start)).unwrap();
|
||||
script_run::with_host(&app, |host, _| host.get_mut_by_id::<ColorPickerDialog>(open.0).map(|d| d.set_color(PickedColor::rgb(open.1)))).unwrap();
|
||||
answer_picker(&mut app, true);
|
||||
assert!(!until_picker(&mut app));
|
||||
assert_eq!(log(&app), json!(["RGBColor"]), "the same sRGB as a plain color is an RGB pick, not the gray the script gave");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stopping_or_quitting_the_run_closes_its_color_picker() {
|
||||
let source = format!("{DRAW} var c = new RGBColor(); app.showColorPicker(c); vc.log('after');");
|
||||
let mut app = app();
|
||||
start(&mut app, &source);
|
||||
assert!(until_picker(&mut app));
|
||||
assert_eq!(app.run("script.stop", json!({})).unwrap()["stopped"], true);
|
||||
assert!(!until_picker(&mut app));
|
||||
assert!(!picker_open(&app), "no picker is left for the stopped run");
|
||||
assert!(color_picker::script_picker(&app).is_none());
|
||||
assert_eq!(objects(&app), 0, "the run's edit goes back");
|
||||
assert_eq!(log(&app), json!([]));
|
||||
let mut app = self::app();
|
||||
start(&mut app, &source);
|
||||
assert!(until_picker(&mut app));
|
||||
script_run::ask_to_close(&mut app);
|
||||
assert!(is_open::<CloseQuestion>(&app), "quitting asks over the picker");
|
||||
cancel(&mut app, CLOSE_KIND);
|
||||
assert!(picker_open(&app), "Cancel shows the picker again");
|
||||
script_run::ask_to_close(&mut app);
|
||||
assert!(confirm(&mut app, CLOSE_KIND));
|
||||
assert!(!app.session.script_running());
|
||||
assert!(!picker_open(&app), "no picker is left for the abandoned run");
|
||||
assert_eq!(objects(&app), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stopping_the_run_ends_only_the_screen_pick_its_color_picker_started() {
|
||||
use craft::color_ui::ui::ScreenPickGesture;
|
||||
let source = "var c = new RGBColor(); app.showColorPicker(c);";
|
||||
for own in [true, false] {
|
||||
let mut app = app();
|
||||
start(&mut app, source);
|
||||
assert!(until_picker(&mut app));
|
||||
let ctx = app.ui_ctx.clone().unwrap();
|
||||
let id = color_picker::script_picker(&app).unwrap();
|
||||
let started = if own {
|
||||
crate::screen_color::hold(&mut app, &ctx, color_picker::owner(id), ScreenPickGesture::Clicked)
|
||||
} else {
|
||||
crate::screen_color::hold(&mut app, &ctx, "fill", ScreenPickGesture::Clicked)
|
||||
};
|
||||
assert_eq!(started, None);
|
||||
assert!(app.screen_pick.busy());
|
||||
assert_eq!(app.run("script.stop", json!({})).unwrap()["stopped"], true);
|
||||
assert!(!until_picker(&mut app));
|
||||
assert_eq!(app.screen_pick.busy(), !own, "own pick {own}: only the picker's own pick ends with it");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_color_picker_opens_on_the_scripts_color_with_only_web_colors_left_on() {
|
||||
let mut app = app();
|
||||
let ctx = app.ui_ctx.clone().unwrap();
|
||||
// A frame of the window's dialogs starts the open pickers with the app's host, whose settings
|
||||
// keep what a picker remembers.
|
||||
let frame = |app: &mut VectorcraftApp| {
|
||||
let _ = crate::testing::part_frame(app, &ctx, egui::RawInput::default(), |app, ui| {
|
||||
if let Some(dialogs) = app.dialogs() {
|
||||
dialogs.with(|host| host.run(ui));
|
||||
}
|
||||
});
|
||||
};
|
||||
// A fill picker closed with Only Web Colors on, which later fill pickers recall.
|
||||
color_picker::open(&mut app, &json!({})).unwrap();
|
||||
frame(&mut app);
|
||||
set(&app, "fill", "webColors", json!(true)).unwrap();
|
||||
let id = open_id(&app, "fill");
|
||||
assert!(script_run::with_host(&app, |host, ctx| host.confirm_by_id(ctx, id)).unwrap());
|
||||
color_picker::pump(&mut app, &ctx);
|
||||
color_picker::open(&mut app, &json!({})).unwrap();
|
||||
frame(&mut app);
|
||||
assert_eq!(fields(&app, "fill")["webColors"], json!(true), "the next fill picker recalls Only Web Colors");
|
||||
let id = open_id(&app, "fill");
|
||||
assert!(script_run::with_host(&app, |host, ctx| host.confirm_by_id(ctx, id)).unwrap());
|
||||
color_picker::pump(&mut app, &ctx);
|
||||
// A frame without the picker drops its overlay.
|
||||
frame(&mut app);
|
||||
assert!(!script_run::busy(&app), "no picker is left open");
|
||||
start(
|
||||
&mut app,
|
||||
"var c = new RGBColor(); c.red = 18; c.green = 52; c.blue = 86; var p = app.showColorPicker(c); vc.log([p.typename, p.red, p.green, p.blue].join());",
|
||||
);
|
||||
assert!(until_picker(&mut app));
|
||||
frame(&mut app);
|
||||
answer_picker(&mut app, true);
|
||||
assert!(!until_picker(&mut app));
|
||||
assert_eq!(log(&app), json!(["RGBColor,18,52,86"]), "untouched OK gives the script's color, not its nearest web color");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pick_takes_the_model_of_the_document_the_script_made() {
|
||||
for (doc, made, want) in [("{}", "CMYK", "CMYKColor"), ("{\"colorMode\": \"cmyk\"}", "RGB", "RGBColor")] {
|
||||
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), crate::Services::default()));
|
||||
app.run("file.new", serde_json::from_str(doc).unwrap()).unwrap();
|
||||
app.session.prefs.show_external_script_warning = false;
|
||||
start(
|
||||
&mut app,
|
||||
&format!(
|
||||
"app.documents.add(DocumentColorSpace.{made}, 50, 60, 1); var c = new RGBColor(); c.red = 255; \
|
||||
var p = app.showColorPicker(c); vc.log(p.typename);"
|
||||
),
|
||||
);
|
||||
assert!(until_picker(&mut app));
|
||||
set(&app, color_picker::SCRIPT_KEY, "color", json!("#00ff00")).unwrap();
|
||||
answer_picker(&mut app, true);
|
||||
assert!(!until_picker(&mut app));
|
||||
assert_eq!(log(&app), json!([want]), "an RGB pick in the {made} document the script made");
|
||||
}
|
||||
}
|
||||
|
||||
/// Only the person at the keyboard turns off the external script warning: Yes from automation, set
|
||||
/// as the answer or given in a pass automation drives, is refused, the warning stays on and the
|
||||
/// question opens again; No is taken from automation.
|
||||
|
||||
@@ -260,6 +260,81 @@ fn a_click_or_close_narrows_the_scope_of_the_draft_it_commits() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_click_reads_a_typed_text_that_matches_the_field_while_another_change_of_it_waits() {
|
||||
let mut app = app();
|
||||
let id = shown(
|
||||
&mut app,
|
||||
"#targetengine drafts\nvar p = new Window('palette'); var t = p.add('edittext', undefined, 'a'); \
|
||||
var go = p.add('button', undefined, 'Go'); go.onClick = function () { vc.log('clicked ' + t.text); }; p.show();",
|
||||
);
|
||||
app.session.script_palette_event(id, UiEvent::Change(1, UiValue::Text("b".into()))).unwrap();
|
||||
// The person types the field's text back and clicks before the change to `b` is delivered.
|
||||
with_palette(&app, id, |w| w.type_text(1, "a")).unwrap();
|
||||
give(&app, id, UiEvent::Click(2));
|
||||
follow(&mut app);
|
||||
let mut logs = Vec::new();
|
||||
for _ in 0..10 {
|
||||
script_runs::poll(&mut app);
|
||||
if !app.session.script_running() && app.session.script_palette_events_waiting() == 0 {
|
||||
break;
|
||||
}
|
||||
run_to_end(&mut app);
|
||||
logs.extend(app.session.script_report().unwrap()["log"].as_array().cloned().unwrap_or_default());
|
||||
}
|
||||
run_to_end(&mut app);
|
||||
if let Some(report) = app.session.script_report() {
|
||||
logs.extend(report["log"].as_array().cloned().unwrap_or_default());
|
||||
}
|
||||
assert!(logs.contains(&json!("clicked a")), "the click reads the text the person typed: {logs:?}");
|
||||
assert!(!logs.contains(&json!("clicked b")), "{logs:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn focus_loss_commits_a_restored_text_while_another_change_of_the_field_waits() {
|
||||
let mut app = app();
|
||||
let id = shown(
|
||||
&mut app,
|
||||
"#targetengine drafts\nvar p = new Window('palette'); var t = p.add('edittext', undefined, 'a'); \
|
||||
var go = p.add('button', undefined, 'Go'); go.onClick = function () { vc.log('clicked ' + t.text); }; p.show();",
|
||||
);
|
||||
app.session.script_palette_event(id, UiEvent::Change(1, UiValue::Text("b".into()))).unwrap();
|
||||
follow(&mut app);
|
||||
with_palette(&app, id, |w| w.type_text(1, "a")).unwrap();
|
||||
let ctx = app.ui_ctx.clone().unwrap();
|
||||
let paint = |app: &mut VectorcraftApp, events: Vec<egui::Event>| {
|
||||
let raw = egui::RawInput { events, ..Default::default() };
|
||||
crate::testing::part_frame(app, &ctx, raw, |app, ui| {
|
||||
with_palette(app, id, |w| w.paint(ui));
|
||||
});
|
||||
};
|
||||
paint(&mut app, Vec::new());
|
||||
// Tab gives the edit field, the palette's first control, the keyboard focus.
|
||||
let tab = |pressed| egui::Event::Key { key: egui::Key::Tab, physical_key: None, pressed, repeat: false, modifiers: Default::default() };
|
||||
paint(&mut app, vec![tab(true), tab(false)]);
|
||||
paint(&mut app, Vec::new());
|
||||
let focused = ctx.memory(|m| m.focused()).expect("the edit field has the keyboard focus");
|
||||
assert!(ctx.text_edit_focused());
|
||||
assert_eq!(with_palette(&app, id, |w| w.typed(1).map(str::to_string)).flatten().as_deref(), Some("a"));
|
||||
// Tab moves the keyboard focus on to the Go button, and the pass after it gives the field's text to the script.
|
||||
paint(&mut app, vec![tab(true), tab(false)]);
|
||||
paint(&mut app, Vec::new());
|
||||
paint(&mut app, Vec::new());
|
||||
assert_ne!(ctx.memory(|m| m.focused()), Some(focused), "the edit field lost the keyboard focus");
|
||||
assert_eq!(with_palette(&app, id, |w| w.typed(1).map(str::to_string)).flatten(), None, "focus loss gives the typed text");
|
||||
follow(&mut app);
|
||||
assert_eq!(app.session.script_palette_events_waiting(), 1, "focus loss merges the restored text into the waiting change");
|
||||
give(&app, id, UiEvent::Click(2));
|
||||
follow(&mut app);
|
||||
assert_eq!(app.session.script_palette_events_waiting(), 2, "the click follows the restored text");
|
||||
for _ in 0..2 {
|
||||
assert!(script_palettes::start_next(&mut app));
|
||||
run_to_end(&mut app);
|
||||
}
|
||||
assert_eq!(app.session.script_report().unwrap()["log"], json!(["clicked a"]));
|
||||
assert_eq!(app.session.script_palette_events_waiting(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_text_typed_in_two_scopes_goes_to_the_script_in_what_both_allow() {
|
||||
use vectorcraft_engine::file_access::{AutomationRoots, confine, unconfined};
|
||||
@@ -791,6 +866,68 @@ fn a_click_whose_run_cannot_begin_after_a_stopped_run_shows_its_own_error() {
|
||||
assert!(app.ui.status.contains("recovery copy"), "{}", app.ui.status);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_click_whose_run_cannot_begin_asks_for_no_frame_until_the_next_input() {
|
||||
let mut app = app();
|
||||
let id = shown(
|
||||
&mut app,
|
||||
"#targetengine two\nvar p = new Window('palette'); p.add('button', undefined, 'A').onClick = function () { vc.log('a'); }; \
|
||||
p.add('button', undefined, 'B').onClick = function () { vc.log('b'); }; p.show();",
|
||||
);
|
||||
// The document has changes, and the session has nowhere to keep a recovery copy of it.
|
||||
app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap();
|
||||
app.session.script_copy_first = true;
|
||||
give(&app, id, UiEvent::Click(1));
|
||||
give(&app, id, UiEvent::Click(2));
|
||||
follow(&mut app);
|
||||
assert!(!script_palettes::start_next(&mut app));
|
||||
assert_eq!(app.session.script_palette_events_waiting(), 1, "the second click still waits");
|
||||
assert!(!script_palettes::can_start(&app), "the failed start does not retry, nor ask for a frame, on every pass");
|
||||
// An event given without the window, as automation gives one, changes what the start depends on.
|
||||
app.session.script_palette_event(id, UiEvent::Click(1)).unwrap();
|
||||
assert!(script_palettes::can_start(&app), "a change of the edit state lets the start try again");
|
||||
assert!(!script_palettes::start_next(&mut app));
|
||||
assert!(!script_palettes::can_start(&app));
|
||||
let ctx = app.ui_ctx.clone().unwrap();
|
||||
let input = egui::RawInput { events: vec![egui::Event::PointerGone], ..Default::default() };
|
||||
crate::testing::part_frame(&mut app, &ctx, input, |app, ui| script_palettes::clear_failed_start(app, ui.ctx()));
|
||||
assert!(script_palettes::can_start(&app), "the person's next input lets the click try again");
|
||||
app.session.script_copy_first = false;
|
||||
assert!(script_palettes::start_next(&mut app));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_palette_start_retries_after_recovery_settings_change_without_input() {
|
||||
let mut app = app();
|
||||
let id = shown(
|
||||
&mut app,
|
||||
"#targetengine retries\nvar p = new Window('palette'); \
|
||||
for (var i = 0; i < 3; i++) { p.add('button', undefined, 'Go ' + i).onClick = function () { vc.log('clicked'); }; } p.show();",
|
||||
);
|
||||
app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap();
|
||||
app.session.script_copy_first = true;
|
||||
for i in 1..=3 {
|
||||
give(&app, id, UiEvent::Click(i));
|
||||
}
|
||||
follow(&mut app);
|
||||
assert!(!script_palettes::start_next(&mut app));
|
||||
assert_eq!(app.session.script_palette_events_waiting(), 2);
|
||||
assert!(!script_palettes::can_start(&app));
|
||||
assert_eq!(settled_delay(&mut app), std::time::Duration::MAX, "the failed start asks for no frames");
|
||||
app.session.execute("prefs.set", &json!({"key": "recoveryOffForComplex", "value": true})).unwrap();
|
||||
assert!(script_palettes::can_start(&app), "automation can change the recovery condition without window input");
|
||||
assert!(!script_palettes::start_next(&mut app), "the missing recovery store still prevents a start");
|
||||
assert_eq!(app.session.script_palette_events_waiting(), 1);
|
||||
assert!(!script_palettes::can_start(&app));
|
||||
assert_eq!(settled_delay(&mut app), std::time::Duration::MAX, "a repeated failure still asks for no frames");
|
||||
app.session.script_copy_first = false;
|
||||
assert!(script_palettes::can_start(&app), "disabling the recovery prerequisite permits another attempt");
|
||||
assert!(script_palettes::start_next(&mut app));
|
||||
run_to_end(&mut app);
|
||||
assert_eq!(app.session.script_report().unwrap()["log"], json!(["clicked"]));
|
||||
assert_eq!(app.session.script_palette_events_waiting(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_typed_text_stays_in_its_field_when_a_run_adds_a_control_before_it() {
|
||||
let mut app = app();
|
||||
|
||||
Loaded 100 of 109 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user