mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-19 02:03:02 +00:00
Merge main into feat/artboard-edge-button-tooltips
This commit is contained in:
Generated
+74
-128
@@ -1001,7 +1001,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-affinity"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
|
||||
dependencies = [
|
||||
"crc32fast",
|
||||
"flate2",
|
||||
@@ -1012,17 +1012,25 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-codepage"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
|
||||
|
||||
[[package]]
|
||||
name = "craft-dds"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
|
||||
dependencies = [
|
||||
"rayon",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-docpath"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
|
||||
|
||||
[[package]]
|
||||
name = "craft-dxf"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
|
||||
dependencies = [
|
||||
"craft-codepage",
|
||||
"encoding_rs",
|
||||
@@ -1034,17 +1042,17 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-eps"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
|
||||
|
||||
[[package]]
|
||||
name = "craft-fonts-build"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
|
||||
|
||||
[[package]]
|
||||
name = "craft-gif"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
|
||||
dependencies = [
|
||||
"gif",
|
||||
]
|
||||
@@ -1052,7 +1060,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-gzip"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
]
|
||||
@@ -1060,7 +1068,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-i18n"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
|
||||
dependencies = [
|
||||
"fixed_decimal",
|
||||
"icu_decimal",
|
||||
@@ -1083,37 +1091,12 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-image-codecs"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=431f704478962677ec47e512754464d372901830#431f704478962677ec47e512754464d372901830"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
|
||||
dependencies = [
|
||||
"craft-jpeg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=431f704478962677ec47e512754464d372901830)",
|
||||
"craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=431f704478962677ec47e512754464d372901830)",
|
||||
"craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=431f704478962677ec47e512754464d372901830)",
|
||||
"crc32fast",
|
||||
"exr",
|
||||
"flate2",
|
||||
"half",
|
||||
"hayro-jpeg2000",
|
||||
"image",
|
||||
"image-webp",
|
||||
"jpeg-encoder",
|
||||
"png 0.18.1",
|
||||
"rayon",
|
||||
"serde_json",
|
||||
"thiserror 2.0.21",
|
||||
"tiff",
|
||||
"zune-core",
|
||||
"zune-jpeg",
|
||||
"zune-jpegxl",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-image-codecs"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
|
||||
dependencies = [
|
||||
"craft-jpeg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)",
|
||||
"craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)",
|
||||
"craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)",
|
||||
"craft-dds",
|
||||
"craft-jpeg",
|
||||
"craft-metadata",
|
||||
"craft-tiff",
|
||||
"crc32fast",
|
||||
"exr",
|
||||
"flate2",
|
||||
@@ -1135,15 +1118,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-jpeg"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=431f704478962677ec47e512754464d372901830#431f704478962677ec47e512754464d372901830"
|
||||
dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-jpeg"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
|
||||
dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
@@ -1151,7 +1126,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-jxl"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
|
||||
dependencies = [
|
||||
"jixel",
|
||||
"jxl-oxide",
|
||||
@@ -1161,7 +1136,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-keymap"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
|
||||
dependencies = [
|
||||
"egui",
|
||||
"serde",
|
||||
@@ -1171,23 +1146,11 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-metadata"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=431f704478962677ec47e512754464d372901830#431f704478962677ec47e512754464d372901830"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
|
||||
dependencies = [
|
||||
"brotli-decompressor 6.3.2",
|
||||
"chrono",
|
||||
"craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=431f704478962677ec47e512754464d372901830)",
|
||||
"quick-xml 0.41.0",
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-metadata"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
|
||||
dependencies = [
|
||||
"brotli-decompressor 6.3.2",
|
||||
"chrono",
|
||||
"craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)",
|
||||
"craft-tiff",
|
||||
"quick-xml 0.41.0",
|
||||
"serde",
|
||||
]
|
||||
@@ -1195,7 +1158,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-metafile"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"image",
|
||||
@@ -1206,7 +1169,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-mime"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"craft-codepage",
|
||||
@@ -1216,7 +1179,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-pdf"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e#0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
|
||||
dependencies = [
|
||||
"hayro-interpret",
|
||||
"hayro-syntax",
|
||||
@@ -1227,7 +1190,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-plotter"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=9101c4fc226f5f111b5a890a6c5c19bf3991fd76#9101c4fc226f5f111b5a890a6c5c19bf3991fd76"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=a7fb55eaf9a15c21e8ce0b13cf605dc54fd15f57#a7fb55eaf9a15c21e8ce0b13cf605dc54fd15f57"
|
||||
dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
@@ -1235,7 +1198,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-print"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
|
||||
dependencies = [
|
||||
"craft-winprint-gdi",
|
||||
"log",
|
||||
@@ -1249,7 +1212,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-proof"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
|
||||
dependencies = [
|
||||
"log",
|
||||
"miniz_oxide 0.9.1",
|
||||
@@ -1260,7 +1223,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ps"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=a80c0f25f1c4767374a27a444fbf95e3e8162e14#a80c0f25f1c4767374a27a444fbf95e3e8162e14"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"kurbo 0.13.1",
|
||||
@@ -1269,7 +1232,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-psd"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"flate2",
|
||||
@@ -1280,7 +1243,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-stream-codecs"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e#0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
|
||||
dependencies = [
|
||||
"fax",
|
||||
"hayro-ccitt",
|
||||
@@ -1291,10 +1254,10 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-svg"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=431f704478962677ec47e512754464d372901830#431f704478962677ec47e512754464d372901830"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
|
||||
dependencies = [
|
||||
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=431f704478962677ec47e512754464d372901830)",
|
||||
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=431f704478962677ec47e512754464d372901830)",
|
||||
"craft-image-codecs",
|
||||
"craft-xml",
|
||||
"data-url",
|
||||
"flate2",
|
||||
"kurbo 0.13.1",
|
||||
@@ -1310,16 +1273,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-tiff"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=431f704478962677ec47e512754464d372901830#431f704478962677ec47e512754464d372901830"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-tiff"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"thiserror 2.0.21",
|
||||
@@ -1328,7 +1282,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
|
||||
dependencies = [
|
||||
"craft-fonts-build",
|
||||
"craft-i18n",
|
||||
@@ -1349,7 +1303,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-update"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"dunce",
|
||||
@@ -1376,7 +1330,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-vectorcraft-format"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"serde",
|
||||
@@ -1387,7 +1341,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-web-api"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=fd5e2feff6ea25bed371a99cc732b3968d621505#fd5e2feff6ea25bed371a99cc732b3968d621505"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
|
||||
dependencies = [
|
||||
"js-sys",
|
||||
"serde_json",
|
||||
@@ -1398,7 +1352,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-window"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
|
||||
dependencies = [
|
||||
"egui",
|
||||
"objc2 0.6.5",
|
||||
@@ -1417,17 +1371,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-xml"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=431f704478962677ec47e512754464d372901830#431f704478962677ec47e512754464d372901830"
|
||||
dependencies = [
|
||||
"quick-xml 0.41.0",
|
||||
"serde",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-xml"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
|
||||
dependencies = [
|
||||
"quick-xml 0.41.0",
|
||||
"serde",
|
||||
@@ -2534,7 +2478,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a"
|
||||
[[package]]
|
||||
name = "hayro-cmap"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e#0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
|
||||
dependencies = [
|
||||
"brotli",
|
||||
"hayro-postscript",
|
||||
@@ -2543,7 +2487,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "hayro-interpret"
|
||||
version = "0.7.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e#0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"hayro-cmap",
|
||||
@@ -2561,7 +2505,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "hayro-jbig2"
|
||||
version = "0.3.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e#0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
|
||||
dependencies = [
|
||||
"fearless_simd",
|
||||
"hayro-ccitt",
|
||||
@@ -2579,12 +2523,12 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "hayro-postscript"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e#0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
|
||||
|
||||
[[package]]
|
||||
name = "hayro-syntax"
|
||||
version = "0.7.2"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e#0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"hayro-ccitt",
|
||||
@@ -3384,7 +3328,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "krilla"
|
||||
version = "0.8.2"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e#0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"bumpalo",
|
||||
@@ -3493,7 +3437,7 @@ checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4"
|
||||
[[package]]
|
||||
name = "linesweeper"
|
||||
version = "0.5.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e#0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
|
||||
dependencies = [
|
||||
"arrayvec",
|
||||
"kurbo 0.13.1",
|
||||
@@ -6698,7 +6642,7 @@ name = "vectorcraft-affinity"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"craft-affinity",
|
||||
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)",
|
||||
"craft-image-codecs",
|
||||
"crc32fast",
|
||||
"proptest",
|
||||
]
|
||||
@@ -6727,7 +6671,7 @@ name = "vectorcraft-cad"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"craft-dxf",
|
||||
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)",
|
||||
"craft-image-codecs",
|
||||
"craft-plotter",
|
||||
"image",
|
||||
"kurbo 0.13.1",
|
||||
@@ -6781,7 +6725,7 @@ name = "vectorcraft-doc"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)",
|
||||
"craft-image-codecs",
|
||||
"craft-stream-codecs",
|
||||
"flate2",
|
||||
"image",
|
||||
@@ -6801,7 +6745,7 @@ dependencies = [
|
||||
name = "vectorcraft-effects"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)",
|
||||
"craft-image-codecs",
|
||||
"craft-svg",
|
||||
"image",
|
||||
"kurbo 0.13.1",
|
||||
@@ -6825,11 +6769,11 @@ dependencies = [
|
||||
"cfb",
|
||||
"chrono",
|
||||
"craft-docpath",
|
||||
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)",
|
||||
"craft-image-codecs",
|
||||
"craft-jxl",
|
||||
"craft-proof",
|
||||
"craft-stream-codecs",
|
||||
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)",
|
||||
"craft-xml",
|
||||
"crc32fast",
|
||||
"flate2",
|
||||
"hayro-ccitt",
|
||||
@@ -6882,7 +6826,7 @@ name = "vectorcraft-eps"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"craft-eps",
|
||||
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)",
|
||||
"craft-image-codecs",
|
||||
"craft-pdf",
|
||||
"craft-ps",
|
||||
"craft-stream-codecs",
|
||||
@@ -6962,7 +6906,7 @@ dependencies = [
|
||||
name = "vectorcraft-mcp"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)",
|
||||
"craft-image-codecs",
|
||||
"image",
|
||||
"log",
|
||||
"proptest",
|
||||
@@ -6982,7 +6926,7 @@ dependencies = [
|
||||
name = "vectorcraft-metafile"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)",
|
||||
"craft-image-codecs",
|
||||
"craft-metafile",
|
||||
"image",
|
||||
"kurbo 0.13.1",
|
||||
@@ -7023,10 +6967,10 @@ version = "0.24.1"
|
||||
dependencies = [
|
||||
"aes",
|
||||
"chrono",
|
||||
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)",
|
||||
"craft-image-codecs",
|
||||
"craft-pdf",
|
||||
"craft-stream-codecs",
|
||||
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)",
|
||||
"craft-xml",
|
||||
"flate2",
|
||||
"getrandom 0.4.3",
|
||||
"image",
|
||||
@@ -7057,7 +7001,7 @@ dependencies = [
|
||||
name = "vectorcraft-plugins"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)",
|
||||
"craft-image-codecs",
|
||||
"craft-vectorcraft-format",
|
||||
"log",
|
||||
"serde",
|
||||
@@ -7077,10 +7021,10 @@ name = "vectorcraft-render"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"craft-gif",
|
||||
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)",
|
||||
"craft-image-codecs",
|
||||
"craft-psd",
|
||||
"craft-stream-codecs",
|
||||
"craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)",
|
||||
"craft-tiff",
|
||||
"flate2",
|
||||
"image",
|
||||
"jpeg-encoder",
|
||||
@@ -7116,7 +7060,7 @@ name = "vectorcraft-svg"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"craft-docpath",
|
||||
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)",
|
||||
"craft-image-codecs",
|
||||
"craft-mime",
|
||||
"craft-svg",
|
||||
"data-url",
|
||||
@@ -7146,7 +7090,7 @@ dependencies = [
|
||||
name = "vectorcraft-testkit"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)",
|
||||
"craft-image-codecs",
|
||||
"fax",
|
||||
"kurbo 0.13.1",
|
||||
"proptest",
|
||||
@@ -7164,6 +7108,7 @@ dependencies = [
|
||||
name = "vectorcraft-text"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"craft-proof",
|
||||
"harfrust 0.13.3",
|
||||
"icu_segmenter",
|
||||
"kurbo 0.13.1",
|
||||
@@ -7172,6 +7117,7 @@ dependencies = [
|
||||
"subsetter",
|
||||
"unicode-bidi",
|
||||
"unicode-general-category",
|
||||
"unicode-normalization",
|
||||
"unicode-script",
|
||||
"unicode-segmentation",
|
||||
"vectorcraft-doc",
|
||||
@@ -7194,7 +7140,7 @@ dependencies = [
|
||||
name = "vectorcraft-tools"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)",
|
||||
"craft-image-codecs",
|
||||
"kurbo 0.13.1",
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -7211,7 +7157,7 @@ dependencies = [
|
||||
name = "vectorcraft-trace"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)",
|
||||
"craft-image-codecs",
|
||||
"image",
|
||||
"kurbo 0.13.1",
|
||||
"serde",
|
||||
@@ -7226,7 +7172,7 @@ version = "0.24.1"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"chrono",
|
||||
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)",
|
||||
"craft-image-codecs",
|
||||
"craft-keymap",
|
||||
"craft-ui",
|
||||
"craft-update",
|
||||
|
||||
+32
-32
@@ -11,40 +11,40 @@ rust-version = "1.95"
|
||||
repository = "https://github.com/storytold/vectorcraft"
|
||||
|
||||
[workspace.dependencies]
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e", default-features = false, features = ["interpret", "write"] }
|
||||
craft-print = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
|
||||
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
|
||||
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd", features = ["serde"] }
|
||||
craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
|
||||
craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b", default-features = false, features = ["interpret", "write"] }
|
||||
craft-print = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
|
||||
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
|
||||
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b", features = ["serde"] }
|
||||
craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
|
||||
craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
|
||||
# Decides who draws the window frame (desktop vs. app) so the suite shares one native titlebar per
|
||||
# desktop. The `egui` feature adds `craft_window::decorate`. (craft-libs#217.)
|
||||
craft-window = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd", features = ["egui"] }
|
||||
craft-window = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b", features = ["egui"] }
|
||||
# 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 = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
|
||||
craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
|
||||
craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
|
||||
craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
|
||||
# craft-update: app-specific pretend versions apply to startup and manual checks.
|
||||
# Native Affinity documents (craft-libs#914).
|
||||
craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
|
||||
craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
|
||||
# SVG parsing, limits, SVGZ and writer (craft-libs#778).
|
||||
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "431f704478962677ec47e512754464d372901830", features = ["tree"] }
|
||||
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
|
||||
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b", features = ["tree"] }
|
||||
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
|
||||
# EPS container, previews, ASCII85 and DSC comments (craft-libs#778).
|
||||
craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
|
||||
craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
|
||||
# DXF tags, reader and writer (craft-libs#778, #926, #927).
|
||||
craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "9101c4fc226f5f111b5a890a6c5c19bf3991fd76" }
|
||||
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
|
||||
craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "a7fb55eaf9a15c21e8ce0b13cf605dc54fd15f57" }
|
||||
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
|
||||
# WMF, EMF and EMF+ reader (craft-libs#778).
|
||||
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
|
||||
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
|
||||
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
|
||||
craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
|
||||
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
|
||||
craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "a80c0f25f1c4767374a27a444fbf95e3e8162e14", default-features = false, features = ["write"] }
|
||||
craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
|
||||
craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e" }
|
||||
craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
|
||||
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd", features = ["egui"] }
|
||||
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
|
||||
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
|
||||
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
|
||||
craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
|
||||
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
|
||||
craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b", default-features = false, features = ["write"] }
|
||||
craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
|
||||
craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
|
||||
craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
|
||||
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b", features = ["egui"] }
|
||||
# internal
|
||||
vectorcraft-geom = { path = "crates/geom" }
|
||||
vectorcraft-color = { path = "crates/color" }
|
||||
@@ -184,13 +184,13 @@ lto = "thin"
|
||||
codegen-units = 1
|
||||
|
||||
[patch.crates-io]
|
||||
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e" }
|
||||
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e" }
|
||||
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e" }
|
||||
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e" }
|
||||
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e" }
|
||||
krilla = { git = "https://github.com/storytold/craft-libs", rev = "0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e" }
|
||||
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e" }
|
||||
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
|
||||
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
|
||||
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
|
||||
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
|
||||
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
|
||||
krilla = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
|
||||
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
emath = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
epaint = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
|
||||
@@ -17,7 +17,7 @@ path = "src/main.rs"
|
||||
vectorcraft-engine = { workspace = true, features = ["bundled-fonts", "heif"] }
|
||||
vectorcraft-ui-egui = { workspace = true }
|
||||
# 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 = "fd5e2feff6ea25bed371a99cc732b3968d621505", version = "0.1.0" }
|
||||
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b", version = "0.1.0" }
|
||||
vectorcraft-format = { workspace = true }
|
||||
vectorcraft-text = { workspace = true }
|
||||
egui = { workspace = true }
|
||||
|
||||
@@ -591,14 +591,15 @@ fn main() -> std::process::ExitCode {
|
||||
created.created(&cc.egui_ctx);
|
||||
if !gpu::skipped().is_empty() {
|
||||
// A processor chosen in Settings can be the one that can't show the window.
|
||||
let hint = if chosen_gpu {
|
||||
" (Settings › Performance › Graphics Processor › Automatic uses the one that drives your display)"
|
||||
if chosen_gpu {
|
||||
app.status(format!(
|
||||
"The graphics processor tried first couldn't show the window, so VectorCraft started again on {summary} (Settings › Performance › Graphics Processor › Automatic uses the one that drives your display)"
|
||||
));
|
||||
} else {
|
||||
""
|
||||
};
|
||||
app.status(format!(
|
||||
"The graphics processor tried first couldn't show the window, so VectorCraft started again on {summary}{hint}"
|
||||
));
|
||||
app.status(format!(
|
||||
"The graphics processor tried first couldn't show the window, so VectorCraft started again on {summary}"
|
||||
));
|
||||
}
|
||||
} else if let Some(crash) = &crash {
|
||||
app.status(match crash {
|
||||
gpu::Crash::Adapter { name, .. } => format!(
|
||||
|
||||
@@ -54,6 +54,7 @@ fn flag_value(flag: &str, arg: &str, args: &mut impl Iterator<Item = String>) ->
|
||||
|
||||
impl Overrides {
|
||||
/// Whether a flag or a variable set the present mode or the frame latency.
|
||||
#[cfg_attr(target_os = "macos", allow(dead_code))] // its one caller, in `main`, is not built on macOS
|
||||
pub fn is_set(&self) -> bool {
|
||||
*self != Self::default()
|
||||
}
|
||||
|
||||
@@ -9,9 +9,8 @@ impl PrintService for SystemPrint {
|
||||
system::printers()
|
||||
}
|
||||
fn print(&mut self, job: &PrintJob) -> Result<String, String> {
|
||||
let result = system::print(job);
|
||||
let to = job.printer.unwrap_or("the default printer");
|
||||
result.map(|note| format!("Sent “{}” to {to}{note}", job.title))
|
||||
let note = system::print(job)?;
|
||||
Ok(sent(job.title, job.printer, ¬e))
|
||||
}
|
||||
fn shared_print(&self) -> Option<vectorcraft_ui_egui::print::SharedPrintFn> {
|
||||
Some(std::sync::Arc::new(|job| SystemPrint.print(job)))
|
||||
@@ -29,6 +28,15 @@ impl PrintService for SystemPrint {
|
||||
}
|
||||
}
|
||||
|
||||
/// The status after the job `title` went to `printer` (the default one without a name), with the
|
||||
/// spooler's `note` when it gave one. Each message has text between its values, so a catalog can
|
||||
/// match it and translate it. The note follows as its own sentence: a printer name can end in
|
||||
/// parentheses ("HP LaserJet (Copy 1)"), and a note in parentheses would match that name.
|
||||
fn sent(title: &str, printer: Option<&str>, note: &str) -> String {
|
||||
let to = printer.unwrap_or("the default printer");
|
||||
if note.is_empty() { format!("Sent “{title}” to {to}") } else { format!("Sent “{title}” to {to}. The spooler replied: {note}") }
|
||||
}
|
||||
|
||||
mod system {
|
||||
use super::{Command, PrintJob, Printer};
|
||||
pub fn printers() -> Vec<Printer> {
|
||||
@@ -38,7 +46,7 @@ mod system {
|
||||
// Copies, layout, marks and colour management are already in the PDF. Preserve its
|
||||
// physical sheet size and the queue's duplex default without printing copies twice.
|
||||
let settings = craft_print::Job { printer: job.printer.map(str::to_string), title: job.title.into(), ..Default::default() };
|
||||
craft_print::submit(job.pdf, &settings).map(|note| if note.is_empty() { note } else { format!(" ({note})") }).map_err(|e| e.to_string())
|
||||
craft_print::submit(job.pdf, &settings).map_err(|e| e.to_string())
|
||||
}
|
||||
#[cfg(windows)]
|
||||
pub(crate) fn setup_command(printer: Option<&str>, default_printer: Option<&str>) -> Command {
|
||||
@@ -127,9 +135,28 @@ mod tests {
|
||||
|
||||
#[cfg(test)]
|
||||
mod turn_tests {
|
||||
use super::SystemPrint;
|
||||
use super::{SystemPrint, sent};
|
||||
use vectorcraft_ui_egui::print::PrintService;
|
||||
|
||||
#[test]
|
||||
fn the_sent_status_names_the_job_the_printer_and_the_note() {
|
||||
assert_eq!(sent("Poster", None, ""), "Sent “Poster” to the default printer");
|
||||
assert_eq!(sent("Poster", Some("Office Laser"), ""), "Sent “Poster” to Office Laser");
|
||||
assert_eq!(sent("Poster", Some("Office Laser"), "job 12"), "Sent “Poster” to Office Laser. The spooler replied: job 12");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_printer_name_ending_in_parentheses_stays_whole_in_a_translation() {
|
||||
use vectorcraft_ui_egui::i18n::{Lang, message};
|
||||
let Some(de) = Lang::from_code("de") else { panic!("no German catalog") };
|
||||
let printer = Some("HP LaserJet (Copy 1)");
|
||||
assert_eq!(message(de, &sent("Poster", printer, "")), "“Poster” an HP LaserJet (Copy 1) gesendet");
|
||||
assert_eq!(
|
||||
message(de, &sent("Poster", printer, "job 12")),
|
||||
"“Poster” an HP LaserJet (Copy 1) gesendet. Antwort der Druckwarteschlange: job 12"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_macos_queues_need_landscape_pages_turned() {
|
||||
assert_eq!(SystemPrint.turns_landscape(), !cfg!(target_os = "macos"));
|
||||
|
||||
@@ -78,7 +78,7 @@ impl Monitor {
|
||||
let scale = self.scale * zoom;
|
||||
let [x, y] = self.pos;
|
||||
let [w, h] = self.size;
|
||||
DockMonitor { name, rect: [x, y, w, h].map(|v| v as f32 / scale), scale }
|
||||
DockMonitor { name, rect: [x, y, w, h].map(|v| v as f32 / scale), scale, work_area: None }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -248,13 +248,13 @@ mod tests {
|
||||
fn floating_panels_get_monitors_in_the_points_a_window_on_them_reports() {
|
||||
let dock = |m: Monitor, zoom| m.docking(Some("m".into()), zoom);
|
||||
let plain = dock(monitor(1920, 0, 1920, 1080, 1.0), 1.0);
|
||||
assert_eq!(plain, DockMonitor { name: Some("m".into()), rect: [1920.0, 0.0, 1920.0, 1080.0], scale: 1.0 });
|
||||
assert_eq!(plain, DockMonitor { name: Some("m".into()), rect: [1920.0, 0.0, 1920.0, 1080.0], scale: 1.0, work_area: None });
|
||||
// A window at (3000, 200) on this monitor reports (1500, 100).
|
||||
let scaled = dock(monitor(1920, -200, 3840, 2160, 2.0), 1.0);
|
||||
assert_eq!(scaled, DockMonitor { name: Some("m".into()), rect: [960.0, -100.0, 1920.0, 1080.0], scale: 2.0 });
|
||||
assert_eq!(scaled, DockMonitor { name: Some("m".into()), rect: [960.0, -100.0, 1920.0, 1080.0], scale: 2.0, work_area: None });
|
||||
// The UI zoom divides what egui reports as well.
|
||||
let zoomed = dock(monitor(-2560, 0, 2560, 1440, 1.0), 1.25);
|
||||
assert_eq!(zoomed, DockMonitor { name: Some("m".into()), rect: [-2048.0, 0.0, 2048.0, 1152.0], scale: 1.25 });
|
||||
assert_eq!(zoomed, DockMonitor { name: Some("m".into()), rect: [-2048.0, 0.0, 2048.0, 1152.0], scale: 1.25, work_area: None });
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -294,13 +294,19 @@ impl GuideOptions {
|
||||
}
|
||||
}
|
||||
|
||||
/// The share of the way to its target (black or white, cool or warm, gray or full color) that the
|
||||
/// variation at `step` goes: 0 at the center, the options' reach at the outermost steps.
|
||||
pub fn step_fraction(opts: &GuideOptions, step: i32) -> f32 {
|
||||
(step.unsigned_abs() as f32 / opts.steps.max(1) as f32).min(1.0) * opts.reach()
|
||||
}
|
||||
|
||||
/// Variation of `c` at `step` (−steps..=steps: negative towards shades/cool/muted, positive towards
|
||||
/// tints/warm/vivid; 0 is `c` itself), in `c`'s model.
|
||||
pub fn variation(c: Color, opts: &GuideOptions, step: i32) -> Color {
|
||||
if step == 0 {
|
||||
return c;
|
||||
}
|
||||
let f = (step.unsigned_abs() as f32 / opts.steps.max(1) as f32).min(1.0) * opts.reach();
|
||||
let f = step_fraction(opts, step);
|
||||
let v = match opts.variation {
|
||||
Variation::TintsShades => c.lerp(if step < 0 { &Color::BLACK } else { &Color::WHITE }, f),
|
||||
Variation::WarmCool => {
|
||||
|
||||
@@ -11,6 +11,8 @@ workspace = true
|
||||
[features]
|
||||
# `vectorcraft_doc::blend::spines_built` for other crates' tests (dev-dependencies only).
|
||||
spine-count = []
|
||||
# `vectorcraft_doc::symbols_read` for other crates' tests (dev-dependencies only).
|
||||
symbol-read-count = []
|
||||
|
||||
[dependencies]
|
||||
vectorcraft-geom = { workspace = true }
|
||||
|
||||
@@ -2174,6 +2174,70 @@ pub fn blend_steps(keys: &[Arc<Node>], spec: &BlendSpec) -> Vec<usize> {
|
||||
StepCount::default().blend(keys, spec, Rail::new(keys, spec).as_ref()).0
|
||||
}
|
||||
|
||||
/// Does each pair of `keys` blended with `spec` ask for the same number of steps
|
||||
/// ([`blend_step_count`]) when each coordinate it counts from moves by up to `length` points and,
|
||||
/// for Smooth Color, the difference between keys of different colors by up to `color` (0 to 1)?
|
||||
/// False when a count sits that close to where it changes, and for Smooth Color by distance when
|
||||
/// the keys are at most `4 × length` wide or high. Specified Steps always asks for the same number.
|
||||
pub fn blend_steps_settled(keys: &[Arc<Node>], spec: &BlendSpec, length: f64, color: f64) -> bool {
|
||||
let rail = Rail::new(keys, spec);
|
||||
keys.windows(2).enumerate().all(|(i, w)| {
|
||||
let [a, b] = w else { return true };
|
||||
match spec.spacing {
|
||||
BlendSpacing::Steps(_) => true,
|
||||
// The count is `len / d` rounded, which grows with `len`.
|
||||
BlendSpacing::Distance(d) => {
|
||||
let len = rail.as_ref().map_or_else(|| center_of(a).distance(center_of(b)), |r| r.len(i));
|
||||
let count = |len: f64| blend_step_count(a, b, BlendSpacing::Distance(d), len);
|
||||
count(len - length) == count(len + length)
|
||||
}
|
||||
BlendSpacing::SmoothColor => smooth_color_settled(a, b, length, color),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// [`blend_steps_settled`] for one pair of Smooth Color keys. Each count [`blend_step_count`]
|
||||
/// takes grows with what it counts from (the color difference, the keys' reach, the distance
|
||||
/// between their edges in key sizes), so the pair is settled when the least and the most of
|
||||
/// these ask for the same count.
|
||||
fn smooth_color_settled(a: &Node, b: &Node, length: f64, color: f64) -> bool {
|
||||
let bounds = a.visual_bounds().zip(b.visual_bounds());
|
||||
let by_level = |d: f64| level_steps(d.max(0.0)) as usize;
|
||||
match (color_distance(a, b), bounds) {
|
||||
// Colors that differ, but by too little to count, or by little more: moving them may cross
|
||||
// where they stop counting as the same. (The same colors stay the same.)
|
||||
(Some(d), _) if d > 0.0 && d * 255.0 <= 1e-3 + color * 255.0 => false,
|
||||
(Some(d), Some((ba, bb))) if d * 255.0 > 1e-3 => {
|
||||
let (ca, cb) = (ba.center(), bb.center());
|
||||
let reach =
|
||||
[(ca.x - cb.x).abs(), (ca.y - cb.y).abs(), ba.width(), ba.height(), bb.width(), bb.height()].into_iter().fold(0.0f64, f64::max);
|
||||
// The centers and sizes move by up to twice `length`.
|
||||
let by_density = |r: f64| (8.0 * r.max(0.0) + 0.5).floor().clamp(1.0, 254.0) as usize;
|
||||
let least = by_level(d - color).min(by_density(reach - 2.0 * length));
|
||||
let most = by_level(d + color).min(by_density(reach + 2.0 * length));
|
||||
reach.is_finite() && least == most
|
||||
}
|
||||
(Some(d), None) if d * 255.0 > 1e-3 => by_level(d - color) == by_level(d + color),
|
||||
(_, Some((ba, bb))) => {
|
||||
let (w, h) = ((ba.width() + bb.width()) / 2.0, (ba.height() + bb.height()) / 2.0);
|
||||
if w <= 4.0 * length || h <= 4.0 * length {
|
||||
return false;
|
||||
}
|
||||
let dx = (ba.x0 - bb.x0).abs().max((ba.x1 - bb.x1).abs());
|
||||
let dy = (ba.y0 - bb.y0).abs().max((ba.y1 - bb.y1).abs());
|
||||
// Each edge moves by up to `length`: the distances between them by up to twice that,
|
||||
// and the mean sizes too.
|
||||
let q = |dx: f64, dy: f64, w: f64, h: f64| (dx.max(0.0) / w).max(dy.max(0.0) / h);
|
||||
let count = |q: f64| ((q + 0.5).floor() - 1.0).clamp(1.0, 1000.0) as usize;
|
||||
let m = 2.0 * length;
|
||||
let least = q(dx - m, dy - m, w + m, h + m);
|
||||
let most = q(dx + m, dy + m, w - m, h - m);
|
||||
least.is_finite() && most.is_finite() && count(least) == count(most)
|
||||
}
|
||||
(_, None) => true,
|
||||
}
|
||||
}
|
||||
|
||||
/// Evaluate a blend: the keys and generated steps in paint order. The steps keep to
|
||||
/// [`MAX_BLEND_STEPS`] in all ([`blend_steps`]).
|
||||
pub fn blend_expand(keys: &[Arc<Node>], spec: &BlendSpec) -> Vec<Node> {
|
||||
@@ -3535,4 +3599,46 @@ mod tests {
|
||||
let (keys, spec) = blend_parts(&outer).unwrap();
|
||||
assert_eq!(blend_steps(keys, spec), vec![99]);
|
||||
}
|
||||
|
||||
/// A count is settled when moving the lengths by 0.01 pt and the colors by 0.001 can't change
|
||||
/// it: Specified Steps always; Specified Distance unless the spine's length is a half step from
|
||||
/// where its count changes; Smooth Color unless the colors differ by too little to count, the
|
||||
/// color difference or the keys' reach sits where its count changes, or keys of the same color
|
||||
/// are at most four times 0.01 pt wide.
|
||||
#[test]
|
||||
fn steps_settle_unless_rounding_can_change_their_count() {
|
||||
let (length, color) = (0.01, 0.001);
|
||||
let settled = |a: Node, b: Node, spacing: BlendSpacing| {
|
||||
let spec = BlendSpec { spacing, ..Default::default() };
|
||||
blend_steps_settled(&[Arc::new(a), Arc::new(b)], &spec, length, color)
|
||||
};
|
||||
let filled = |x: f64, size: f64, c: Color| smooth_key((x, 0.0), (size, size), Paint::solid(c), Paint::None, 0.0);
|
||||
let gray = |x: f64| filled(x, 10.0, Color::rgb(0.5, 0.5, 0.5));
|
||||
|
||||
// The keys' centers are 100 pt apart: 100 / 25 is 4, and 100 / (100 / 3.5) is 3.5.
|
||||
assert!(settled(gray(0.0), gray(100.0), BlendSpacing::Steps(3)));
|
||||
assert!(settled(gray(0.0), gray(100.0), BlendSpacing::Distance(25.0)));
|
||||
assert!(!settled(gray(0.0), gray(100.0), BlendSpacing::Distance(100.0 / 3.5)));
|
||||
|
||||
// Smooth Color between colors that differ: by a 2,000th of a step, by 51 steps of 255
|
||||
// (settled) and by 51.5 (where the count changes).
|
||||
let red = |x: f64, r: f32| filled(x, 10.0, Color::rgb(r, 0.0, 0.0));
|
||||
assert!(!settled(red(0.0, 0.0), red(100.0, 0.0005), BlendSpacing::SmoothColor));
|
||||
assert!(settled(red(0.0, 0.0), red(100.0, 51.0 / 255.0), BlendSpacing::SmoothColor));
|
||||
assert!(!settled(red(0.0, 0.0), red(100.0, 51.5 / 255.0), BlendSpacing::SmoothColor));
|
||||
// Black to white is counted by the keys' reach, eight steps a point: 10 pt is settled,
|
||||
// 10.0625 pt (80.5 steps) is not.
|
||||
let near = |size: f64| settled(filled(0.0, size, Color::BLACK), filled(5.0, size, Color::WHITE), BlendSpacing::SmoothColor);
|
||||
assert!(near(10.0));
|
||||
assert!(!near(10.0625));
|
||||
// Keys without bounds are counted by their colors alone.
|
||||
let bare = |r: f32| Node::path(NodeId(1), PathData::default(), Appearance::basic(Paint::solid(Color::rgb(r, 0.0, 0.0)), Paint::None, 0.0));
|
||||
assert!(settled(bare(0.0), bare(51.0 / 255.0), BlendSpacing::SmoothColor));
|
||||
assert!(!settled(bare(0.0), bare(51.5 / 255.0), BlendSpacing::SmoothColor));
|
||||
// Keys of the same color are counted by distance in key sizes; keys 0.04 pt wide or less
|
||||
// are never settled.
|
||||
assert!(settled(gray(0.0), gray(100.0), BlendSpacing::SmoothColor));
|
||||
assert!(!settled(filled(0.0, 0.04, Color::rgb(0.5, 0.5, 0.5)), filled(100.0, 0.04, Color::rgb(0.5, 0.5, 0.5)), BlendSpacing::SmoothColor));
|
||||
assert!(settled(filled(0.0, 0.05, Color::rgb(0.5, 0.5, 0.5)), filled(100.0, 0.05, Color::rgb(0.5, 0.5, 0.5)), BlendSpacing::SmoothColor));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -75,6 +75,9 @@ pub mod style_libs;
|
||||
pub mod swatches;
|
||||
mod symbols;
|
||||
pub use symbols::SymbolBoxes;
|
||||
#[cfg(any(test, feature = "symbol-read-count"))]
|
||||
#[doc(hidden)]
|
||||
pub use symbols::symbols_read;
|
||||
pub mod text;
|
||||
pub mod trace;
|
||||
pub mod twist;
|
||||
|
||||
+27
-1
@@ -65,7 +65,9 @@ pub use expand::{
|
||||
#[cfg(test)]
|
||||
use mesh::grid_eval;
|
||||
pub use mesh::{Coons, GradientMesh, MeshAppearance, MeshPiece, MeshPoint, MeshQuad, default_fidelity, grid_points, nodes_bounds};
|
||||
pub use warp::{WARP_NET, WarpNet, WarpStyle, fit_piece, map_nonlinear, map_nonlinear_within, pieces, uses_net, warp_point, warp_version};
|
||||
pub use warp::{
|
||||
WARP_NET, WarpNet, WarpStyle, fit_piece, map_nonlinear, map_nonlinear_within, map_smooth_within, pieces, uses_net, warp_point, warp_version,
|
||||
};
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
@@ -88,6 +90,30 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// The smooth map takes each handle along the map's derivative, also far from the origin,
|
||||
/// where a fixed sampling step would round away (#7069): the identity map keeps a curve's
|
||||
/// handles there.
|
||||
#[test]
|
||||
fn map_smooth_within_keeps_handles_far_from_the_origin() {
|
||||
for at in [0.0, 1e13] {
|
||||
let o = Point::new(at, at);
|
||||
let curve = PathData::single(vectorcraft_geom::SubPath::new(
|
||||
vec![
|
||||
vectorcraft_geom::Anchor::with_handles(o, o, o + vectorcraft_geom::Vec2::new(0.2, 0.0)),
|
||||
vectorcraft_geom::Anchor::with_handles(
|
||||
o + vectorcraft_geom::Vec2::new(1.0, 0.5),
|
||||
o + vectorcraft_geom::Vec2::new(0.8, 0.5),
|
||||
o + vectorcraft_geom::Vec2::new(1.0, 0.5),
|
||||
),
|
||||
],
|
||||
false,
|
||||
));
|
||||
let out = map_smooth_within(&curve, 10.0, usize::MAX, |p| p);
|
||||
let (a, b) = (&curve.subpaths[0].anchors, &out.subpaths[0].anchors);
|
||||
assert!(a[0].h_out.distance(b[0].h_out) < 0.01 && a[1].h_in.distance(b[1].h_in) < 0.01, "at {at}: {:?} {:?}", b[0].h_out, b[1].h_in);
|
||||
}
|
||||
}
|
||||
|
||||
/// #3578: a non-linear map within an anchor budget splits its segments into longer pieces,
|
||||
/// down to one a segment, and matches the plain map where the budget leaves room.
|
||||
#[test]
|
||||
|
||||
@@ -497,6 +497,37 @@ pub fn map_nonlinear(path: &PathData, max_piece: f64, f: impl Fn(Point) -> Point
|
||||
/// where pieces of `max_piece` would make more, the pieces grow until they don't ([`fit_piece`]),
|
||||
/// a coarser approximation of the image curve. Geometry effects map within their anchor budget.
|
||||
pub fn map_nonlinear_within(path: &PathData, max_piece: f64, max: usize, f: impl Fn(Point) -> Point) -> PathData {
|
||||
map_pieces_within(path, max_piece, max, &f, |_, h| f(h))
|
||||
}
|
||||
|
||||
/// [`map_nonlinear_within`] with each handle mapped along `f`'s derivative at its point
|
||||
/// ([`mapped_handle`]) rather than as a point of its own: where `f` turns quickly (Twist), handles
|
||||
/// mapped as points point different ways on the two sides of a join and the curve kinks there
|
||||
/// (#7069); along the derivative, the pieces on both sides leave each join in one direction.
|
||||
pub fn map_smooth_within(path: &PathData, max_piece: f64, max: usize, f: impl Fn(Point) -> Point) -> PathData {
|
||||
map_pieces_within(path, max_piece, max, &f, |p, h| mapped_handle(&f, p, h))
|
||||
}
|
||||
|
||||
/// Handle `h` of point `p` mapped through `f`: `f(p)` plus `f`'s derivative at `p` along `h - p`
|
||||
/// (a central difference), so the image curve leaves `f(p)` the way `f` takes the curve.
|
||||
fn mapped_handle(f: &impl Fn(Point) -> Point, p: Point, h: Point) -> Point {
|
||||
let v = h - p;
|
||||
let len = v.hypot();
|
||||
// A retracted handle stays retracted, and a non-finite one has no direction to follow.
|
||||
if len.is_nan() || len <= 0.0 || len.is_infinite() {
|
||||
return f(p);
|
||||
}
|
||||
// A thousandth of the handle, or more where the coordinates are so large that so short a
|
||||
// step would round away (#7069): the samples stay a billionth of the coordinates apart, and
|
||||
// at most at the handle's own end.
|
||||
let size = p.x.abs().max(p.y.abs()).max(1.0);
|
||||
let step = (1e-3f64).max(size * 1e-9 / len).min(1.0);
|
||||
let d = (f(p + v * step) - f(p - v * step)) / (2.0 * step);
|
||||
f(p) + d
|
||||
}
|
||||
|
||||
/// [`map_nonlinear_within`]'s pieces, with `handle(point, handle)` giving each mapped handle.
|
||||
fn map_pieces_within(path: &PathData, max_piece: f64, max: usize, f: &impl Fn(Point) -> Point, handle: impl Fn(Point, Point) -> Point) -> PathData {
|
||||
let mut max_piece = max_piece.max(1e-3);
|
||||
// Each segment adds one anchor per piece past its first.
|
||||
let room = max.saturating_sub(path.anchor_count());
|
||||
@@ -516,20 +547,20 @@ pub fn map_nonlinear_within(path: &PathData, max_piece: f64, max: usize, f: impl
|
||||
let mut pending_in: Option<Point> = None;
|
||||
for i in 0..n {
|
||||
let a = &sp.anchors[i];
|
||||
let h_in = pending_in.take().unwrap_or_else(|| f(a.h_in));
|
||||
res.push(Anchor { p: f(a.p), h_in, h_out: f(a.h_out), kind: a.kind });
|
||||
let h_in = pending_in.take().unwrap_or_else(|| handle(a.p, a.h_in));
|
||||
res.push(Anchor { p: f(a.p), h_in, h_out: handle(a.p, a.h_out), kind: a.kind });
|
||||
if i < segs {
|
||||
let c = seg_cubic(sp, i);
|
||||
let k = pieces(poly_len(&c), max_piece, MAX_PIECES);
|
||||
for j in 0..k {
|
||||
let sub = c.subsegment((j as f64 / k as f64)..((j + 1) as f64 / k as f64));
|
||||
if let Some(last) = res.last_mut() {
|
||||
last.h_out = f(sub.p1);
|
||||
last.h_out = handle(sub.p0, sub.p1);
|
||||
}
|
||||
if j + 1 < k {
|
||||
res.push(Anchor { p: f(sub.p3), h_in: f(sub.p2), h_out: f(sub.p3), kind: Default::default() });
|
||||
res.push(Anchor { p: f(sub.p3), h_in: handle(sub.p3, sub.p2), h_out: f(sub.p3), kind: Default::default() });
|
||||
} else {
|
||||
pending_in = Some(f(sub.p2));
|
||||
pending_in = Some(handle(sub.p3, sub.p2));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+60
-13
@@ -183,23 +183,69 @@ impl Selection {
|
||||
self.key_anchor = None;
|
||||
}
|
||||
}
|
||||
/// [`Self::add`] for each of `ids` in order, going through the selected objects once.
|
||||
pub fn add_all(&mut self, ids: impl IntoIterator<Item = NodeId>) {
|
||||
self.each(ids, false);
|
||||
}
|
||||
/// [`Self::toggle`] for each of `ids` in order, going through the selected objects once. An id
|
||||
/// listed twice is removed and then added again at the end.
|
||||
pub fn toggle_all(&mut self, ids: impl IntoIterator<Item = NodeId>) {
|
||||
self.each(ids, true);
|
||||
}
|
||||
/// [`Self::add_all`], or [`Self::toggle_all`] when `toggle` is set. Each selected object slot
|
||||
/// carries the number of the activation that made it; an id's slots are kept only when they
|
||||
/// carry its current activation, so a removal drops every slot of the id at once.
|
||||
fn each(&mut self, ids: impl IntoIterator<Item = NodeId>, toggle: bool) {
|
||||
use std::collections::hash_map::{Entry, HashMap};
|
||||
let mut ids = ids.into_iter().peekable();
|
||||
if ids.peek().is_none() {
|
||||
return;
|
||||
}
|
||||
self.target = None;
|
||||
self.slices.clear();
|
||||
self.symbol_part = None;
|
||||
self.on_path_member = None;
|
||||
let mut live: HashMap<NodeId, usize> = self.objects.iter().map(|id| (*id, 0)).collect();
|
||||
let mut added: Vec<(NodeId, usize)> = Vec::new();
|
||||
let mut removed = false;
|
||||
for id in ids {
|
||||
match live.entry(id) {
|
||||
Entry::Vacant(e) => {
|
||||
let activation = added.len() + 1;
|
||||
e.insert(activation);
|
||||
added.push((id, activation));
|
||||
}
|
||||
Entry::Occupied(e) if toggle => {
|
||||
e.remove();
|
||||
removed = true;
|
||||
self.anchors.remove(&id);
|
||||
self.segments.remove(&id);
|
||||
if self.key == Some(id) {
|
||||
self.key = None;
|
||||
}
|
||||
if self.key_anchor.is_some_and(|(k, _)| k == id) {
|
||||
self.key_anchor = None;
|
||||
}
|
||||
}
|
||||
Entry::Occupied(_) => {}
|
||||
}
|
||||
}
|
||||
if removed {
|
||||
self.objects.retain(|id| live.get(id) == Some(&0));
|
||||
}
|
||||
self.objects.extend(added.into_iter().filter(|(id, n)| live.get(id) == Some(n)).map(|(id, _)| id));
|
||||
}
|
||||
/// Select slices `ids` (see [`Selection::slices`]) and nothing else.
|
||||
pub fn set_slices(&mut self, ids: impl IntoIterator<Item = NodeId>) {
|
||||
self.clear();
|
||||
for id in ids {
|
||||
if !self.slices.contains(&id) {
|
||||
self.slices.push(id);
|
||||
}
|
||||
}
|
||||
let mut seen = HashSet::new();
|
||||
self.slices.extend(ids.into_iter().filter(|id| seen.insert(*id)));
|
||||
}
|
||||
/// Select ruler guides `ids` (see [`Selection::guides`]) and nothing else.
|
||||
pub fn set_guides(&mut self, ids: impl IntoIterator<Item = NodeId>) {
|
||||
self.clear();
|
||||
for i in ids {
|
||||
if !self.guides.contains(&i) {
|
||||
self.guides.push(i);
|
||||
}
|
||||
}
|
||||
let mut seen = HashSet::new();
|
||||
self.guides.extend(ids.into_iter().filter(|id| seen.insert(*id)));
|
||||
}
|
||||
/// Add ruler guide `i` to the selection, or take it out, keeping the selected objects (a
|
||||
/// Shift-click on a guide).
|
||||
@@ -426,10 +472,11 @@ impl Selection {
|
||||
};
|
||||
let locks = doc.locked_artboards();
|
||||
ids.retain(|i| !locks.holds_id(*i));
|
||||
if ids.iter().all(|i| self.contains(*i)) {
|
||||
ids.iter().for_each(|i| self.remove(*i));
|
||||
let selected: HashSet<NodeId> = self.objects.iter().copied().collect();
|
||||
if ids.iter().all(|i| selected.contains(i)) {
|
||||
self.remove_all(ids);
|
||||
} else {
|
||||
ids.into_iter().for_each(|i| self.add(i));
|
||||
self.add_all(ids);
|
||||
}
|
||||
self.target = None;
|
||||
}
|
||||
|
||||
@@ -45,6 +45,148 @@ fn remove_all_does_what_removing_each_does() {
|
||||
assert_eq!(none, s);
|
||||
}
|
||||
|
||||
/// A selection with every field set: objects 1 to 6 with 3 listed twice, anchors, segments, a key,
|
||||
/// a key anchor, a target, slices, guides, a key guide, new art, a symbol part and an on-path member.
|
||||
fn seeded() -> Selection {
|
||||
let mut s = Selection { objects: [1, 2, 3, 4, 5, 3, 6].map(NodeId).to_vec(), ..Selection::default() };
|
||||
for i in [2, 3, 4, 5] {
|
||||
s.anchors.insert(NodeId(i), BTreeSet::from([(0, 1)]));
|
||||
s.segments.insert(NodeId(i), BTreeSet::from([(0, 0)]));
|
||||
}
|
||||
s.key = Some(NodeId(4));
|
||||
s.key_anchor = Some((NodeId(5), (0, 1)));
|
||||
s.target = Some(NodeId(3));
|
||||
s.slices = vec![NodeId(9)];
|
||||
s.guides = vec![NodeId(10)];
|
||||
s.key_guide = Some(NodeId(10));
|
||||
s.new_art = Arc::new(HashSet::from([NodeId(2)]));
|
||||
s.symbol_part = Some(SymbolPart { instance: NodeId(1), path: vec![0] });
|
||||
s.on_path_member = Some(NodeId(11));
|
||||
s
|
||||
}
|
||||
|
||||
/// Id lists with repeats, ids not selected, removals followed by additions, and the empty list.
|
||||
fn id_streams() -> Vec<Vec<NodeId>> {
|
||||
let mut streams: Vec<Vec<NodeId>> = [
|
||||
vec![],
|
||||
vec![4],
|
||||
vec![7],
|
||||
vec![3],
|
||||
vec![4, 1, 4, 7],
|
||||
vec![7, 8, 7, 7, 3, 3, 5],
|
||||
vec![1, 2, 3, 4, 5, 6],
|
||||
vec![6, 5, 4, 3, 2, 1, 1, 2, 3],
|
||||
vec![8, 2, 8, 2, 9, 9, 9],
|
||||
]
|
||||
.into_iter()
|
||||
.map(|ids| ids.into_iter().map(NodeId).collect())
|
||||
.collect();
|
||||
// Deterministic pseudo-random lists over ids 1 to 12, half of them selected to start with.
|
||||
let mut x: u64 = 0x9e37_79b9_7f4a_7c15;
|
||||
for len in [5, 17, 40, 120] {
|
||||
let ids = (0..len)
|
||||
.map(|_| {
|
||||
x ^= x << 13;
|
||||
x ^= x >> 7;
|
||||
x ^= x << 17;
|
||||
NodeId(x % 12 + 1)
|
||||
})
|
||||
.collect();
|
||||
streams.push(ids);
|
||||
}
|
||||
streams
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn add_all_does_what_adding_each_does() {
|
||||
for ids in id_streams() {
|
||||
let mut one_by_one = seeded();
|
||||
for id in &ids {
|
||||
one_by_one.add(*id);
|
||||
}
|
||||
let mut all = seeded();
|
||||
all.add_all(ids.iter().copied());
|
||||
assert_eq!(all, one_by_one, "add_all({ids:?})");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn toggle_all_does_what_toggling_each_does() {
|
||||
for ids in id_streams() {
|
||||
let mut one_by_one = seeded();
|
||||
for id in &ids {
|
||||
one_by_one.toggle(*id);
|
||||
}
|
||||
let mut all = seeded();
|
||||
all.toggle_all(ids.iter().copied());
|
||||
assert_eq!(all, one_by_one, "toggle_all({ids:?})");
|
||||
}
|
||||
// An id toggled twice is selected again, at the end, without the anchors it had.
|
||||
let mut s = seeded();
|
||||
s.toggle_all([NodeId(2), NodeId(2)]);
|
||||
assert_eq!(s.objects, [1, 3, 4, 5, 3, 6, 2].map(NodeId));
|
||||
assert!(!s.anchors.contains_key(&NodeId(2)) && !s.segments.contains_key(&NodeId(2)));
|
||||
// A removed key and key anchor stay cleared.
|
||||
let mut s = seeded();
|
||||
s.toggle_all([NodeId(4), NodeId(5), NodeId(4), NodeId(5)]);
|
||||
assert_eq!((s.key, s.key_anchor), (None, None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_slices_and_set_guides_keep_the_first_of_each_id() {
|
||||
let mut s = seeded();
|
||||
s.set_slices([3, 1, 3, 2, 1].map(NodeId));
|
||||
assert_eq!(s.slices, [3, 1, 2].map(NodeId));
|
||||
assert!(s.objects.is_empty() && s.guides.is_empty());
|
||||
s.set_guides([5, 5, 4, 6, 4].map(NodeId));
|
||||
assert_eq!(s.guides, [5, 4, 6].map(NodeId));
|
||||
assert!(s.slices.is_empty());
|
||||
}
|
||||
|
||||
/// Shift-clicking a target circle does what removing or adding each of its art one by one does,
|
||||
/// for a layer with art, an empty layer and an object.
|
||||
#[test]
|
||||
fn toggle_target_does_what_toggling_its_art_one_by_one_does() {
|
||||
let rect = || vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(0.0, 0.0, 10.0, 10.0));
|
||||
let mut d = Document::new(100.0, 100.0);
|
||||
let l = d.layers[0].id;
|
||||
let art: Vec<NodeId> = (0..4).map(|_| d.alloc_id()).collect();
|
||||
for id in &art {
|
||||
d.insert(Some(l), usize::MAX, Node::path(*id, rect(), crate::Appearance::default_art())).unwrap();
|
||||
}
|
||||
let empty = d.alloc_id();
|
||||
d.insert(None, usize::MAX, Node::layer(empty, "Empty", crate::LayerColor::Preset(2))).unwrap();
|
||||
let one_by_one = |s: &Selection, id: NodeId| {
|
||||
let mut s = s.clone();
|
||||
let ids = match d.node(id) {
|
||||
Some(n) if n.is_layer() => n.layer_art(true),
|
||||
_ => vec![id],
|
||||
};
|
||||
if ids.iter().all(|i| s.contains(*i)) {
|
||||
ids.iter().for_each(|i| s.remove(*i));
|
||||
} else {
|
||||
ids.into_iter().for_each(|i| s.add(i));
|
||||
}
|
||||
s.target = None;
|
||||
s
|
||||
};
|
||||
let mut starts = vec![Selection::default()];
|
||||
for objects in [vec![art[1]], vec![art[3], art[0], art[1], art[2]], vec![art[2], art[2], NodeId(99)]] {
|
||||
let mut s = seeded();
|
||||
s.objects = objects;
|
||||
s.key = s.objects.first().copied();
|
||||
s.anchors.insert(art[1], BTreeSet::from([(0, 0)]));
|
||||
starts.push(s);
|
||||
}
|
||||
for start in &starts {
|
||||
for id in [l, empty, art[2], NodeId(99)] {
|
||||
let mut s = start.clone();
|
||||
s.toggle_target(&d, id);
|
||||
assert_eq!(s, one_by_one(start, id), "toggle_target({id:?}) on {:?}", start.objects);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remove_all_does_what_removing_each_does_to_a_key_anchor_and_symbol_part() {
|
||||
for kept in [false, true] {
|
||||
|
||||
@@ -9,7 +9,7 @@ use std::sync::Arc;
|
||||
use vectorcraft_geom::{Affine, Rect};
|
||||
|
||||
use crate::symbol_nine_slice::transformed;
|
||||
use crate::{AppearanceItem, Document, MAX_SYMBOL_NODES, NineSliceMap, Node, NodeKind, SYMBOL_HALF};
|
||||
use crate::{AppearanceItem, Document, MAX_SYMBOL_NODES, NineSliceMap, Node, NodeKind, SYMBOL_HALF, Symbol};
|
||||
|
||||
/// The box a symbol instance is measured by when its symbol's art has no box
|
||||
/// ([`SymbolBoxes::art`]), and in [`Node::geometric_bounds`]: the 20 × 20 square around the origin
|
||||
@@ -312,7 +312,7 @@ impl Document {
|
||||
/// Each symbol name of this document → the index of the first symbol of that name (the one a
|
||||
/// name finds).
|
||||
pub(crate) fn symbol_names(&self) -> SymbolNames {
|
||||
#[cfg(test)]
|
||||
#[cfg(any(test, feature = "symbol-read-count"))]
|
||||
SYMBOLS_READ.with(|c| c.set(c.get() + self.symbols.len()));
|
||||
let mut names = HashMap::with_capacity(self.symbols.len());
|
||||
for (i, s) in self.symbols.iter().enumerate() {
|
||||
@@ -322,7 +322,7 @@ impl Document {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[cfg(any(test, feature = "symbol-read-count"))]
|
||||
thread_local! {
|
||||
/// How many symbols [`Document::symbol_names`] has read on this thread.
|
||||
pub(crate) static SYMBOLS_READ: Cell<usize> = const { Cell::new(0) };
|
||||
@@ -330,12 +330,31 @@ thread_local! {
|
||||
static ART_BOXES_MEASURED: Cell<usize> = const { Cell::new(0) };
|
||||
}
|
||||
|
||||
/// How many symbols [`Document::symbol_names`] has read on this thread, for other crates' tests
|
||||
/// that count how often the symbol list is read to find symbols by name (the `symbol-read-count`
|
||||
/// feature, dev-dependencies only).
|
||||
#[cfg(any(test, feature = "symbol-read-count"))]
|
||||
#[doc(hidden)]
|
||||
pub fn symbols_read() -> usize {
|
||||
SYMBOLS_READ.with(Cell::get)
|
||||
}
|
||||
|
||||
impl<'a> SymbolBoxes<'a> {
|
||||
/// The document whose symbols these are.
|
||||
pub fn document(&self) -> &'a Document {
|
||||
self.doc
|
||||
}
|
||||
|
||||
/// New boxes for the same document, none measured yet and with none of the options set, that
|
||||
/// find symbols by name through the same index as these boxes ([`Self::symbol`]). Measuring
|
||||
/// objects one at a time in boxes of their own made this way measures them as boxes made by
|
||||
/// [`Document::symbol_boxes`] do, without reading the symbol list again.
|
||||
pub fn unmeasured(&self) -> SymbolBoxes<'a> {
|
||||
let doc: &'a Document = self.doc;
|
||||
let names = self.names.get_or_init(|| Arc::new(doc.symbol_names()));
|
||||
doc.symbol_boxes().with_names(names)
|
||||
}
|
||||
|
||||
/// Makes these boxes find symbols by `names` ([`Document::symbol_names`]), made from the
|
||||
/// document's symbols while they had the names and order they have now.
|
||||
pub(crate) fn with_names(self, names: &Arc<SymbolNames>) -> Self {
|
||||
@@ -343,19 +362,24 @@ impl<'a> SymbolBoxes<'a> {
|
||||
self
|
||||
}
|
||||
|
||||
/// The art of the first symbol of the document named `name`, found in time independent of the
|
||||
/// number of symbols after the first lookup.
|
||||
pub(crate) fn symbol_art(&self, name: &str) -> Option<&'a Arc<Node>> {
|
||||
/// The first symbol of the document named `name`, found in time independent of the number of
|
||||
/// symbols after the first lookup.
|
||||
pub fn symbol(&self, name: &str) -> Option<&'a Symbol> {
|
||||
let doc: &'a Document = self.doc;
|
||||
let names = self.names.get_or_init(|| Arc::new(doc.symbol_names()));
|
||||
let i = *names.get(name)?;
|
||||
match doc.symbols.get(i) {
|
||||
Some(s) if s.name == name => Some(&s.art),
|
||||
Some(s) if s.name == name => Some(s),
|
||||
// Names that no longer match the symbols: the first symbol of that name.
|
||||
_ => doc.symbols.iter().find(|s| s.name == name).map(|s| &s.art),
|
||||
_ => doc.symbols.iter().find(|s| s.name == name),
|
||||
}
|
||||
}
|
||||
|
||||
/// The art of the first symbol of the document named `name` ([`Self::symbol`]).
|
||||
pub(crate) fn symbol_art(&self, name: &str) -> Option<&'a Arc<Node>> {
|
||||
self.symbol(name).map(|s| &s.art)
|
||||
}
|
||||
|
||||
/// Makes these boxes measure every symbol instance as [`Node::reach_bounds_with`] does, by its
|
||||
/// art box alone. An instance that scales or turns stroked art then measures a little larger
|
||||
/// than with [`Node::visual_bounds_with`], and its art is not transformed to measure it. The
|
||||
@@ -904,6 +928,57 @@ mod tests {
|
||||
assert_eq!(s.sliced_placed.get(), 13);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn symbols_are_found_by_name_reading_the_list_once() {
|
||||
// 2,000 symbols, then two named "Mark": a name finds the first.
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
for i in 0..2000 {
|
||||
let r = rect(&mut d, Rect::new(0.0, 0.0, 1.0, 1.0), 0.0);
|
||||
symbol(&mut d, &format!("Filler {i}"), vec![r]);
|
||||
}
|
||||
let (first, second) = (rect(&mut d, Rect::new(0.0, 0.0, 10.0, 10.0), 0.0), rect(&mut d, Rect::new(0.0, 0.0, 20.0, 20.0), 0.0));
|
||||
symbol(&mut d, "Mark", vec![first]);
|
||||
symbol(&mut d, "Mark", vec![second]);
|
||||
let read = || SYMBOLS_READ.with(Cell::get);
|
||||
let before = read();
|
||||
let s = d.symbol_boxes();
|
||||
for _ in 0..1000 {
|
||||
assert!(s.symbol("Mark").is_some_and(|m| std::ptr::eq(m, &d.symbols[2000])));
|
||||
assert!(s.symbol("Filler 7").is_some_and(|m| std::ptr::eq(m, &d.symbols[7])));
|
||||
assert!(s.symbol("Nowhere").is_none());
|
||||
}
|
||||
assert_eq!(read() - before, d.symbols.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unmeasured_boxes_share_the_index_and_nothing_measured() {
|
||||
// 2,000 symbols, then a 9-slice frame held, scaled, by "Holder", whose instances spend
|
||||
// the boxes' budget of placed objects.
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
for i in 0..2000 {
|
||||
let r = rect(&mut d, Rect::new(0.0, 0.0, 1.0, 1.0), 0.0);
|
||||
symbol(&mut d, &format!("Filler {i}"), vec![r]);
|
||||
}
|
||||
let frame = rect(&mut d, Rect::new(0.0, 0.0, 100.0, 100.0), 1.0);
|
||||
symbol(&mut d, "Panel", vec![frame]);
|
||||
d.set_symbol_nine_slice("Panel", Some(crate::SymbolNineSlice::default()));
|
||||
let wide = instance(&mut d, "Panel", Affine::scale_non_uniform(2.0, 1.0));
|
||||
symbol(&mut d, "Holder", vec![wide]);
|
||||
let holder = instance(&mut d, "Holder", Affine::scale_non_uniform(1.5, 1.5));
|
||||
let fresh = holder.visual_bounds_with(&d.symbol_boxes().quick());
|
||||
let read = || SYMBOLS_READ.with(Cell::get);
|
||||
let s = d.symbol_boxes().quick();
|
||||
assert_eq!(holder.visual_bounds_with(&s), fresh);
|
||||
assert!(s.sliced_placed.get() > 0);
|
||||
let before = read();
|
||||
let u = s.unmeasured();
|
||||
assert_eq!(read(), before, "the index is shared");
|
||||
assert!(u.measured.borrow().is_empty() && u.sliced.borrow().is_empty() && u.reaches.borrow().is_empty());
|
||||
assert_eq!((u.sliced_placed.get(), u.holders.get(), u.quick.get()), (0, 0, false));
|
||||
assert_eq!(holder.visual_bounds_with(&u.quick()), fresh);
|
||||
assert_eq!(read(), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn measuring_9_slice_instances_reads_the_symbol_list_once() {
|
||||
// 2,000 symbols, then a frame with guides and a symbol with guides holding the frame
|
||||
|
||||
@@ -27,7 +27,11 @@ impl TextObject {
|
||||
/// Character attributes as presented by controls (stored runs stay local for layout
|
||||
/// and rich-text clipboard operations). Explicit vertical character scale stays separate.
|
||||
pub fn effective_char_style(&self, style: &CharStyle) -> Option<CharStyle> {
|
||||
let scale = self.style_scale()?;
|
||||
Self::scaled_char_style(style, self.style_scale()?)
|
||||
}
|
||||
|
||||
/// `style` with `scale` taken into its attributes ([`Self::effective_char_style`]).
|
||||
fn scaled_char_style(style: &CharStyle, scale: TextStyleScale) -> Option<CharStyle> {
|
||||
let mut style = style.clone();
|
||||
style.size *= scale.points;
|
||||
style.leading = style.leading.map(|v| v * scale.points);
|
||||
@@ -57,19 +61,27 @@ impl TextObject {
|
||||
/// scale from `xf`, so panels show document-point sizes without a separate transform factor.
|
||||
/// Returns `false` when there is nothing to bake (identity scale or an unrepresentable
|
||||
/// transform).
|
||||
///
|
||||
/// Type on a path bakes only the uniform part of the scale (the vertical one) and keeps any
|
||||
/// stretch in `xf`: its brackets and glyphs sit at fractions of the path's length, which a
|
||||
/// non-uniform scale of the path would move, and a uniform one keeps.
|
||||
pub fn scale_text_attributes(&mut self) -> bool {
|
||||
let Some(scale) = self.style_scale() else { return false };
|
||||
if (scale.points - 1.0).abs() <= 1e-12 && (scale.horizontal - 1.0).abs() <= 1e-12 {
|
||||
let Some(mut scale) = self.style_scale() else { return false };
|
||||
let [a, b, c, d, _, _] = self.xf.as_coeffs();
|
||||
let (mut sx, sy) = (a.hypot(b), c.hypot(d));
|
||||
if sx <= 1e-12 || sy <= 1e-12 {
|
||||
return false;
|
||||
}
|
||||
let [a, b, c, d, _, _] = self.xf.as_coeffs();
|
||||
let (sx, sy) = (a.hypot(b), c.hypot(d));
|
||||
if sx <= 1e-12 || sy <= 1e-12 {
|
||||
if matches!(self.kind, TextKind::OnPath { .. }) {
|
||||
scale.horizontal = 1.0;
|
||||
sx = sy;
|
||||
}
|
||||
if (scale.points - 1.0).abs() <= 1e-12 && (scale.horizontal - 1.0).abs() <= 1e-12 {
|
||||
return false;
|
||||
}
|
||||
let mut baked = Vec::with_capacity(self.runs.len());
|
||||
for run in &self.runs {
|
||||
let Some(eff) = self.effective_char_style(&run.style) else { return false };
|
||||
let Some(eff) = Self::scaled_char_style(&run.style, scale) else { return false };
|
||||
baked.push(eff);
|
||||
}
|
||||
for (run, style) in self.runs.iter_mut().zip(baked) {
|
||||
@@ -78,6 +90,14 @@ impl TextObject {
|
||||
// Character strokes are drawn in text space: widen them by the vertical scale we remove.
|
||||
self.scale_char_strokes(1.0 / sy);
|
||||
self.xf *= Affine::scale_non_uniform(1.0 / sx, 1.0 / sy);
|
||||
// An area's frame and a path type's path are drawn through `xf` too: give them the scale
|
||||
// `xf` loses, so the frame (and so the line breaks) and the path stay where they were.
|
||||
let grow = Affine::scale_non_uniform(sx, sy);
|
||||
match &mut self.kind {
|
||||
TextKind::Area { frame } => frame.transform(grow),
|
||||
TextKind::OnPath { path, .. } => path.transform(grow),
|
||||
TextKind::Point => {}
|
||||
}
|
||||
self.cached_bounds = None;
|
||||
self.cached_baselines.clear();
|
||||
self.cached_ink = None;
|
||||
|
||||
@@ -5,7 +5,9 @@ use vectorcraft_geom::kurbo::ParamCurveArclen;
|
||||
use vectorcraft_geom::{Affine, Anchor, ParamCurve, PathData, Point, Rect, SubPath, Vec2};
|
||||
use vectorcraft_pathops::addons::pathtools::insert_at;
|
||||
|
||||
use crate::util::{catmull_rom, fit_piece, flag, map_nonlinear_within, mean_size, noise, normal_at, num, pieces, seed, seg_cubic, smooth_points};
|
||||
use crate::util::{
|
||||
catmull_rom, fit_piece, flag, map_nonlinear_within, map_smooth_within, mean_size, noise, normal_at, num, pieces, seed, seg_cubic, smooth_points,
|
||||
};
|
||||
|
||||
fn diag(b: Rect) -> f64 {
|
||||
b.width().hypot(b.height()).max(1e-6)
|
||||
@@ -325,8 +327,8 @@ pub fn tweak(path: &PathData, b: Rect, p: &Value) -> PathData {
|
||||
}
|
||||
|
||||
/// Twist: rotation that is strongest at the centre and fades to zero at the bounding circle,
|
||||
/// clockwise on the page for a positive `angle`, making at most `max` anchors
|
||||
/// ([`map_nonlinear_within`]).
|
||||
/// clockwise on the page for a positive `angle`, making at most `max` anchors. Its handles follow
|
||||
/// the rotation's derivative ([`map_smooth_within`]), so the pieces join without kinks (#7069).
|
||||
pub fn twist(path: &PathData, b: Rect, angle: f64, max: usize) -> PathData {
|
||||
let ang = angle.clamp(-3600.0, 3600.0).to_radians();
|
||||
if ang == 0.0 {
|
||||
@@ -343,7 +345,7 @@ pub fn twist(path: &PathData, b: Rect, angle: f64, max: usize) -> PathData {
|
||||
c + Vec2::new(d.x * co - d.y * s, d.x * s + d.y * co)
|
||||
};
|
||||
let piece = (r / 8.0).min(r / (1.0 + ang.abs() * 2.0));
|
||||
map_nonlinear_within(path, piece, max, f)
|
||||
map_smooth_within(path, piece, max, f)
|
||||
}
|
||||
|
||||
const ZIGZAG_ARCLEN_ACCURACY: f64 = 1e-4;
|
||||
|
||||
@@ -94,13 +94,13 @@ pub use revolve::{
|
||||
CLASSIC_REVOLVE, REVOLVE, has_revolve, is_revolve, revolve_art, revolve_art_in, revolve_options, validate_revolve, validate_revolve_in,
|
||||
};
|
||||
pub use solids::{
|
||||
CLASSIC_EXTRUDE, CLASSIC_ROTATE, EXTRUDE, GRAPHICS, GraphicFrame, INFLATE, MAX_GRAPHICS, MappedGraphic, RENDER, RENDER_MODES, ROTATE,
|
||||
ROTATE_SURFACES, ROTATION_PRESETS, SHADING_COLORS, SOLIDS, SolidMesh, THREE_D_TYPES, classic_extrude_options, classic_shading, extrude_options,
|
||||
graphic_bounds, graphic_frame, graphic_symbols, has_solid, inflate_options, is_classic_three_d, is_three_d, mapped_graphics, missing_symbol,
|
||||
names_graphic_symbol, rename_graphic_symbol, rename_graphic_symbol_in, renders_wireframe, solid_art, solid_art_in, takes_graphics,
|
||||
three_d_meshes, three_d_meshes_in, three_d_meshes_of, three_d_meshes_of_in, three_d_params_as, three_d_wireframe_in, validate_solid,
|
||||
validate_solid_in, validate_three_d, validate_three_d_at, validate_three_d_at_in, validate_three_d_in, validate_three_d_params, view_options,
|
||||
with_graphic,
|
||||
CLASSIC_EXTRUDE, CLASSIC_ROTATE, EXTRUDE, GRAPHICS, GraphicFrame, INFLATE, MAX_GRAPHICS, MappedGraphic, MeshGraphics, RENDER, RENDER_MODES,
|
||||
ROTATE, ROTATE_SURFACES, ROTATION_PRESETS, SHADING_COLORS, SOLIDS, SolidMesh, THREE_D_TYPES, classic_extrude_options, classic_shading,
|
||||
extrude_options, graphic_bounds, graphic_frame, graphic_symbols, has_solid, inflate_options, is_classic_three_d, is_three_d, mapped_graphics,
|
||||
mesh_graphics_art, missing_symbol, names_graphic_symbol, rename_graphic_symbol, rename_graphic_symbol_in, renders_wireframe, solid_art,
|
||||
solid_art_in, takes_graphics, three_d_meshes, three_d_meshes_in, three_d_meshes_of, three_d_meshes_of_in, three_d_params_as,
|
||||
three_d_wireframe_in, validate_solid, validate_solid_in, validate_three_d, validate_three_d_at, validate_three_d_at_in, validate_three_d_in,
|
||||
validate_three_d_params, view_options, with_graphic,
|
||||
};
|
||||
pub use solids::{
|
||||
GRAPHIC_MAX_OFFSET, GRAPHIC_SCALE_RANGE, GRAPHICS_NOT_TAKEN, appearance_graphic_symbols, exports_three_d, graphic_frame_at,
|
||||
|
||||
@@ -801,7 +801,7 @@ pub(crate) fn revolve_meshes(n: &Node, total: &mut usize, limit: usize) -> Resul
|
||||
let b = path.bounds().ok_or("Revolve requires a shape with at least two anchors")?;
|
||||
let (paint, opacity, _) = paint_of(item);
|
||||
let mesh = vectorcraft_three_d::revolve_mesh(path, rule, b, fx_options(fx))?;
|
||||
Ok(crate::SolidMesh { mesh, color: crate::solids::mesh_color(&paint, opacity) })
|
||||
Ok(crate::SolidMesh::plain(mesh, crate::solids::mesh_color(&paint, opacity)))
|
||||
};
|
||||
if let Some(index) = n.appearance.effects.iter().position(|e| e.visible && is_revolve(&e.id)) {
|
||||
let before = n.appearance.effects.get(..index).unwrap_or_default();
|
||||
@@ -924,7 +924,7 @@ fn group_meshes(n: &Node, total: &mut usize, limit: usize) -> Result<Vec<crate::
|
||||
let Some(item) = surface_item(&s.items) else { continue };
|
||||
let (paint, opacity, _) = paint_of(item);
|
||||
let mesh = vectorcraft_three_d::revolve_mesh(&s.path, s.rule, b, options)?;
|
||||
crate::solids::keep_mesh(&mut out, total, crate::SolidMesh { mesh, color: crate::solids::mesh_color(&paint, opacity * s.opacity) }, limit)?;
|
||||
crate::solids::keep_mesh(&mut out, total, crate::SolidMesh::plain(mesh, crate::solids::mesh_color(&paint, opacity * s.opacity)), limit)?;
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
@@ -25,8 +25,8 @@ pub(crate) use source::{resolve, resolve_for};
|
||||
|
||||
pub(crate) mod graphics;
|
||||
pub use graphics::{
|
||||
GRAPHICS, GraphicFrame, MAX_GRAPHICS, MappedGraphic, graphic_symbols, mapped_graphics, missing_symbol, names_graphic_symbol,
|
||||
rename_graphic_symbol, rename_graphic_symbol_in, takes_graphics, with_graphic,
|
||||
GRAPHICS, GraphicFrame, MAX_GRAPHICS, MappedGraphic, MeshGraphics, graphic_symbols, mapped_graphics, mesh_graphics_art, missing_symbol,
|
||||
names_graphic_symbol, rename_graphic_symbol, rename_graphic_symbol_in, takes_graphics, with_graphic,
|
||||
};
|
||||
pub use graphics::{
|
||||
MAX_OFFSET as GRAPHIC_MAX_OFFSET, NOT_TAKEN as GRAPHICS_NOT_TAKEN, SCALE_RANGE as GRAPHIC_SCALE_RANGE, appearance_graphic_symbols,
|
||||
@@ -2322,6 +2322,71 @@ pub struct SolidMesh {
|
||||
/// The paint's display color (sRGB, 0..1) and its opacity: a gradient's stops averaged, gray
|
||||
/// for a pattern.
|
||||
pub color: [f32; 4],
|
||||
/// The graphics mapped onto the mesh when it is the part of a solid's planar face that carries
|
||||
/// some ([`split_graphics`]); `None` otherwise.
|
||||
pub graphics: Option<MeshGraphics>,
|
||||
}
|
||||
|
||||
impl SolidMesh {
|
||||
/// A mesh painted `color`, with no graphics.
|
||||
pub fn plain(mesh: Mesh, color: [f32; 4]) -> Self {
|
||||
Self { mesh, color, graphics: None }
|
||||
}
|
||||
}
|
||||
|
||||
/// The parts of `mesh`, a solid that 3D effect `id` with parameters `p` built about `bounds`, painted
|
||||
/// `color` from a fill or stroke at `opacity`: for each planar face that carries graphics (Extrude &
|
||||
/// Bevel's caps, the plane), the triangles on it as a mesh of their own with the art point of each
|
||||
/// corner ([`MeshGraphics`]), then the rest. Revolve's side, whose graphics are not mapped onto its
|
||||
/// mesh, stays plain.
|
||||
fn split_graphics(id: &str, p: &Value, bounds: Rect, mesh: Mesh, (color, opacity): ([f32; 4], f32)) -> Vec<SolidMesh> {
|
||||
let list = graphics::mapped_graphics(p);
|
||||
if list.is_empty() || !takes_graphics(id) || id == crate::REVOLVE {
|
||||
return vec![SolidMesh::plain(mesh, color)];
|
||||
}
|
||||
let view = view_options(p);
|
||||
let mut rest = mesh;
|
||||
let mut out = vec![];
|
||||
for face in PlanarFace::ALL {
|
||||
if !list.iter().any(|g| g.face == face) {
|
||||
continue;
|
||||
}
|
||||
let on_mesh = if id == ROTATE {
|
||||
vectorcraft_three_d::plane_mesh_face(bounds, view)
|
||||
} else {
|
||||
vectorcraft_three_d::extrude_mesh_face(bounds, extrude_options(p), view, face)
|
||||
};
|
||||
let Some(on_mesh) = on_mesh else { continue };
|
||||
let (mut taken, mut left, mut art) = (Mesh::default(), Mesh::default(), vec![]);
|
||||
for t in &rest.triangles {
|
||||
let corner = |i: u32| rest.positions.get(i as usize).copied().zip(rest.normals.get(i as usize).copied());
|
||||
let Some(corners) = t.iter().map(|&i| corner(i)).collect::<Option<Vec<_>>>() else { continue };
|
||||
let points: Option<Vec<Point>> = corners.iter().map(|(m, n)| on_mesh.art_point(*m, *n)).collect();
|
||||
let into = match points {
|
||||
Some(points) => {
|
||||
art.extend(points);
|
||||
&mut taken
|
||||
}
|
||||
None => &mut left,
|
||||
};
|
||||
let base = into.positions.len() as u32;
|
||||
for (m, n) in corners {
|
||||
into.positions.push(m);
|
||||
into.normals.push(n);
|
||||
}
|
||||
into.triangles.push([base, base + 1, base + 2]);
|
||||
}
|
||||
rest = left;
|
||||
if !taken.is_empty() {
|
||||
let graphics = list.iter().filter(|g| g.face == face).cloned().collect();
|
||||
let graphics = MeshGraphics { face, graphics, center: bounds.center(), art, opacity, object: 1.0 };
|
||||
out.push(SolidMesh { mesh: taken, color, graphics: Some(graphics) });
|
||||
}
|
||||
}
|
||||
if !rest.is_empty() {
|
||||
out.insert(0, SolidMesh::plain(rest, color));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The color a mesh of `paint` at `opacity` takes ([`SolidMesh::color`]).
|
||||
@@ -2363,13 +2428,18 @@ fn meshes_for(fx: &Effect, shapes: &[Profile], total: &mut usize, limit: usize)
|
||||
let p = crate::merged_params(&fx.id, &fx.params);
|
||||
let view = view_options(&p);
|
||||
let mut out = vec![];
|
||||
let mut keep = |out: &mut Vec<SolidMesh>, mesh: Mesh, color: [f32; 4]| keep_mesh(out, total, SolidMesh { mesh, color }, limit);
|
||||
// A solid's parts with and without graphics count together against the limit.
|
||||
let mut keep = |out: &mut Vec<SolidMesh>, mesh: Mesh, (paint, opacity): (&Paint, f32), bounds: Rect| {
|
||||
split_graphics(&fx.id, &p, bounds, mesh, (mesh_color(paint, opacity), opacity))
|
||||
.into_iter()
|
||||
.try_for_each(|part| keep_mesh(out, total, part, limit))
|
||||
};
|
||||
if is_plane(&fx.id) {
|
||||
for s in shapes {
|
||||
for item in &s.items {
|
||||
let (paint, opacity, _) = paint_of(item, s.opacity);
|
||||
let (area, rule) = region(&s.path, s.rule, item);
|
||||
keep(&mut out, vectorcraft_three_d::plane_mesh(&area, rule, b, view)?, mesh_color(&paint, opacity))?;
|
||||
keep(&mut out, vectorcraft_three_d::plane_mesh(&area, rule, b, view)?, (&paint, opacity), b)?;
|
||||
}
|
||||
}
|
||||
return Ok(out);
|
||||
@@ -2406,7 +2476,7 @@ fn meshes_for(fx: &Effect, shapes: &[Profile], total: &mut usize, limit: usize)
|
||||
match solid.mesh() {
|
||||
Ok(mesh) => {
|
||||
let (paint, opacity, _) = paint_of(item, *member);
|
||||
keep(&mut out, mesh, mesh_color(&paint, opacity))?;
|
||||
keep(&mut out, mesh, (&paint, opacity), bounds)?;
|
||||
}
|
||||
Err(_) if matches!(item, AppearanceItem::Stroke(_)) => {}
|
||||
Err(e) => return Err(e),
|
||||
@@ -2494,6 +2564,9 @@ fn meshes_within(doc: Option<&Document>, n: &Node, total: &mut usize, limit: usi
|
||||
.filter(|m| !m.mesh.is_empty())
|
||||
.map(|mut m| {
|
||||
m.color[3] *= n.opacity.clamp(0.0, 1.0);
|
||||
if let Some(g) = &mut m.graphics {
|
||||
g.object *= n.opacity.clamp(0.0, 1.0);
|
||||
}
|
||||
m
|
||||
})
|
||||
.collect();
|
||||
|
||||
@@ -519,6 +519,71 @@ pub(super) fn face_art(
|
||||
Some(Node::new(id, NodeKind::Group { children: vec![Arc::new(clip), Arc::new(Node::group(id, children))], clip: true }))
|
||||
}
|
||||
|
||||
/// The graphics on one planar face of a solid's mesh ([`super::SolidMesh`]): those mapped onto
|
||||
/// `face`, placed about `center` (the center of the bounds the solids were built with), and the
|
||||
/// point of the art's plane that each corner of the mesh shows (document coordinates of the art
|
||||
/// before its 3D effect, y down).
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct MeshGraphics {
|
||||
pub face: PlanarFace,
|
||||
pub graphics: Vec<MappedGraphic>,
|
||||
pub center: Point,
|
||||
/// One for each position of the mesh.
|
||||
pub art: Vec<Point>,
|
||||
/// The opacity of the fill or stroke the face is painted with, which the graphics take too, as
|
||||
/// the canvas draws them; neither a gradient's stops nor the object's own opacity is in it.
|
||||
pub opacity: f32,
|
||||
/// The opacity of the object the face belongs to, which applies to the face and its graphics
|
||||
/// together.
|
||||
pub object: f32,
|
||||
}
|
||||
|
||||
impl MeshGraphics {
|
||||
/// The bounds of the art points of the mesh's corners; `None` without corners.
|
||||
pub fn art_bounds(&self) -> Option<Rect> {
|
||||
let first = *self.art.first()?;
|
||||
Some(self.art.iter().fold(Rect::from_points(first, first), |r, p| r.union_pt(*p)))
|
||||
}
|
||||
}
|
||||
|
||||
/// The art `graphics` draws on its face, flat in the art's plane, unshaded and unclipped: each
|
||||
/// graphic's fills and stroke outlines at its place ([`MappedGraphic`]), back to front, as one
|
||||
/// group of objects with id `id`. A graphic whose symbol `doc` does not have, or whose art is past
|
||||
/// the limits of [`pieces_of`], is left out, as the canvas leaves it out. `Ok(None)` when nothing
|
||||
/// is drawn; an error when the graphics' art draws more than [`MAX_ELEMENTS`] path elements
|
||||
/// together.
|
||||
pub fn mesh_graphics_art(doc: &Document, id: NodeId, graphics: &MeshGraphics) -> Result<Option<Node>, String> {
|
||||
let mut children = vec![];
|
||||
let mut elements = 0usize;
|
||||
for g in graphics.graphics.iter().filter(|g| g.face == graphics.face) {
|
||||
let Some(symbol) = doc.symbols.iter().find(|s| s.name == g.symbol) else { continue };
|
||||
let Ok(pieces) = pieces_of(doc, symbol) else { continue };
|
||||
let Some(bounds) = pieces.iter().filter_map(|p| p.path.bounds()).reduce(|a, b| a.union(b)) else { continue };
|
||||
let place = g.placement(bounds, graphics.center);
|
||||
for piece in pieces {
|
||||
elements = elements.saturating_add(drawn_elements(&piece.path, 1));
|
||||
if elements > MAX_ELEMENTS {
|
||||
return Err("The graphics are too complex: simplify the symbols' art".into());
|
||||
}
|
||||
let mut paint = piece.paint;
|
||||
if let Paint::Pattern { xf, .. } = &mut paint {
|
||||
*xf = place * *xf;
|
||||
}
|
||||
let mut fill = FillLayer::new(paint);
|
||||
fill.opacity = piece.opacity;
|
||||
fill.blend = piece.blend;
|
||||
let mut appearance = Appearance { items: vec![AppearanceItem::Fill(fill)], ..Default::default() };
|
||||
appearance.transform_gradients(place);
|
||||
let mut node = Node::path(id, piece.path.transformed(place), appearance);
|
||||
if let NodeKind::Path { rule, .. } = &mut node.kind {
|
||||
*rule = piece.rule;
|
||||
}
|
||||
children.push(Arc::new(node));
|
||||
}
|
||||
}
|
||||
Ok((!children.is_empty()).then(|| Node::group(id, children)))
|
||||
}
|
||||
|
||||
/// One area of a graphic placed on Revolve's unrolled side surface, cut into straight pieces.
|
||||
struct Unrolled {
|
||||
polygons: Vec<Vec<Point>>,
|
||||
|
||||
@@ -86,6 +86,48 @@ fn a_graphic_is_drawn_on_the_front_cap_at_its_offset_size_and_turn() {
|
||||
assert!((b.width() - 10.0 * 2f64.sqrt()).abs() < 1e-6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_mesh_carries_its_caps_graphics_flat_in_the_arts_plane() {
|
||||
let d = document();
|
||||
let graphics =
|
||||
json!([{"symbol": "Mark", "x": 20.0, "y": -10.0, "scale": 200.0}, {"symbol": "Mark", "face": "back", "x": 20.0, "y": -10.0, "scale": 200.0}]);
|
||||
// Turned, so the caps' corners in the mesh are not the art's.
|
||||
let n = object(EXTRUDE, json!({"rotationX": -20.0, "rotationY": 35.0, "rotationZ": 10.0, "graphics": graphics}));
|
||||
let parts = super::super::three_d_meshes_in(Some(&d), &n).unwrap();
|
||||
// The walls first, then the front cap and the back cap, each two triangles.
|
||||
assert_eq!(
|
||||
parts.iter().map(|p| p.graphics.as_ref().map(|g| g.face)).collect::<Vec<_>>(),
|
||||
[None, Some(PlanarFace::Front), Some(PlanarFace::Back)]
|
||||
);
|
||||
let total: usize = parts.iter().map(|p| p.mesh.triangles.len()).sum();
|
||||
let plain = super::super::three_d_meshes_in(Some(&d), &object(EXTRUDE, json!({"rotationX": -20.0, "rotationY": 35.0, "rotationZ": 10.0})));
|
||||
assert_eq!(total, plain.as_ref().map_or(0, |p| p.iter().map(|p| p.mesh.triangles.len()).sum()), "no triangle is lost or doubled");
|
||||
assert!(plain.unwrap().iter().all(|p| p.graphics.is_none()));
|
||||
// The art points of each cap's corners are the art's own square; the graphic is drawn flat at
|
||||
// its place, mirrored on the back so it reads from behind.
|
||||
for (part, drawn) in parts[1..].iter().zip([Rect::new(60.0, 30.0, 80.0, 50.0), Rect::new(20.0, 30.0, 40.0, 50.0)]) {
|
||||
let Some(g) = &part.graphics else { panic!("no graphics") };
|
||||
assert_eq!(g.art.len(), part.mesh.positions.len());
|
||||
assert!(close(g.art_bounds().unwrap(), Rect::new(0.0, 0.0, 100.0, 100.0)), "{:?}", g.art_bounds());
|
||||
assert_eq!(g.graphics.len(), 1);
|
||||
let art = mesh_graphics_art(&d, NodeId(9), g).unwrap().unwrap();
|
||||
let paths: Vec<(PathData, Paint)> = art
|
||||
.children()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(|c| Some((c.path_data()?.clone(), c.appearance.items.first()?.paint().clone())))
|
||||
.collect();
|
||||
assert!(close(bounds_of(&paths), drawn), "{:?}: {:?}", g.face, bounds_of(&paths));
|
||||
assert_eq!(paths[0].1, Paint::solid(red()), "unshaded");
|
||||
}
|
||||
// A plane is all one face; a graphic whose symbol is gone draws nothing.
|
||||
let n = object(ROTATE, json!({"rotationY": 35.0, "graphics": [{"symbol": "Gone"}]}));
|
||||
let parts = super::super::three_d_meshes_in(Some(&d), &n).unwrap();
|
||||
assert_eq!(parts.len(), 1);
|
||||
let Some(g) = &parts[0].graphics else { panic!("no graphics") };
|
||||
assert_eq!(mesh_graphics_art(&d, NodeId(9), g), Ok(None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn without_the_document_or_its_symbol_nothing_is_drawn() {
|
||||
let n = object(EXTRUDE, json!({"graphics": [{"symbol": "Mark"}]}));
|
||||
@@ -563,6 +605,15 @@ fn art_nested_too_deep_is_refused_and_not_drawn() {
|
||||
// A loaded file draws its other graphics.
|
||||
let both = object(EXTRUDE, json!({"graphics": [{"symbol": "Deep"}, {"symbol": "Mark"}]}));
|
||||
assert_eq!(graphics_in(&solid_art_in(Some(&d), &both).unwrap()).len(), 1);
|
||||
// A mesh's graphics leave it out as well and draw the others.
|
||||
let parts = super::super::three_d_meshes_in(Some(&d), &both).unwrap();
|
||||
let Some(g) = parts.iter().find_map(|p| p.graphics.as_ref()) else { panic!("no graphics") };
|
||||
let art = mesh_graphics_art(&d, NodeId(9), g).unwrap().unwrap();
|
||||
assert_eq!(art.children().map_or(0, |c| c.len()), 1);
|
||||
let deep = object(EXTRUDE, json!({"graphics": [{"symbol": "Deep"}]}));
|
||||
let parts = super::super::three_d_meshes_in(Some(&d), &deep).unwrap();
|
||||
let Some(g) = parts.iter().find_map(|p| p.graphics.as_ref()) else { panic!("no graphics") };
|
||||
assert_eq!(mesh_graphics_art(&d, NodeId(9), g), Ok(None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -238,7 +238,7 @@ fn meshes_built_apart(fx: &Effect, shapes: &[Profile], total: &mut usize, limit:
|
||||
match mesh {
|
||||
Ok(mesh) => {
|
||||
let (paint, opacity, _) = paint_of(item, *opacity);
|
||||
keep_mesh(&mut out, total, SolidMesh { mesh, color: mesh_color(&paint, opacity) }, limit)?;
|
||||
keep_mesh(&mut out, total, SolidMesh::plain(mesh, mesh_color(&paint, opacity)), limit)?;
|
||||
}
|
||||
Err(_) if matches!(item, AppearanceItem::Stroke(_)) => {}
|
||||
Err(e) => return Err(e),
|
||||
|
||||
@@ -1687,6 +1687,27 @@ fn twist_turns_clockwise_for_positive_angles() {
|
||||
assert!(turned(-45.0).y < 49.5, "{:?}", turned(-45.0));
|
||||
}
|
||||
|
||||
/// Twist turns a line into a smooth spiral: the points it adds join their pieces without a kink,
|
||||
/// however far it turns (#7069).
|
||||
#[test]
|
||||
fn twist_joins_its_pieces_smoothly() {
|
||||
let line = PathData::single(SubPath::polyline(&[Point::new(40.0, 30.0), Point::new(60.0, 30.0)], false));
|
||||
let bounds = Rect::new(40.0, 30.0, 60.0, 30.0);
|
||||
for angle in [90.0, 400.0, -720.0] {
|
||||
let out = apply_geometry(&[fx("distort.twist", json!({"angle": angle}))], &line, bounds);
|
||||
let anchors = &out.subpaths[0].anchors;
|
||||
assert!(anchors.len() > 8, "{angle}°: {} anchors", anchors.len());
|
||||
for a in anchors.iter().skip(1).take(anchors.len() - 2) {
|
||||
let (into, out) = (a.p - a.h_in, a.h_out - a.p);
|
||||
if into.hypot() < 1e-9 || out.hypot() < 1e-9 {
|
||||
continue;
|
||||
}
|
||||
let kink = (into.x * out.y - into.y * out.x).atan2(into.dot(out)).to_degrees().abs();
|
||||
assert!(kink < 1.0, "{angle}°: a kink of {kink:.1}° at {:?}", a.p);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn twist_fixes_the_outer_circle_and_rotates_inside() {
|
||||
let out = run("distort.twist", json!({"angle": 0}), &square());
|
||||
|
||||
@@ -71,7 +71,7 @@ pub fn seg_cubic(sp: &SubPath, i: usize) -> CubicBez {
|
||||
|
||||
/// Non-linear path mapping (shared with live envelopes in `vectorcraft-doc`), and the split of
|
||||
/// segments into pieces within an anchor budget.
|
||||
pub use vectorcraft_doc::live::{fit_piece, map_nonlinear_within, pieces};
|
||||
pub use vectorcraft_doc::live::{fit_piece, map_nonlinear_within, map_smooth_within, pieces};
|
||||
|
||||
/// About how many lines the renderer flattens `path` into at 1 px/pt: one for a straight
|
||||
/// segment, and for a curve the count Wang's formula gives at vello's tolerance of 0.25 px,
|
||||
|
||||
@@ -47,6 +47,7 @@ vectorcraft-js = { workspace = true }
|
||||
vectorcraft-apischema = { workspace = true }
|
||||
image = { workspace = true }
|
||||
craft-image-codecs = { workspace = true }
|
||||
tiff = { workspace = true }
|
||||
jxl-oxide = { workspace = true }
|
||||
jxl-color = { workspace = true }
|
||||
jxl-grid = { workspace = true }
|
||||
@@ -88,7 +89,6 @@ craft-jxl = { workspace = true }
|
||||
# vectorcraft-doc's Group 3 TIFF reader before craft-stream-codecs, the reference
|
||||
# tests/group3_reference.rs compares it with.
|
||||
hayro-ccitt = { workspace = true }
|
||||
tiff = { workspace = true }
|
||||
craft-stream-codecs = { workspace = true }
|
||||
vectorcraft-affinity = { workspace = true, features = ["synth"] }
|
||||
crc32fast = { workspace = true }
|
||||
@@ -98,6 +98,8 @@ proptest = { workspace = true }
|
||||
vectorcraft-text = { workspace = true, features = ["test-fonts"] }
|
||||
# How many times an open reads a PDF.
|
||||
vectorcraft-pdf = { workspace = true, features = ["read-count"] }
|
||||
# How many times the symbol list is read to find symbols by name.
|
||||
vectorcraft-doc = { workspace = true, features = ["symbol-read-count"] }
|
||||
wat = { workspace = true }
|
||||
# Zstandard streams for the Illustrator editing data fuzz tests.
|
||||
ruzstd = { workspace = true }
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
//! `cargo run --release -p vectorcraft-engine --example selection_bench` prints the time of the
|
||||
//! selection steps behind `select.toggle`, `select.add` and `select.inverse` on selections of 2,000,
|
||||
//! 20,000 and 50,000 objects, done one id at a time (`old`) and in one pass (`new`), side by side in
|
||||
//! one process. Each step checks that both give the same selection before it is timed.
|
||||
//! `ITERS` sets the runs per step (default 7); each row is the median wall time in ms.
|
||||
// Example (dev tool): unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness).
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::hint::black_box;
|
||||
use std::time::Instant;
|
||||
|
||||
use vectorcraft_doc::{NodeId, Selection};
|
||||
|
||||
fn iters() -> usize {
|
||||
std::env::var("ITERS").ok().and_then(|v| v.parse().ok()).unwrap_or(7).max(1)
|
||||
}
|
||||
|
||||
fn median(mut ms: Vec<f64>) -> f64 {
|
||||
ms.sort_by(f64::total_cmp);
|
||||
ms[ms.len() / 2]
|
||||
}
|
||||
|
||||
/// The median time of `old` and of `new` on clones of `start`, run in turn.
|
||||
fn time(start: &Selection, old: impl Fn(&mut Selection), new: impl Fn(&mut Selection)) -> (f64, f64) {
|
||||
let (mut a, mut b) = (start.clone(), start.clone());
|
||||
old(&mut a);
|
||||
new(&mut b);
|
||||
assert_eq!(a, b, "both ways give the same selection");
|
||||
let run = |f: &dyn Fn(&mut Selection)| {
|
||||
let mut s = start.clone();
|
||||
let t = Instant::now();
|
||||
f(&mut s);
|
||||
let ms = t.elapsed().as_secs_f64() * 1000.0;
|
||||
black_box(s);
|
||||
ms
|
||||
};
|
||||
let (mut olds, mut news) = (Vec::new(), Vec::new());
|
||||
for _ in 0..iters() {
|
||||
olds.push(run(&old));
|
||||
news.push(run(&new));
|
||||
}
|
||||
(median(olds), median(news))
|
||||
}
|
||||
|
||||
/// `select.add` before the change: [`Selection::add`] for each id.
|
||||
fn old_add(s: &mut Selection, ids: &[NodeId]) {
|
||||
for id in ids {
|
||||
s.add(*id);
|
||||
}
|
||||
}
|
||||
|
||||
/// `select.toggle` before the change: [`Selection::toggle`] for each id.
|
||||
fn old_toggle(s: &mut Selection, ids: &[NodeId]) {
|
||||
for id in ids {
|
||||
s.toggle(*id);
|
||||
}
|
||||
}
|
||||
|
||||
/// `select.inverse` before the change: the selectable ids not found by [`Selection::contains`].
|
||||
fn old_inverse(s: &mut Selection, selectable: &[NodeId]) {
|
||||
let ids: Vec<NodeId> = selectable.iter().copied().filter(|id| !s.contains(*id)).collect();
|
||||
s.set(ids);
|
||||
}
|
||||
|
||||
/// `select.inverse` after the change: the selectable ids not in a set of the selected ones.
|
||||
fn new_inverse(s: &mut Selection, selectable: &[NodeId]) {
|
||||
let selected: HashSet<NodeId> = s.objects.iter().copied().collect();
|
||||
let ids: Vec<NodeId> = selectable.iter().copied().filter(|id| !selected.contains(id)).collect();
|
||||
s.set(ids);
|
||||
}
|
||||
|
||||
fn row(name: &str, (old, new): (f64, f64)) {
|
||||
println!(" {name:<44} {old:>12.3} ms {new:>12.3} ms {:>9.1}x", old / new.max(1e-9));
|
||||
}
|
||||
|
||||
fn main() {
|
||||
println!(" {:<44} {:>15} {:>15} {:>10}", "step", "old", "new", "speedup");
|
||||
for n in [2_000u64, 20_000, 50_000] {
|
||||
println!("{n} objects");
|
||||
let all: Vec<NodeId> = (1..=n).map(NodeId).collect();
|
||||
let none = Selection::default();
|
||||
let mut every = Selection::default();
|
||||
every.set(all.iter().copied());
|
||||
let mut half = Selection::default();
|
||||
half.set(all.iter().copied().step_by(2));
|
||||
let interleaved: Vec<NodeId> = all.iter().copied().skip(n as usize / 4).chain(all.iter().copied().take(n as usize / 4)).collect();
|
||||
let half_new: Vec<NodeId> = all.iter().copied().skip(n as usize / 2).collect();
|
||||
row("toggle every object off", time(&every, |s| old_toggle(s, &all), |s| s.toggle_all(all.iter().copied())));
|
||||
row("toggle every object on", time(&none, |s| old_toggle(s, &all), |s| s.toggle_all(all.iter().copied())));
|
||||
row("toggle every object, half selected", time(&half, |s| old_toggle(s, &interleaved), |s| s.toggle_all(interleaved.iter().copied())));
|
||||
row("add half the objects, half selected", time(&half, |s| old_add(s, &half_new), |s| s.add_all(half_new.iter().copied())));
|
||||
row("inverse, half selected", time(&half, |s| old_inverse(s, &all), |s| new_inverse(s, &all)));
|
||||
}
|
||||
}
|
||||
@@ -147,7 +147,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Add Points at Crossings",
|
||||
["Object", "Plug-ins", "Path Precision Tools"],
|
||||
None,
|
||||
"{cut?: bool (false: add anchors where the paths cross; true: also cut them there), selfCrossings?: bool (false: where a path crosses itself too, a curved segment that loops over itself included), ids?: [id…] (default: the selection)} where the paths under the objects cross one another, as one undo step; at most 10000 segments → {ids, crossings (anchors placed)}",
|
||||
"{cut?: bool (false: add anchors where the paths cross; true: also cut them there), selfCrossings?: bool (false: where a path crosses itself too, a curved segment that loops over itself included), ids?: [id…] (default: the selection)} where the paths under the objects cross one another, an open end that lies within 0.001 pt of another path counting as crossing it there, as one undo step; at most 10000 segments → {ids, crossings (anchors placed)}",
|
||||
has_selection,
|
||||
crossings
|
||||
),
|
||||
|
||||
@@ -35,7 +35,7 @@ pub(super) fn specs() -> Vec<CommandSpec> {
|
||||
"Trim at Crossings",
|
||||
[],
|
||||
None,
|
||||
"{at: [x, y], tolerance?: pt 0..100 (3; how near `at` a path counts as under it)} or {rect: [x, y, width, height]} or {points: [[x, y]…] (2 to 100000 points)} remove stretches of paths, a stretch running between two neighboring places where the path is crossed by another path or by itself, or from such a place to an open end: `at` removes the stretch of the nearest path at that point, `rect` every stretch the rectangle touches, `points` every stretch the line through the points crosses. Give exactly one of the three. Every path that can be edited takes part, selected or not, compound path members included; hidden and locked paths, guides and clipping paths (compound ones' members included) are neither trimmed nor counted as crossing; in isolation mode only paths inside the isolated object are trimmed. A path that ends on another marks a place on the other; paths that lie along each other don't cross. A closed path that loses a stretch becomes open, an open path that loses a middle stretch becomes two paths with its appearance in its place in the stacking order, and a path nothing crosses is removed whole; a live shape becomes a plain path. One undo step, none when nothing is removed → {ids (the paths left of those trimmed), removed (stretches)}",
|
||||
"{at: [x, y], tolerance?: pt 0..100 (3; how near `at` a path counts as under it)} or {rect: [x, y, width, height]} or {points: [[x, y]…] (2 to 100000 points)} remove stretches of paths, a stretch running between two neighboring places where the path is crossed by another path or by itself, or from such a place to an open end: `at` removes the stretch of the nearest path at that point, `rect` every stretch the rectangle touches, `points` every stretch the line through the points crosses. Give exactly one of the three. Every path that can be edited takes part, selected or not, compound path members included; hidden and locked paths, guides and clipping paths (compound ones' members included) are neither trimmed nor counted as crossing; in isolation mode only paths inside the isolated object are trimmed. A path that ends on another, or within 0.001 pt of it, marks a place on the other; paths that lie along each other don't cross. A closed path that loses a stretch becomes open, an open path that loses a middle stretch becomes two paths with its appearance in its place in the stacking order, and a path nothing crosses is removed whole; a live shape becomes a plain path. One undo step, none when nothing is removed → {ids (the paths left of those trimmed), removed (stretches)}",
|
||||
has_doc,
|
||||
trim
|
||||
)]
|
||||
|
||||
@@ -782,3 +782,45 @@ fn bad_params_are_refused_and_change_nothing() {
|
||||
assert_eq!(steps(&s), n);
|
||||
assert!(*s.doc().unwrap().doc == *before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_line_ending_on_a_curve_that_was_cut_still_divides_it_there() {
|
||||
// An open egg-shaped curve, lines across it whose stubs on the left are trimmed away, so each
|
||||
// line ends on the curve, and the curve's bottom trimmed off below the last line, which cuts
|
||||
// its segments there. A click on the curve between the last two lines removes only that
|
||||
// stretch: the lines' ends on it still divide it, however the curve was cut. Twenty placements,
|
||||
// as how near a cut end lies to the curve depends on the coordinates.
|
||||
for shift in 0..20 {
|
||||
let dx = shift as f64 * 7.31;
|
||||
let mut s = session();
|
||||
let egg = json!({"anchors": [
|
||||
{"x": 160.0 + dx, "y": 40.0, "out": [110.0 + dx, 80.0]},
|
||||
{"x": 92.3 + dx, "y": 190.7, "in": [88.0 + dx, 140.0], "out": [97.0 + dx, 240.0]},
|
||||
{"x": 170.0 + dx, "y": 268.0, "in": [130.0 + dx, 265.0], "out": [210.0 + dx, 271.0]},
|
||||
{"x": 236.4 + dx, "y": 170.2, "in": [238.0 + dx, 230.0], "out": [233.0 + dx, 110.0]},
|
||||
{"x": 150.0 + dx, "y": 20.0, "in": [200.0 + dx, 40.0]}
|
||||
], "closed": false});
|
||||
let egg = NodeId(s.execute("path.create", &egg).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let ys: Vec<f64> = (0..8).map(|k| 70.0 + k as f64 * 23.17 + shift as f64 * 0.37).collect();
|
||||
let lines: Vec<NodeId> = ys.iter().map(|y| line(&mut s, &[(40.0 + dx, *y), (300.0 + dx, *y)], false)).collect();
|
||||
for y in &ys {
|
||||
assert_eq!(s.execute(TRIM, &json!({"at": [50.0 + dx, y], "tolerance": 0.5})).unwrap()["removed"], json!(1));
|
||||
}
|
||||
assert_eq!(s.execute(TRIM, &json!({"at": [170.0 + dx, 268.0], "tolerance": 0.5})).unwrap()["removed"], json!(1));
|
||||
let start = |id: NodeId| path(&s, id).subpaths[0].anchors[0].p;
|
||||
let ends: Vec<Point> = lines.iter().map(|id| start(*id)).collect();
|
||||
// Off every path but the lines: the curve's pieces.
|
||||
let off_curve = |s: &Session, p: Point| {
|
||||
stack(s).into_iter().filter(|id| !lines.contains(id)).filter_map(|id| path(s, id).nearest(p)).map(|n| n.4).fold(f64::INFINITY, f64::min)
|
||||
};
|
||||
let (a, b) = (ends[6], ends[7]);
|
||||
let click = path(&s, egg).nearest(a.midpoint(b)).unwrap().3;
|
||||
assert!(off_curve(&s, a) < 1e-3 && off_curve(&s, click) < 1e-3);
|
||||
assert_eq!(s.execute(TRIM, &json!({"at": [click.x, click.y], "tolerance": 0.5})).unwrap()["removed"], json!(1));
|
||||
assert!(off_curve(&s, click) > 0.5, "{shift}: the stretch clicked is left");
|
||||
for (k, e) in ends.iter().enumerate().take(7) {
|
||||
assert!(off_curve(&s, *e) < 1e-3, "{shift}: the curve no longer reaches line {k}'s end");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,8 +10,8 @@ use vectorcraft_doc::{ExportAsset, NodeId};
|
||||
|
||||
use super::edit::{refuse_symbol_part, roots_of, selected_roots};
|
||||
use super::fileio::{
|
||||
DEFAULT_FORMAT_3D, FORMATS_3D, SCREEN_SETTINGS_KEYS, check_screen_settings, create_dir, export_crop, export_screens, mesh_file_names, mesh_files,
|
||||
safe_file_name, store_screen_settings, with_screen_export_preset, write_file,
|
||||
DEFAULT_FORMAT_3D, FORMATS_3D, SCREEN_SETTINGS_KEYS, TEXTURE_SIZE, TEXTURE_SIZES, check_screen_settings, create_dir, export_crop, export_screens,
|
||||
image_maps, mesh_file_names, mesh_files, safe_file_name, store_screen_settings, textures, with_screen_export_preset, write_file,
|
||||
};
|
||||
use super::{CommandSpec, EngineError, Result, Session, bad, bool_or, checked_ids_param, cmd, has_doc, ok, str_param, switch_or, text_param};
|
||||
|
||||
@@ -80,7 +80,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Export 3D Assets",
|
||||
[],
|
||||
None,
|
||||
"{assets?: [asset id…] (default every 3D asset), folder?, zip?} each 3D asset's object as a mesh file in its format (assets.set3DFormat), named after the asset: USDA or USDZ, glTF 2.0 (one .gltf, its buffer embedded) or OBJ with its .mtl (whitespace and # in an OBJ's name become _). Every solid of the object (the fill's, each stroke's, a group's members') is a mesh with a material in the color it is painted; faces turned away from the viewer are included, at the object's 3D rotation, y up, about the point it turns about, in points (glTF: meters). Files that would share a name get -2, -3…; an object with a hole that crosses its face's outline or another hole, or with more than 2,000,000 triangles, is refused → {files: [path…]} (no folder: {files: [{name, dataBase64}]}, or with zip one zip as {name, dataBase64, files})",
|
||||
"{assets?: [asset id…] (default every 3D asset), folder?, zip?, textureSize?: 128…4096 (default 1024: the pixels along the longer side of each face's texture)} each 3D asset's object as a mesh file in its format (assets.set3DFormat), named after the asset: USDA or USDZ, glTF 2.0 (one .gltf, its buffer embedded) or OBJ with its .mtl (whitespace and # in an OBJ's name become _). Every solid of the object (the fill's, each stroke's, a group's members') is a mesh with a material in the color it is painted; faces turned away from the viewer are included, at the object's 3D rotation, y up, about the point it turns about, in points (glTF: meters). The graphics mapped onto a plane or onto Extrude & Bevel's front or back cap (threeD.mapGraphic) are a PNG texture of that face: its color with the graphics drawn over it, flat and unlit, on a mesh of the face's own with texture coordinates; glTF embeds it, USDZ stores it after the layer, and OBJ and USDA write it beside them as <name>-texture-1.png… (whitespace, # and @ become _); a face that is not opaque keeps its opacity in the texture's alpha, and an OBJ also gets <name>-texture-1-opacity.png…, the alpha as gray levels for its map_d. Graphics on Revolve's side are not exported. Files that would share a name get -2, -3…; an object with a hole that crosses its face's outline or another hole, or with more than 2,000,000 triangles, or textures of more than 67,108,864 pixels in one export, is refused → {files: [path…]} (no folder: {files: [{name, dataBase64}]}, or with zip one zip as {name, dataBase64, files})",
|
||||
has_doc,
|
||||
export_3d
|
||||
),
|
||||
@@ -299,6 +299,8 @@ fn export_3d(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let folder = text_param(p, "folder", C)?.filter(|f| !f.is_empty());
|
||||
let zip = switch_or(p, "zip", false, C)?;
|
||||
let size = texture_size_param(p, C)?;
|
||||
let mut pixels = 0u64;
|
||||
// Every file's name, compared without case: a later file that would take one gets -2, -3…
|
||||
let mut taken: HashSet<String> = HashSet::new();
|
||||
let mut files: Vec<(String, Vec<u8>)> = vec![];
|
||||
@@ -311,18 +313,20 @@ fn export_3d(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let what = &a.name;
|
||||
let parts =
|
||||
vectorcraft_render::effects::three_d_meshes_of_in(Some(d), nodes).map_err(|e| bad(C, format!("{what} can't be exported in 3D: {e}")))?;
|
||||
let pictures = textures(d, &parts, size, &mut pixels).map_err(|e| bad(C, format!("{what} can't be exported in 3D: {e}")))?;
|
||||
let images = image_maps(&pictures);
|
||||
let base = Some(safe_file_name(&a.name)).filter(|b| !b.is_empty()).unwrap_or_else(|| "Asset".into());
|
||||
let mut stem = base.clone();
|
||||
let mut k = 1;
|
||||
loop {
|
||||
let names = mesh_file_names(&stem, format).map_err(|e| bad(C, e))?;
|
||||
let names = mesh_file_names(&stem, format, &images).map_err(|e| bad(C, e))?;
|
||||
if names.iter().all(|n| !taken.contains(&n.to_lowercase())) {
|
||||
break;
|
||||
}
|
||||
k += 1;
|
||||
stem = format!("{base}-{k}");
|
||||
}
|
||||
let made = mesh_files(&stem, format, &parts).map_err(|e| bad(C, e))?;
|
||||
let made = mesh_files(&stem, format, &parts, &pictures).map_err(|e| bad(C, e))?;
|
||||
taken.extend(made.iter().map(|(n, _)| n.to_lowercase()));
|
||||
files.extend(made);
|
||||
}
|
||||
@@ -360,6 +364,21 @@ fn export_3d(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Param `textureSize` of command `cmd`: the pixels along the longer side of each face's texture,
|
||||
/// [`TEXTURE_SIZE`] when it is not given.
|
||||
fn texture_size_param(p: &Value, cmd: &str) -> Result<u32> {
|
||||
let key = "textureSize";
|
||||
let (lo, hi) = TEXTURE_SIZES;
|
||||
match p.get(key) {
|
||||
None | Some(Value::Null) => Ok(TEXTURE_SIZE),
|
||||
Some(v) => v
|
||||
.as_u64()
|
||||
.and_then(|n| u32::try_from(n).ok())
|
||||
.filter(|n| (lo..=hi).contains(n))
|
||||
.ok_or_else(|| bad(cmd, format!("`{key}` must be a whole number of pixels from {lo} to {hi}"))),
|
||||
}
|
||||
}
|
||||
|
||||
/// The asset ids of param `key`.
|
||||
fn asset_ids(p: &Value, key: &str, cmd: &str) -> Result<Vec<u64>> {
|
||||
let ids = p.get(key).and_then(Value::as_array).ok_or_else(|| bad(cmd, format!("`{key}` must be an array of asset ids (see assets.list)")))?;
|
||||
|
||||
@@ -38,6 +38,7 @@ mod shape_builder;
|
||||
mod trace;
|
||||
|
||||
pub use live_paint::live_paint_gaps;
|
||||
pub(crate) use live_paint::{isolated_live_paint, merge_drawn_in_isolation};
|
||||
use live_paint::{lp_expand, lp_fill, lp_gap_options, lp_info, lp_make, lp_merge, lp_release, lp_stroke_edge};
|
||||
use shape_builder::{sb_merge, sb_regions};
|
||||
pub(crate) use trace::TracePresetChanges;
|
||||
@@ -144,7 +145,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Make",
|
||||
["Object", "Image Trace"],
|
||||
None,
|
||||
"{id?: image or Image Trace group (default: selection), preset?: name (imageTrace.presets), savedPreset?: {settings} (a saved preset's settings, which the journal records so a replay traces with them after the preset is changed, renamed or deleted; used in place of the saved preset `preset` names), enhanced?: false (the preset's enhanced version: with Auto Grouping, and with Shapes in all but High Fidelity Photo; Flat Logo has none and is traced as it is), params?: {mode: \"blackAndWhite\"|\"grayscale\"|\"color\"|\"logo\", threshold: 0-255, palette: \"limited\"|\"fullTone\"|\"automatic\"|\"documentLibrary\" (color mode; limited: the `colors` best colours, fullTone: as many as the tones need, more with colorDetail, automatic: flat art with its own colours, else fullTone, documentLibrary: at most `colors` of the library's colours, as they are), colors: 2-256, colorDetail: 0-100 (fullTone, automatic), library: \"document\" (the document's swatches) or a swatch library id or name (swatch.library.list; documentLibrary), colorGroup?: name (color mode, documentLibrary with library \"document\": the colors of that document color group instead of every swatch; \"\" is every swatch), paths: 0-100, corners: 0-100, noise: px (an area smaller than this joins the color it shares the longest border with; when that color is far from its own and the area is 2 px or more, or a single pixel whose longest border is not tied between colors, it joins the neighboring color nearest its pixels among those sharing at least a tenth of that border), method: \"abutting\"|\"overlapping\" (abutting with fills, not mode logo: a \"Seam Fills\" clip group under the paths holds strokes along the edges two filled paths share, 1.5 image pixels wide (VectorCraft's own width), in the color of the lower path (on an image stretched more one way than another, each stroke's outline in image pixels as a filled path), clipped to the image's box within the traced paths' box; paths that became live shapes get none; the paths are not changed), ignoreWhite (leave out white areas), ignoreColor?: \"#rrggbb\" (with ignoreWhite: the colour left out instead of white), ignoreBackground: false (with ignoreWhite: only the areas of the ignored color that reach the image's edge are left out), keepColors?: [\"#rrggbb\"…] (not mode logo: only the palette colors within about 30 levels of a listed color are traced; empty: every color), snapCurvesToLines, shapes: false (filled outlines that are a circle, an ellipse, a rectangle or a regular polygon come out as that live shape), autoGrouping: false (each path that has others inside it is grouped with them), gradients: false (grayscale and color: an area whose colour changes evenly along one direction is one path with a linear gradient fill), fills: true, strokes: false (Create: lines up to strokeWidth wide become stroked centre lines; without fills, wider areas become stroked outlines), strokeWidth: px (10), logoColors?: [\"#rrggbb\"…] (mode logo: flat-colour logos only; colours found automatically or named here, at most ten; white is its own color, and a named color with every channel 245 or more is taken as that white, except with logoColors named, logoWhite false and no ignoreWhite; noise = areas under noise/10 px ignored; edges to a fraction of a pixel, sharp corners restored, lines and circles snapped; enclosed transparent areas are painted white while white is its own color, and stay holes with ignoreWhite or without a white of its own; fills/strokes are ignored; gradients and photos are refused, judged by the image's own colors also when logoColors are named), logoWhite: true (mode logo with logoColors named; false traces the named colors only: white areas take the nearest of them, a named white is kept and enclosed transparent areas stay holes; with ignoreWhite, white areas are left out either way)}, view?: as imageTrace.setView (default: the traced object's own, else tracingResult), ids?: [id…] (instead of id)} → {id, paths, anchors, colors, warnings: [text…] (the image is over 1500 px on a side, so it traces more slowly; or it was traced scaled down; Flat Logo names only the size it traced a larger image at; or a keepColors color matches none the trace found, or nothing was traced)}",
|
||||
"{id?: image or Image Trace group (default: selection), preset?: name (imageTrace.presets), savedPreset?: {settings} (a saved preset's settings, which the journal records so a replay traces with them after the preset is changed, renamed or deleted; used in place of the saved preset `preset` names), enhanced?: false (the preset's enhanced version: with Auto Grouping, and with Shapes in all but High Fidelity Photo; Flat Logo has none and is traced as it is), params?: {mode: \"blackAndWhite\"|\"grayscale\"|\"color\"|\"logo\", threshold: 0-255, palette: \"limited\"|\"fullTone\"|\"automatic\"|\"documentLibrary\" (color mode; limited: the `colors` best colours, fullTone: as many as the tones need, more with colorDetail, split into at least colorDetail colors where the image has that many before colors that look alike merge (less than 5 apart in Oklab × 100 and thoroughly mixed, or less than 1.5 and mixed in patches), automatic: flat art with its own colours, else as many as the tones need without fullTone's least count, merging close RGB colors, documentLibrary: at most `colors` of the library's colours, as they are), colors: 2-256, colorDetail: 0-100 (fullTone, automatic), library: \"document\" (the document's swatches) or a swatch library id or name (swatch.library.list; documentLibrary), colorGroup?: name (color mode, documentLibrary with library \"document\": the colors of that document color group instead of every swatch; \"\" is every swatch), paths: 0-100, corners: 0-100, noise: px (an area smaller than this joins the color it shares the longest border with; when that color is far from its own and the area is 2 px or more, or a single pixel whose longest border is not tied between colors, it joins the neighboring color nearest its pixels among those sharing at least a tenth of that border), method: \"abutting\"|\"overlapping\" (abutting with fills, not mode logo: a \"Seam Fills\" clip group under the paths holds strokes along the edges two filled paths share, 1.5 image pixels wide (VectorCraft's own width), in the color of the lower path (on an image stretched more one way than another, each stroke's outline in image pixels as a filled path), clipped to the image's box within the traced paths' box; paths that became live shapes get none; the paths are not changed), ignoreWhite (leave out white areas), ignoreColor?: \"#rrggbb\" (with ignoreWhite: the colour left out instead of white), ignoreBackground: false (with ignoreWhite: only the areas of the ignored color that reach the image's edge are left out), keepColors?: [\"#rrggbb\"…] (not mode logo: only the palette colors within about 30 levels of a listed color are traced; empty: every color), snapCurvesToLines, shapes: false (filled outlines that are a circle, an ellipse, a rectangle or a regular polygon come out as that live shape), autoGrouping: false (each path that has others inside it is grouped with them), gradients: false (grayscale and color: an area whose colour changes evenly along one direction is one path with a linear gradient fill), fills: true, strokes: false (Create: lines up to strokeWidth wide become stroked centre lines; without fills, wider areas become stroked outlines), strokeWidth: px (10), logoColors?: [\"#rrggbb\"…] (mode logo: flat-colour logos only; colours found automatically or named here, at most ten; white is its own color, and a named color with every channel 245 or more is taken as that white, except with logoColors named, logoWhite false and no ignoreWhite; noise = areas under noise/10 px ignored; edges to a fraction of a pixel, sharp corners restored, lines and circles snapped; enclosed transparent areas are painted white while white is its own color, and stay holes with ignoreWhite or without a white of its own; fills/strokes are ignored; gradients and photos are refused, judged by the image's own colors also when logoColors are named), logoWhite: true (mode logo with logoColors named; false traces the named colors only: white areas take the nearest of them, a named white is kept and enclosed transparent areas stay holes; with ignoreWhite, white areas are left out either way)}, view?: as imageTrace.setView (default: the traced object's own, else tracingResult), ids?: [id…] (instead of id)} → {id, paths, anchors, colors, warnings: [text…] (the image is over 1500 px on a side, so it traces more slowly; or it was traced scaled down; Flat Logo names only the size it traced a larger image at; or a keepColors color matches none the trace found, or nothing was traced)}",
|
||||
has_selection_or_ids,
|
||||
|s, p| trace_make(s, p, false)
|
||||
),
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
use super::{
|
||||
Appearance, AppearanceItem, Arc, Beside, Document, EDGE_NAME, EngineError, FACE_NAME, GapOptions, GapSize, LIVE_PAINT_NAME, Node, NodeId,
|
||||
PathData, Point, Rect, Result, SOURCES_NAME, Selection, Session, SubPath, Value, b, bad, build_children, edge_near, face_at, finite,
|
||||
fit_to_old_edge, ids_json, is_live_paint, json, number_or, object_param, paint_from, po, point_param, repaint_from, replace_roots, root_ids,
|
||||
source_nodes, source_shapes, switch_or,
|
||||
PathData, Point, Rect, Result, Selection, Session, SubPath, Value, b, bad, build_children, edge_near, face_at, finite, fit_to_old_edge, ids_json,
|
||||
is_live_paint, json, number_or, object_param, paint_from, po, point_param, repaint_from, replace_roots, root_ids, source_nodes, source_shapes,
|
||||
switch_or,
|
||||
};
|
||||
|
||||
/// `options` as stored on a Live Paint group: none for the defaults.
|
||||
@@ -53,6 +53,27 @@ fn make_live(d: &mut Document, sel: &mut Selection, roots: &[NodeId]) -> Result<
|
||||
Ok((gid, nf, ne))
|
||||
}
|
||||
|
||||
/// The children of Live Paint group `g` besides its sources group ([`b::sources`]) and its faces and
|
||||
/// edges (paths named [`FACE_NAME`] or [`EDGE_NAME`]), back to front: objects drawn in it in
|
||||
/// isolation mode. A group or other object named like a part is one of them.
|
||||
fn others_in(g: &Node) -> impl Iterator<Item = &Arc<Node>> {
|
||||
let src = b::sources(g).map(|s| s.id);
|
||||
g.children()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter(move |c| Some(c.id) != src && !(c.path_data().is_some() && matches!(c.name.as_deref(), Some(FACE_NAME | EDGE_NAME))))
|
||||
}
|
||||
|
||||
/// Make `parts` (a sources group, faces and edges made again) the children of Live Paint group `g`,
|
||||
/// with its other children ([`others_in`]) that are not among `gone` kept in front of them, in their
|
||||
/// order.
|
||||
fn set_parts(g: &mut Node, mut parts: Vec<Arc<Node>>, gone: &[NodeId]) {
|
||||
parts.extend(others_in(g).filter(|c| !gone.contains(&c.id)).cloned());
|
||||
if let Some(ch) = g.children_mut() {
|
||||
*ch = parts;
|
||||
}
|
||||
}
|
||||
|
||||
/// Select `ids` alone, without an undo step, when they are not selected that way already.
|
||||
fn select_only(s: &mut Session, ids: &[NodeId]) -> Result<()> {
|
||||
let st = s.doc()?;
|
||||
@@ -134,9 +155,15 @@ fn merge_live(d: &mut Document, sel: &mut Selection, roots: &[NodeId]) -> Result
|
||||
b::faces(&old).iter().filter(|f| draws(f)).filter_map(|f| Some((po::interior_point(f.path_data()?)?, Carried::of(f)))).collect();
|
||||
let old_parts = old.clone();
|
||||
let mut sources = source_nodes(&old);
|
||||
// The objects drawn in the other Live Paint groups besides their parts stay in the merged group.
|
||||
let mut others = vec![];
|
||||
for r in roots {
|
||||
if *r != target {
|
||||
sources.extend(source_nodes(d.node(*r).ok_or(EngineError::NoNode(*r))?));
|
||||
let n = d.node(*r).ok_or(EngineError::NoNode(*r))?;
|
||||
sources.extend(source_nodes(n));
|
||||
if is_live_paint(n) {
|
||||
others.extend(others_in(n).cloned());
|
||||
}
|
||||
}
|
||||
}
|
||||
// Merge applies the Gap Options' merge rules to the groups' options, bottom-most first.
|
||||
@@ -146,8 +173,9 @@ fn merge_live(d: &mut Document, sel: &mut Selection, roots: &[NodeId]) -> Result
|
||||
// The group keeps its name, lock, visibility, transparency, appearance, opacity mask, graphic
|
||||
// style link and the rest; its children are made again and its Gap Options set to the merged ones.
|
||||
let mut g = old;
|
||||
set_parts(&mut g, children, roots);
|
||||
if let Some(ch) = g.children_mut() {
|
||||
*ch = children;
|
||||
ch.extend(others);
|
||||
}
|
||||
g.extras_mut().live_paint_gaps = stored_gap_options(options);
|
||||
for (pt, carried) in keep_faces {
|
||||
@@ -199,6 +227,38 @@ pub(super) fn lp_merge(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "id": id.0, "faces": faces, "edges": edges }))
|
||||
}
|
||||
|
||||
/// The Live Paint group whose drawn art is added when isolation mode leaves `isolated`: the innermost
|
||||
/// Live Paint group that is `isolated` or holds it, such as a group drawn in an isolated Live Paint
|
||||
/// group and then isolated itself. None when `isolated` is not in a Live Paint group.
|
||||
pub(crate) fn isolated_live_paint(d: &Document, isolated: NodeId) -> Option<NodeId> {
|
||||
d.ancestry(isolated)?.into_iter().rev().find(|id| d.node(*id).is_some_and(is_live_paint))
|
||||
}
|
||||
|
||||
/// The children of Live Paint group `g` besides its parts ([`others_in`]) that Live Paint takes
|
||||
/// ([`b::live_paint_takes`]) and that are shown and unlocked with everything in them, back to
|
||||
/// front: the paths drawn in it in isolation mode.
|
||||
fn drawn_in(g: &Node) -> Vec<NodeId> {
|
||||
fn open(n: &Node) -> bool {
|
||||
n.visible && !n.locked && n.children().is_none_or(|ch| ch.iter().all(|c| open(c)))
|
||||
}
|
||||
others_in(g).filter(|c| open(c) && b::live_paint_takes(c)).map(|c| c.id).collect()
|
||||
}
|
||||
|
||||
/// Leaving isolation mode in Live Paint group `g` adds the paths drawn in it to the group as
|
||||
/// `livePaint.merge` does, in one "Merge Live Paint" undo step; → whether any were added. Type,
|
||||
/// images, other objects Live Paint does not take, and hidden or locked objects stay where they
|
||||
/// are. With nothing to add, or when `g` is not a Live Paint group, nothing changes and no undo
|
||||
/// step is recorded.
|
||||
pub(crate) fn merge_drawn_in_isolation(s: &mut Session, g: NodeId) -> Result<bool> {
|
||||
let drawn = s.doc()?.doc.node(g).filter(|n| is_live_paint(n)).map(drawn_in).unwrap_or_default();
|
||||
if drawn.is_empty() {
|
||||
return Ok(false);
|
||||
}
|
||||
let roots: Vec<NodeId> = std::iter::once(g).chain(drawn).collect();
|
||||
s.edit("Merge Live Paint", |d, sel| merge_live(d, sel, &roots))?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
fn live_targets(s: &Session, p: &Value) -> Result<Vec<NodeId>> {
|
||||
let d = &s.doc()?.doc;
|
||||
let ids = root_ids(s, p)?;
|
||||
@@ -216,7 +276,8 @@ pub(super) fn lp_release(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut released = Beside::replacing(d, &targets);
|
||||
for g in &targets {
|
||||
let n = d.node(*g).cloned().ok_or(EngineError::NoNode(*g))?;
|
||||
let srcs: Vec<Node> = source_nodes(&n).iter().map(|c| (**c).clone()).collect();
|
||||
// The objects drawn in the group besides its parts are released in front of its paths.
|
||||
let srcs: Vec<Node> = source_nodes(&n).iter().chain(others_in(&n)).map(|c| (**c).clone()).collect();
|
||||
out.extend(srcs.iter().map(|c| c.id));
|
||||
released.put(d, *g, srcs)?;
|
||||
}
|
||||
@@ -245,10 +306,12 @@ pub(super) fn lp_expand(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
e.trace = None;
|
||||
e.live_paint_gaps = None;
|
||||
}
|
||||
// Objects drawn in the group ([`others_in`]) stay, whatever they are named.
|
||||
let src = b::sources(n).map(|c| c.id);
|
||||
if let Some(ch) = n.children_mut() {
|
||||
ch.retain(|c| match c.name.as_deref() {
|
||||
Some(SOURCES_NAME) => false,
|
||||
Some(FACE_NAME | EDGE_NAME) => draws(c),
|
||||
_ if Some(c.id) == src => false,
|
||||
Some(FACE_NAME | EDGE_NAME) if c.path_data().is_some() => draws(c),
|
||||
_ => true,
|
||||
});
|
||||
}
|
||||
@@ -354,9 +417,7 @@ pub(super) fn lp_gap_options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// The faces change only with what paint stops at, or with new paths.
|
||||
if added > 0 || options.max_gap() != old.gap_options().max_gap() {
|
||||
let (children, _, _) = build_children(d, sources, options.max_gap())?;
|
||||
if let Some(ch) = n.children_mut() {
|
||||
*ch = children;
|
||||
}
|
||||
set_parts(&mut n, children, &[]);
|
||||
repaint_from(&mut n, &old);
|
||||
}
|
||||
n.extras_mut().live_paint_gaps = stored_gap_options(options);
|
||||
|
||||
@@ -209,7 +209,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Load Metafile into Clipboard",
|
||||
[],
|
||||
None,
|
||||
"{dataBase64 (EMF or WMF bytes), center?: [x, y]} replace the clipboard with the picture's objects (paths, clipping groups, images, point type; the images they use), centred on `center` (default: the first artboard) → {count, warnings}; records VectorCraft doesn't read are skipped with one warning; then run edit.paste",
|
||||
"{dataBase64 (EMF or WMF bytes), center?: [x, y]} replace the clipboard with the picture's objects (paths, clipping groups, images, point type; the images they use), centred on `center` (default: the first artboard) → {count, warnings}; records VectorCraft doesn't read are skipped with one warning; a picture cut short by a reader limit, images and pattern brushes that can't be read, clips that can't be applied and raster operations other than a plain copy each add a warning; then run edit.paste",
|
||||
has_doc,
|
||||
import_emf
|
||||
),
|
||||
|
||||
@@ -53,7 +53,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Flare",
|
||||
[],
|
||||
None,
|
||||
"{cx, cy, diameter=100, opacity=50 (%), brightness=30 (%), growth=20 (%), fuzziness=50 (%), rays=15, longest=300 (%), rayFuzziness=100 (%), rotation=0 (deg, turns the rays clockwise), x2?, y2? (ring end; else pathLength at direction), pathLength=300, rings=10, largest=50 (%), direction=45 (deg counter-clockwise from 3 o'clock: where the rings run from the centre), seed?, ringSeed? (whole number below 2^53: places the rings along the path anew, keeping their count and sizes)} → {id}",
|
||||
"{cx, cy, diameter=100, opacity=50 (%), brightness=30 (%), growth=20 (%), fuzziness=50 (%), rays=15, longest=300 (%), rayFuzziness=100 (%), rotation=0 (deg, turns the rays clockwise), x2?, y2? (ring end; else pathLength at direction), pathLength=300, rings=10, largest=50 (%), direction=45 (deg counter-clockwise from 3 o'clock: where the rings run from the centre), seed?, ringSeed? (whole number below 2^53: deterministically places every ring along the path, including the first for small seed values, keeping their count and sizes)} → {id}",
|
||||
has_doc,
|
||||
flare
|
||||
),
|
||||
@@ -67,7 +67,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
circle_through_points
|
||||
),
|
||||
cmd!("shape.line", "Line Segment", [], None, "{x1, y1, x2, y2, fill?: bool (Fill Line: the current fill, else none)} → {id}", has_doc, line),
|
||||
cmd!("shape.spiral", "Spiral", [], None, "{cx, cy, radius, decay=80 (%), segments=10, clockwise?} → {id}", has_doc, spiral),
|
||||
cmd!(
|
||||
"shape.spiral",
|
||||
"Spiral",
|
||||
[],
|
||||
None,
|
||||
"{cx, cy, radius, decay=80 (%), segments=10, clockwise?, rotation?: deg clockwise about (cx, cy)} (0: outer end at (cx + radius, cy)) → {id}",
|
||||
has_doc,
|
||||
spiral
|
||||
),
|
||||
cmd!(
|
||||
"shape.arc",
|
||||
"Arc",
|
||||
@@ -125,13 +133,6 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
]
|
||||
}
|
||||
|
||||
/// Insert a new object at the top of the insertion parent with the current paint and new-art
|
||||
/// template; select it.
|
||||
pub(crate) fn add_art(s: &mut Session, label: &str, kind: NodeKind, name: Option<String>) -> Result<Value> {
|
||||
let look = s.new_art_look(s.paint.fill.clone(), s.paint.stroke.clone(), s.paint.stroke_width);
|
||||
add_look(s, label, kind, look, name)
|
||||
}
|
||||
|
||||
/// Insert a new object looking like `look` (drawing modes apply); select it.
|
||||
pub(crate) fn add_look(s: &mut Session, label: &str, kind: NodeKind, look: NewArt, name: Option<String>) -> Result<Value> {
|
||||
insert_look(s, label, kind, look, name, true)
|
||||
@@ -143,7 +144,8 @@ pub(crate) fn insert_look(s: &mut Session, label: &str, kind: NodeKind, look: Ne
|
||||
insert_look_turned(s, label, kind, look, name, select, 0.0, true)
|
||||
}
|
||||
|
||||
/// [`add_art`] for an object made turned by a `rotation` param (degrees, clockwise on the page):
|
||||
/// Insert a new object at the top of the insertion parent with the current paint and new-art
|
||||
/// template, made turned by a `rotation` param (degrees, clockwise on the page), and select it:
|
||||
/// its bounding box turns with it, as after the Rotate tool.
|
||||
fn add_art_turned(s: &mut Session, label: &str, kind: NodeKind, rotation: f64) -> Result<Value> {
|
||||
let look = s.new_art_look(s.paint.fill.clone(), s.paint.stroke.clone(), s.paint.stroke_width);
|
||||
@@ -321,7 +323,7 @@ fn path_kind(path: PathData, live: Option<LiveShape>) -> NodeKind {
|
||||
/// a box (rectangle, ellipse, grid) runs along the turned axes from `pivot`, the point the dialog
|
||||
/// placed at the click (its top-left corner `x`, `y`, or a grid's reference point), which stays
|
||||
/// put; an arc sized by its lengths turns about its reference point `x`, `y`, which the dialog
|
||||
/// placed at the click; a polygon or star turns its base orientation about its centre. The params as they are at
|
||||
/// placed at the click; a polygon, star or spiral turns its base orientation about its centre. The params as they are at
|
||||
/// 0° or a whole turn, for other commands and when they already carry a `rotation`.
|
||||
pub fn constrain_click(s: &Session, cmd: &str, mut params: Value, pivot: Point) -> Value {
|
||||
let base = s.prefs.constrain_angle;
|
||||
@@ -337,7 +339,7 @@ pub fn constrain_click(s: &Session, cmd: &str, mut params: Value, pivot: Point)
|
||||
o.insert("y".into(), json!(c.y - h / 2.0));
|
||||
o.insert("rotation".into(), json!(rotation));
|
||||
}
|
||||
"shape.polygon" | "shape.star" => {
|
||||
"shape.polygon" | "shape.star" | "shape.spiral" => {
|
||||
o.insert("rotation".into(), json!(rotation));
|
||||
}
|
||||
"shape.arc" if o.contains_key("lengthX") || o.contains_key("lengthY") => {
|
||||
@@ -565,7 +567,7 @@ fn flare(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
None | Some(Value::Null) => Ok(None),
|
||||
Some(v) => v.as_u64().map(Some).ok_or_else(|| bad("shape.flare", format!("`{key}` must be a whole number of at least 0, not {v}"))),
|
||||
};
|
||||
// The generator's state is odd (never 0).
|
||||
// Xorshift64. Both streams start from a nonzero state.
|
||||
let random = |mut state: u64| {
|
||||
move || {
|
||||
state ^= state << 13;
|
||||
@@ -580,7 +582,13 @@ fn flare(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Some(r) if r >= 1 << 53 => return Err(bad("shape.flare", format!("`ringSeed` must be below 2^53, not {r}"))),
|
||||
r => r,
|
||||
};
|
||||
let mut ring_at = ring_seed.map(|r| random((r << 1) | 1));
|
||||
let mut ring_at = ring_seed.map(|r| {
|
||||
// SplitMix64 initializes the ring-position stream.
|
||||
let mut z = r.wrapping_add(0x9e37_79b9_7f4a_7c15);
|
||||
z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
|
||||
z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
|
||||
random(z ^ (z >> 31))
|
||||
});
|
||||
let stop = |offset: f32, opacity: f32| GradientStop { opacity, ..GradientStop::new(offset, vectorcraft_color::Color::WHITE) };
|
||||
let radial = |centre: Point, radius: f64, stops: Vec<GradientStop>| {
|
||||
let mut g = GradientPaint::new(Gradient::new(GradientKind::Radial, stops));
|
||||
@@ -667,6 +675,10 @@ fn line(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
fn spiral(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let rotation = if p.get("rotation").is_some() { f64_req(p, "rotation", "shape.spiral")? } else { 0.0 };
|
||||
if !rotation.is_finite() {
|
||||
return Err(bad("shape.spiral", "rotation must be finite"));
|
||||
}
|
||||
let c = Point::new(f64_req(p, "cx", "shape.spiral")?, f64_req(p, "cy", "shape.spiral")?);
|
||||
let segments = count_or(p, "segments", 10, "shape.spiral")?.clamp(2, 1000) as u32;
|
||||
let path = shapes::spiral(
|
||||
@@ -676,7 +688,15 @@ fn spiral(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
segments,
|
||||
switch_or(p, "clockwise", true, "shape.spiral")?,
|
||||
);
|
||||
add_art(s, "Spiral", path_kind(path, None), None)
|
||||
// The outer end turns clockwise from (cx + radius, cy) about the center; 0 and whole turns
|
||||
// leave the path as it is, and quarter turns are exact.
|
||||
let path = if bbox_turn(rotation) == 0.0 {
|
||||
path
|
||||
} else {
|
||||
let c = c.to_vec2();
|
||||
path.transformed(Affine::translate(c) * vectorcraft_geom::rotate_deg(rotation) * Affine::translate(-c))
|
||||
};
|
||||
add_art_turned(s, "Spiral", path_kind(path, None), constrained_turn(s, rotation))
|
||||
}
|
||||
|
||||
fn arc(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
@@ -11,7 +11,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Pencil",
|
||||
[],
|
||||
None,
|
||||
"{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1: the stroke keeps it, for Calligraphic and Scatter brushes with Pressure variation; a point without one presses fully. Pen tilt in degrees, each −90..90, x positive leaning right and y leaning down the page, and barrel rotation in degrees clockwise, 0..360: the stroke keeps how far the pen leaned, which way and how far its barrel turned, for brushes with Tilt, Bearing and Rotation variation; null for what a point lacks. A pressure, tilt or rotation outside its range, or a point array of more than six numbers, is an error), fidelity?: pt (1.5; from 0.000015625 (0.01 / 640) to 100 / 0.0313 (about 3194.89), the Pencil's and the Paintbrush's 0.01 to 100 px Fidelity at the highest and the lowest zoom; a value outside that range is an error. The tools send their Fidelity in pixels divided by the zoom, kept within the range), fit?: bool (true; false: the points are joined by straight segments, as the Pencil previews a stroke with Live curve fitting off), closed?, style?: \"pencil\"|\"brush\", fill?: bool, keepSelected?: bool (true: the drawn or continued path is selected; false: a new path leaves nothing selected, and a continued or redrawn one is deselected while the rest of the selection stays), extend?: {id, end: \"start\"|\"end\"}, connect?: {id, end: \"start\"|\"end\"}, redraw?: {id, within?: pt (12)}} fit a freehand stroke → {id}. extend continues the path from that end, and closes it when `closed` is true (left out, when the stroke ends within four Fidelities of the path's other end, 6 to 400 pt); with connect, the stroke ends on that end of another path's last open subpath and joins it on, in one path with the extended path's appearance (the other path is removed when nothing of it is left); redraw (Edit Selected Paths) replaces the section of the path between where the stroke starts and ends, each within `within` of one subpath (the shorter way round a closed one), and draws a new path when the stroke doesn't end on it",
|
||||
"{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1: the stroke keeps it, for Calligraphic and Scatter brushes with Pressure variation; a point without one presses fully. Pen tilt in degrees, each −90..90, x positive leaning right and y leaning down the page, and barrel rotation in degrees clockwise, 0..360: the stroke keeps how far the pen leaned, which way and how far its barrel turned, for brushes with Tilt, Bearing and Rotation variation; null for what a point lacks. A pressure, tilt or rotation outside its range, or a point array of more than six numbers, is an error), fidelity?: pt (1.5; from 0.000015625 (0.01 / 640) to 100 / 0.0313 (about 3194.89), the Pencil's and the Paintbrush's 0.01 to 100 px Fidelity at the highest and the lowest zoom; a value outside that range is an error. The tools send their Fidelity in pixels divided by the zoom, kept within the range), fit?: bool (true; false: the points are joined by straight segments, as the Pencil previews a stroke with Live curve fitting off), closed?, style?: \"pencil\" (default) | \"brush\", fill?: bool, keepSelected?: bool (true: the drawn or continued path is selected; false: a new path leaves nothing selected, and a continued or redrawn one is deselected while the rest of the selection stays), extend?: {id, end?: \"end\" (default) | \"start\"}, connect?: {id, end: \"start\"|\"end\"}, redraw?: {id, within?: pt (12)}} fit a freehand stroke → {id}. extend continues the path from that end, and closes it when `closed` is true (left out, when the stroke ends within four Fidelities of the path's other end, 6 to 400 pt); with connect, the stroke ends on that end of another path's last open subpath and joins it on, in one path with the extended path's appearance (the other path is removed when nothing of it is left); redraw (Edit Selected Paths) replaces the section of the path between where the stroke starts and ends, each within `within` of one subpath (the shorter way round a closed one), and draws a new path when the stroke doesn't end on it. Any other style, extend end or connect end is an error, and nothing changes",
|
||||
has_doc,
|
||||
freehand
|
||||
),
|
||||
@@ -128,7 +128,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Blob Brush",
|
||||
[],
|
||||
None,
|
||||
"{points: [[x,y]…] or [[x,y,pressure]…] (pen pressure 0..1; pen values are checked as path.freehand checks them), size?: pt (10; from 0.1 to 1000), sizeMode?: \"fixed\" (default) | \"pressure\" (Blob Brush Tool Options' Size set to Pressure: the brush is size − sizeVariation wide at the lightest pen pressure and size + sizeVariation at the heaviest, at least 0.1 pt; a stroke without pressure keeps the size), sizeVariation?: pt (0; from 0 to 1000, checked with Fixed too), angle?: ° (0, kept within −180–180: the tip's long axis counter-clockwise from horizontal, kept on the page along the stroke), roundness?: % (100, kept within 0–100: the tip's short axis in percent of its long one, 100 round; 0 is drawn as 0.1), fidelity?: pt (0.01–100; the brush follows the stroke fitted at this tolerance as path.freehand fits a Pencil stroke, and a higher value gives a smoother shape; without it the brush follows every point), merge?: true, mergeOnlySelection?: bool (false: merge with any touching same-color blob; true: only with selected ones), keepSelected?: bool (false: the drawn or merged path is not selected, and the rest of the selection stays; true: it is selected)} filled brush shape, merged with the topmost touching same-color blob and the touching ones next to it in stacking order in its group or layer → {id}",
|
||||
"{points: [[x,y]…] or [[x,y,pressure]…] (pen pressure 0..1; pen values are checked as path.freehand checks them), size?: pt (10; from 0.1 to 1000), sizeMode?: \"fixed\" (default) | \"pressure\" (Blob Brush Tool Options' Size set to Pressure: the brush is size − sizeVariation wide at the lightest pen pressure and size + sizeVariation at the heaviest, at least 0.1 pt; a stroke without pressure keeps the size), sizeVariation?: pt (0; from 0 to 1000, checked with Fixed too), angle?: ° (0, −180–180: the tip's long axis counter-clockwise from horizontal, kept on the page along the stroke), roundness?: % (100, 0–100: the tip's short axis in percent of its long one, 100 round; 0 is drawn as 0.1), fidelity?: pt (0.01–100; the brush follows the stroke fitted at this tolerance as path.freehand fits a Pencil stroke, and a higher value gives a smoother shape; without it the brush follows every point), merge?: true, mergeOnlySelection?: bool (false: merge with any touching same-color blob; true: only with selected ones), keepSelected?: bool (false: the drawn or merged path is not selected, and the rest of the selection stays; true: it is selected)} filled brush shape, merged with the topmost touching same-color blob and the touching ones next to it in stacking order in its group or layer → {id}. An angle, roundness or fidelity outside its range is rejected with an error, and nothing changes",
|
||||
has_doc,
|
||||
blob
|
||||
),
|
||||
|
||||
@@ -200,14 +200,22 @@ pub(crate) fn freehand_brushed(s: &mut Session, p: &Value, brush_name: Option<&s
|
||||
// The tolerance the stroke is fitted at; with `fit: false` it is not fitted.
|
||||
let fit_tol = switch_or(p, "fit", true, C)?.then_some(tol);
|
||||
let closed = switch_or(p, "closed", false, C)?;
|
||||
let brush = str_param(p, "style") == Some("brush");
|
||||
let brush = match p.get("style").filter(|v| !v.is_null()).map(Value::as_str) {
|
||||
None | Some(Some("pencil")) => false,
|
||||
Some(Some("brush")) => true,
|
||||
Some(_) => return Err(bad(C, "style must be \"pencil\" or \"brush\"")),
|
||||
};
|
||||
// The undo step's name: a stroke painted with a brush is a Paintbrush stroke, whatever its style.
|
||||
let label = if brush || brush_name.is_some() { "Paintbrush" } else { "Pencil" };
|
||||
let keep_selected = switch_or(p, "keepSelected", true, C)?;
|
||||
let filled = switch_or(p, "fill", false, C)?;
|
||||
if let Some(ext) = p.get("extend").filter(|v| !v.is_null()) {
|
||||
let id = object_param(ext, "id", C)?.ok_or_else(|| bad(C, "extend needs id"))?;
|
||||
let at_start = str_param(ext, "end") == Some("start");
|
||||
let at_start = match ext.get("end").filter(|v| !v.is_null()).map(Value::as_str) {
|
||||
None | Some(Some("end")) => false,
|
||||
Some(Some("start")) => true,
|
||||
Some(_) => return Err(bad(C, "extend end must be \"start\" or \"end\"")),
|
||||
};
|
||||
let (pd, _) = path_of(&s.doc()?.doc, id)?;
|
||||
let si = pd.subpaths.iter().rposition(|s| !s.closed && !s.anchors.is_empty()).ok_or_else(|| bad(C, "path has no open end"))?;
|
||||
let target = brush_target(&s.doc()?.doc, id);
|
||||
@@ -488,12 +496,23 @@ pub(super) fn blob(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let samples = samples_param(p, "points", C)?;
|
||||
let size = ranged(p, "size", 10.0, SIZES, C)?;
|
||||
let angle = number_or(p, "angle", 0.0, C)?;
|
||||
if !(-180.0..=180.0).contains(&angle) {
|
||||
return Err(bad(C, "`angle` must be from -180 to 180 degrees"));
|
||||
}
|
||||
let roundness = number_or(p, "roundness", 100.0, C)?;
|
||||
if !angle.is_finite() || !roundness.is_finite() {
|
||||
return Err(bad(C, "angle and roundness must be finite"));
|
||||
if !(0.0..=100.0).contains(&roundness) {
|
||||
return Err(bad(C, "`roundness` must be from 0 to 100%"));
|
||||
}
|
||||
// With `fidelity` (pt), the brush follows the stroke fitted by [`fit_freehand`], as a Pencil
|
||||
// stroke is fitted. Without it, or when the fitted stroke has no length (a short stroke back to
|
||||
// its start), the brush follows every point.
|
||||
let fidelity = match p.get("fidelity") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(_) => Some(number_or(p, "fidelity", 0.0, C)?),
|
||||
};
|
||||
if fidelity.is_some_and(|f| !(vectorcraft_tools::draw2::MIN_FIDELITY..=100.0).contains(&f)) {
|
||||
return Err(bad(C, "`fidelity` must be from 0.01 to 100 pt"));
|
||||
}
|
||||
let angle = angle.clamp(-180.0, 180.0);
|
||||
let roundness = roundness.clamp(0.0, 100.0);
|
||||
let tip = vectorcraft_tools::draw2::blob_tip(angle, roundness);
|
||||
let squash = tip.inverse();
|
||||
// Width profiles use distance along the spine, so measure pressure on the same squashed
|
||||
@@ -515,13 +534,6 @@ pub(super) fn blob(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mapped_pts: Vec<Point> = mapped_samples.into_iter().map(|s| s.pt).collect();
|
||||
// The widest the brush gets: the area merges look in.
|
||||
let reach = pressure.as_ref().map_or(size, |(_, v)| size + v);
|
||||
// With `fidelity` (pt), the brush follows the stroke fitted by [`fit_freehand`], as a Pencil
|
||||
// stroke is fitted. Without it, or when the fitted stroke has no length (a short stroke back to
|
||||
// its start), the brush follows every point.
|
||||
let fidelity = match p.get("fidelity") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(_) => Some(number_or(p, "fidelity", 0.0, C)?.clamp(vectorcraft_tools::draw2::MIN_FIDELITY, 100.0)),
|
||||
};
|
||||
let spine = |tol: Option<f64>| {
|
||||
let path = match tol {
|
||||
Some(tol) => PathData::single(fit_freehand(&pts, tol, false)),
|
||||
|
||||
@@ -39,7 +39,7 @@ pub mod jxlread;
|
||||
mod legacy_ai;
|
||||
mod load;
|
||||
mod mesh3d;
|
||||
pub(crate) use load::{MAX_RASTER_ALLOC, file_clipped, png_clip, size_note};
|
||||
pub(crate) use load::{MAX_RASTER_ALLOC, file_clipped, image_clip, size_note};
|
||||
mod heifread;
|
||||
mod hpgl;
|
||||
mod jp2read;
|
||||
@@ -87,8 +87,10 @@ pub use load::{
|
||||
};
|
||||
pub(crate) use load::{check_files_not_lossy_overwrite, check_not_lossy_overwrite, lossy_source};
|
||||
pub use load::{losses_summary, overwrite_losses};
|
||||
pub use mesh3d::{DEFAULT_FORMAT_3D, FORMATS_3D, format_3d_label};
|
||||
pub(crate) use mesh3d::{mesh_file_names, mesh_files};
|
||||
#[cfg(test)]
|
||||
pub(crate) use mesh3d::MAX_TEXTURE_PIXELS;
|
||||
pub use mesh3d::{DEFAULT_FORMAT_3D, FORMATS_3D, draws_textures, format_3d_label};
|
||||
pub(crate) use mesh3d::{TEXTURE_SIZE, TEXTURE_SIZES, image_maps, mesh_file_names, mesh_files, textures};
|
||||
pub use naming::{NameParts as FileNameParts, parse_date as parse_file_date, render as render_file_name};
|
||||
pub(crate) use native::preview_png;
|
||||
pub use native::with_compression_pref;
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -241,7 +241,8 @@ struct RasterOptions {
|
||||
width: Option<f64>,
|
||||
/// The height of each file in pixels (wins over `ppi` and `scale`).
|
||||
height: Option<f64>,
|
||||
quality: Option<u8>,
|
||||
/// JPEG and lossy WebP quality, read by [`RasterOptions::quality`].
|
||||
quality: Option<Value>,
|
||||
background: Option<Value>,
|
||||
anti_alias: Option<String>,
|
||||
interlaced: Option<bool>,
|
||||
@@ -281,6 +282,19 @@ fn clamped_ppi(ppi: f64) -> f64 {
|
||||
}
|
||||
|
||||
impl RasterOptions {
|
||||
/// `quality` as given: `None` when absent or null, else a whole number 0–255 (JPEG caps it at
|
||||
/// 100; WebP refuses more than 100), or an error naming it.
|
||||
fn quality(&self) -> Result<Option<u8>> {
|
||||
match &self.quality {
|
||||
None | Some(Value::Null) => Ok(None),
|
||||
Some(v) => v
|
||||
.as_u64()
|
||||
.and_then(|q| u8::try_from(q).ok())
|
||||
.map(Some)
|
||||
.ok_or_else(|| bad(C, format!("quality must be a whole number from 0 to 100, not {v}"))),
|
||||
}
|
||||
}
|
||||
|
||||
/// The pixel size each file is scaled to: `width`, else `height`; `None` when neither is set.
|
||||
fn pixel_size(&self) -> Result<Option<ScreenSize>> {
|
||||
let checked = |key: &str, n: f64| {
|
||||
@@ -311,7 +325,8 @@ impl RasterOptions {
|
||||
},
|
||||
anti_alias: self.anti_alias.as_deref().map(anti_alias).transpose().map_err(|e| bad(C, e))?.unwrap_or_default(),
|
||||
interlaced: self.interlaced.unwrap_or(false),
|
||||
quality: self.quality.unwrap_or(90).min(100),
|
||||
quality: self.quality()?.unwrap_or(90).min(100),
|
||||
webp_lossless: self.lossless.unwrap_or(true),
|
||||
jpeg: JpegOptions {
|
||||
color_model,
|
||||
method: parse(self.method.as_deref(), jpeg::Method::from_id, "method", "baseline, optimized or progressive")?,
|
||||
@@ -1136,6 +1151,11 @@ fn encode_files(doc: &Document, f: &Format, p: &Value) -> Result<Encoded> {
|
||||
"psd" => RasterFormat::Psd,
|
||||
_ => RasterFormat::WebP,
|
||||
};
|
||||
if format == RasterFormat::WebP
|
||||
&& let Some(q) = o.quality()?.filter(|q| *q > 100)
|
||||
{
|
||||
return Err(bad(C, format!("quality {q}: WebP quality is 0–100")));
|
||||
}
|
||||
check_options(format, &settings)?;
|
||||
// Use Artboards: one file per chosen artboard (default all); else the one chosen.
|
||||
let chosen = match use_artboards {
|
||||
@@ -1182,9 +1202,6 @@ fn encode_files(doc: &Document, f: &Format, p: &Value) -> Result<Encoded> {
|
||||
}
|
||||
let regions: Vec<Rect> = enc.files.iter().filter_map(|(b, _)| b.and_then(|b| doc.artboards.get(b))).map(|a| a.rect).collect();
|
||||
enc.warnings.extend(crate::cmd::fonts::export_overflow_warning(doc, &doc.layers, Some(®ions)));
|
||||
if format == RasterFormat::WebP && o.lossless == Some(false) {
|
||||
enc.setting_notes.push("lossy WebP isn't available yet: the file is lossless (exact, but larger)".into());
|
||||
}
|
||||
return Ok(enc);
|
||||
}
|
||||
_ => return Err(bad(C, format!("no encoder for {} yet", f.label))),
|
||||
|
||||
@@ -211,17 +211,11 @@ fn selected_part(n: &Arc<Node>, keep: &HashSet<NodeId>, holders: &HashSet<NodeId
|
||||
/// its own art, not a whole document of artboards. `renderer` measures the 3D art, and keeps it for
|
||||
/// the next artboard of the same document.
|
||||
pub(super) fn art_over(doc: &Document, rect: vectorcraft_geom::Rect, renderer: &mut vectorcraft_render::Renderer) -> Document {
|
||||
fn kept(
|
||||
n: &Arc<Node>,
|
||||
doc: &Document,
|
||||
symbols: &SymbolBoxes,
|
||||
rect: vectorcraft_geom::Rect,
|
||||
renderer: &mut vectorcraft_render::Renderer,
|
||||
) -> Option<Arc<Node>> {
|
||||
fn kept(n: &Arc<Node>, symbols: &SymbolBoxes, rect: vectorcraft_geom::Rect, renderer: &mut vectorcraft_render::Renderer) -> Option<Arc<Node>> {
|
||||
if matches!(n.kind, NodeKind::Layer { clip: false, .. }) {
|
||||
let mut layer = Node::clone(n);
|
||||
let children = layer.children_mut()?;
|
||||
*children = children.iter().filter_map(|c| kept(c, doc, symbols, rect, renderer)).collect();
|
||||
*children = children.iter().filter_map(|c| kept(c, symbols, rect, renderer)).collect();
|
||||
return Some(Arc::new(layer));
|
||||
}
|
||||
// A group that doesn't clip keeps only its members over the artboard, so art gathered in one
|
||||
@@ -230,20 +224,21 @@ pub(super) fn art_over(doc: &Document, rect: vectorcraft_geom::Rect, renderer: &
|
||||
if matches!(n.kind, NodeKind::Group { clip: false, .. }) && n.appearance.effects.is_empty() {
|
||||
let mut group = Node::clone(n);
|
||||
let children = group.children_mut()?;
|
||||
*children = children.iter().filter_map(|c| kept(c, doc, symbols, rect, renderer)).collect();
|
||||
*children = children.iter().filter_map(|c| kept(c, symbols, rect, renderer)).collect();
|
||||
return (!children.is_empty()).then(|| Arc::new(group));
|
||||
}
|
||||
let over = |b: vectorcraft_geom::Rect| b.x0 <= rect.x1 && rect.x0 <= b.x1 && b.y0 <= rect.y1 && rect.y0 <= b.y1;
|
||||
let mut holds_instance = false;
|
||||
n.walk(&mut |c| holds_instance |= matches!(c.kind, NodeKind::SymbolInstance { .. }));
|
||||
let painted = || holds_instance && vectorcraft_render::painted_bounds(doc, n).is_some_and(over);
|
||||
// Measured in boxes of its own, which find symbols through the same index.
|
||||
let painted = || holds_instance && vectorcraft_render::painted_bounds_with(&symbols.unmeasured(), n).is_some_and(over);
|
||||
let reach = vectorcraft_brush::reach_within(n);
|
||||
let brushed = |b: vectorcraft_geom::Rect| over(if reach > 0.0 { b.inflate(reach, reach) } else { b });
|
||||
(n.visual_bounds_with(symbols).is_none_or(brushed) || renderer.effect_bounds(symbols, n).is_some_and(brushed) || painted()).then(|| n.clone())
|
||||
}
|
||||
let symbols = doc.symbol_boxes().with_brush_art();
|
||||
let mut d = doc.clone();
|
||||
d.layers = doc.layers.iter().filter_map(|l| kept(l, doc, &symbols, rect, renderer)).collect();
|
||||
d.layers = doc.layers.iter().filter_map(|l| kept(l, &symbols, rect, renderer)).collect();
|
||||
d
|
||||
}
|
||||
|
||||
|
||||
@@ -206,11 +206,15 @@ const LOSSLESS: FormatOption = FormatOption {
|
||||
name: "lossless",
|
||||
ty: "boolean",
|
||||
default: "true",
|
||||
description: "lossless WebP; false asks for lossy, which isn't available yet (written lossless, with a warning)",
|
||||
description: "lossless WebP (every pixel kept exactly); false writes lossy WebP at quality: a smaller file that loses some detail",
|
||||
};
|
||||
|
||||
const WEBP_QUALITY: FormatOption =
|
||||
FormatOption { name: "quality", ty: "integer", default: "90", description: "lossy quality 0–100 (for when lossy WebP is available)" };
|
||||
const WEBP_QUALITY: FormatOption = FormatOption {
|
||||
name: "quality",
|
||||
ty: "integer",
|
||||
default: "90",
|
||||
description: "lossy WebP quality 0–100 (with lossless false; higher keeps more detail in a larger file; more than 100 is refused)",
|
||||
};
|
||||
|
||||
/// The options of the palette formats (PNG-8, GIF).
|
||||
const PALETTE_OPTIONS: &[FormatOption] = &[
|
||||
|
||||
@@ -60,8 +60,7 @@ impl Loaded {
|
||||
}
|
||||
}
|
||||
|
||||
/// An image ready to embed: PNG/JPEG/GIF/WebP keep their bytes, other formats are stored as PNG
|
||||
/// (what browsers, PDF and SVG viewers show).
|
||||
/// An image ready to embed. CMYK images use JPEG or TIFF; other images use browser-readable formats.
|
||||
#[derive(Clone)]
|
||||
pub struct RasterImage {
|
||||
/// Content key for `Document::images` (identical files share one blob).
|
||||
@@ -937,8 +936,9 @@ pub(crate) fn size_note(bytes: &[u8]) -> Option<String> {
|
||||
/// ink are written again with their inks together ([`vectorcraft_doc::cmyk::stored_cmyk_tiff`]);
|
||||
/// CMYK TIFFs with an alpha channel, which the decoder can't read, become RGBA in the active color
|
||||
/// settings' CMYK, whichever of their extra channels is the alpha
|
||||
/// ([`vectorcraft_doc::cmyk::extra_samples_tiff_rgba`]), as do CMYK Photoshop documents, whose
|
||||
/// merged image is read ([`psdread`]).
|
||||
/// ([`vectorcraft_doc::cmyk::extra_samples_tiff_rgba`]). Opaque CMYK PSD/PSB merged images retain
|
||||
/// 8- or 16-bit inks and their CMYK ICC profile as TIFF, within the native CMYK pixel and allocation limits;
|
||||
/// other CMYK composites use the RGBA decoder's allocation limit ([`psdread`]).
|
||||
/// 1-bit TIFFs compressed with CCITT Group 3, which the decoder can't read either, become RGBA
|
||||
/// too ([`vectorcraft_doc::cmyk::group3_tiff_rgba`]).
|
||||
/// Grayscale TIFFs with an alpha channel or other extra channels, which the decoder can't read
|
||||
@@ -961,14 +961,27 @@ pub(crate) fn size_note(bytes: &[u8]) -> Option<String> {
|
||||
/// or TIFF keeps its inks, at the 8 or 16 bits the file has, and its CMYK ICC profile as a CMYK
|
||||
/// TIFF ([`vectorcraft_doc::cmyk::turned_cmyk`]). An image the decoder reads and that is stored as
|
||||
/// PNG keeps its gray or RGB samples at 8 or 16 bits, and the gray or RGB ICC profile they are in;
|
||||
/// other samples become 8-bit RGBA. A Photoshop document's PNG keeps the clipping path the file
|
||||
/// names ([`png_with_clip`]).
|
||||
/// other samples become 8-bit RGBA. A PSD/PSB composite's stored image keeps its imported
|
||||
/// clipping path ([`image_clip`]).
|
||||
pub fn raster_image(bytes: &[u8]) -> Result<RasterImage> {
|
||||
let ppi = super::ppi::resolution(bytes);
|
||||
if let Some((w, h)) = vectorcraft_doc::cmyk::oversized_tiff(bytes) {
|
||||
return Err(err(format!("an image of {w} × {h} pixels is too large to draw")));
|
||||
}
|
||||
if psdread::is_psd(bytes) {
|
||||
if let Some(mut native) = psdread::decode_cmyk(bytes, MAX_RASTER_ALLOC).map_err(err)? {
|
||||
native.meta.dpi = ppi.map(|(x, y)| (x as f32, y as f32));
|
||||
let clip = psdread::clipping_path(bytes).and_then(|path| {
|
||||
let json = serde_json::to_string(&path).ok().filter(|j| j.len() <= MAX_PNG_CLIP)?;
|
||||
native.meta.text.push(("Description".into(), format!("{CLIP_KEYWORD}\n{json}")));
|
||||
Some((path, vectorcraft_geom::FillRule::EvenOdd))
|
||||
});
|
||||
let data =
|
||||
craft_image_codecs::encode(&native, craft_image_codecs::Format::Tiff, &craft_image_codecs::EncodeOptions::default()).map_err(err)?;
|
||||
let mut img = stored(data, "image/tiff", native.dimensions(), ppi)?;
|
||||
img.clip = clip;
|
||||
return Ok(img);
|
||||
}
|
||||
let cms = vectorcraft_color::cms::active();
|
||||
let img = as_png(psdread::decode(bytes, MAX_RASTER_ALLOC, |c| cms.cmyk_to_srgb(c, false)).map_err(err)?, None, ppi)?;
|
||||
return Ok(png_with_clip(img, psdread::clipping_path(bytes)));
|
||||
@@ -1173,6 +1186,31 @@ pub(crate) fn png_clip(png: &[u8]) -> Option<vectorcraft_geom::PathData> {
|
||||
vectorcraft_geom::path::with_anchor_budget(vectorcraft_geom::path::MAX_READ_ANCHORS, || serde_json::from_slice(json).ok())
|
||||
}
|
||||
|
||||
/// The imported clipping-path marker in a stored PNG or CMYK TIFF, within the path budget.
|
||||
pub(crate) fn image_clip(blob: &ImageBlob) -> Option<vectorcraft_geom::PathData> {
|
||||
if blob.mime == "image/png" {
|
||||
return png_clip(&blob.bytes);
|
||||
}
|
||||
if blob.mime != "image/tiff" {
|
||||
return None;
|
||||
}
|
||||
use tiff::tags::{Tag, Type, ValueBuffer};
|
||||
let mut d = tiff::decoder::Decoder::new(std::io::Cursor::new(blob.bytes.as_slice())).ok()?;
|
||||
let mut ifd = d.image_ifd();
|
||||
let entry = ifd.find_entry(Tag::ImageDescription)?;
|
||||
if entry.field_type() != Type::ASCII || entry.count() > (MAX_PNG_CLIP + CLIP_KEYWORD.len() + 2) as u64 {
|
||||
return None;
|
||||
}
|
||||
let mut buf = ValueBuffer::empty(Type::ASCII);
|
||||
ifd.find_tag_buf(Tag::ImageDescription, &mut buf).ok()??;
|
||||
let json = buf.as_bytes().strip_prefix(CLIP_KEYWORD.as_bytes())?.strip_prefix(b"\n")?;
|
||||
let json = json.strip_suffix(b"\0").unwrap_or(json);
|
||||
if json.len() > MAX_PNG_CLIP {
|
||||
return None;
|
||||
}
|
||||
vectorcraft_geom::path::with_anchor_budget(vectorcraft_geom::path::MAX_READ_ANCHORS, || serde_json::from_slice(json).ok())
|
||||
}
|
||||
|
||||
/// An image as a document of its physical size at the resolution it declares (as Place sizes it;
|
||||
/// 72 ppi, 1 px = 1 pt, when it declares none), the image named after the file.
|
||||
pub(super) fn raster_doc(name: &str, bytes: &[u8]) -> Result<Document> {
|
||||
|
||||
@@ -9,13 +9,24 @@
|
||||
//! as their specifications ask; MTL colors are the display colors. Materials are two-sided, since
|
||||
//! an open solid or a turned plane is seen from both sides.
|
||||
//!
|
||||
//! The graphics mapped onto a face of a solid ([`textures`]) are a PNG picture of that face: its
|
||||
//! color with the graphics drawn over it, flat and unshaded, which the face's own mesh shows through
|
||||
//! texture coordinates and a material of its own. glTF embeds each PNG as a data URI, USDZ stores it
|
||||
//! after the layer, and OBJ and USDA name PNG files written beside them (`<name>-texture-1.png`…).
|
||||
//!
|
||||
//! Formats: glTF 2.0 <https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html>, USD
|
||||
//! <https://openusd.org/release/index.html> (USDZ: <https://openusd.org/release/spec_usdz.html>).
|
||||
//! <https://openusd.org/release/index.html> (USDZ: <https://openusd.org/release/spec_usdz.html>;
|
||||
//! textures: <https://openusd.org/release/spec_usdpreviewsurface.html>), OBJ and MTL
|
||||
//! <https://www.loc.gov/preservation/digital/formats/fdd/fdd000508.shtml>.
|
||||
|
||||
use std::fmt::Write as _;
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_render::effects::SolidMesh;
|
||||
use vectorcraft_doc::color::{Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, Document, Node, NodeId};
|
||||
use vectorcraft_geom::{Affine, Rect};
|
||||
use vectorcraft_render::effects::{MeshGraphics, SolidMesh};
|
||||
|
||||
/// The formats a 3D asset exports to, as `assets.set3DFormat` names them: USDA first, the default.
|
||||
pub const FORMATS_3D: [&str; 4] = ["usda", "usdz", "gltf", "obj"];
|
||||
@@ -23,6 +34,12 @@ pub const FORMATS_3D: [&str; 4] = ["usda", "usdz", "gltf", "obj"];
|
||||
pub const DEFAULT_FORMAT_3D: &str = "usda";
|
||||
/// The meters in a point (1/72 inch).
|
||||
const METERS_PER_POINT: f64 = 0.0254 / 72.0;
|
||||
/// The pixels along the longer side of a face's texture, unless `assets.export3D` is given another
|
||||
/// size, and the sizes it takes.
|
||||
pub(crate) const TEXTURE_SIZE: u32 = 1024;
|
||||
pub(crate) const TEXTURE_SIZES: (u32, u32) = (128, 4096);
|
||||
/// The most texture pixels one export draws, all its assets together.
|
||||
pub(crate) const MAX_TEXTURE_PIXELS: u64 = 4 * 4096 * 4096;
|
||||
|
||||
/// The label of `format` for menus: `USDA`, `USDZ`, `glTF`, `OBJ`.
|
||||
pub fn format_3d_label(format: &str) -> &'static str {
|
||||
@@ -40,14 +57,44 @@ fn obj_stem(stem: &str) -> String {
|
||||
stem.chars().map(|c| if c.is_whitespace() || c == '#' { '_' } else { c }).collect()
|
||||
}
|
||||
|
||||
/// The names of the files [`mesh_files`] writes for `stem` in `format`.
|
||||
pub(crate) fn mesh_file_names(stem: &str, format: &str) -> Result<Vec<String>, String> {
|
||||
/// The name of texture `k` (from 0) of the object named `stem`: whitespace, `#` and `@` become `_`,
|
||||
/// so an MTL `map_Kd` line and a USD asset path name it as one word.
|
||||
fn texture_name(stem: &str, k: usize) -> String {
|
||||
format!("{}-texture-{}.png", texture_stem(stem), k + 1)
|
||||
}
|
||||
|
||||
/// The name of the opacity map of texture `k` (from 0) of the object named `stem`, as
|
||||
/// [`texture_name`] names the texture.
|
||||
fn opacity_name(stem: &str, k: usize) -> String {
|
||||
format!("{}-texture-{}-opacity.png", texture_stem(stem), k + 1)
|
||||
}
|
||||
|
||||
/// `stem` with whitespace, `#` and `@` turned into `_`, for the names of its textures.
|
||||
fn texture_stem(stem: &str) -> String {
|
||||
stem.chars().map(|c| if c.is_whitespace() || c == '#' || c == '@' { '_' } else { c }).collect()
|
||||
}
|
||||
|
||||
/// The names of the files [`mesh_files`] writes for `stem` in `format` with the textures `images`
|
||||
/// ([`image_maps`]: for each, whether it has an opacity map): OBJ and USDA name a PNG file for each
|
||||
/// texture after them, and OBJ also one for each opacity map, after its texture; glTF and USDZ hold
|
||||
/// theirs.
|
||||
pub(crate) fn mesh_file_names(stem: &str, format: &str, images: &[bool]) -> Result<Vec<String>, String> {
|
||||
let beside = |mut names: Vec<String>, stem: &str, maps: bool| {
|
||||
for (k, map) in images.iter().enumerate() {
|
||||
names.push(texture_name(stem, k));
|
||||
if maps && *map {
|
||||
names.push(opacity_name(stem, k));
|
||||
}
|
||||
}
|
||||
names
|
||||
};
|
||||
match format {
|
||||
"obj" => {
|
||||
let stem = obj_stem(stem);
|
||||
Ok(vec![format!("{stem}.obj"), format!("{stem}.mtl")])
|
||||
Ok(beside(vec![format!("{stem}.obj"), format!("{stem}.mtl")], &stem, true))
|
||||
}
|
||||
"gltf" | "usda" | "usdz" => Ok(vec![format!("{stem}.{format}")]),
|
||||
"usda" => Ok(beside(vec![format!("{stem}.usda")], stem, false)),
|
||||
"gltf" | "usdz" => Ok(vec![format!("{stem}.{format}")]),
|
||||
_ => {
|
||||
let key = "format";
|
||||
Err(format!("`{key}` must be one of {}", FORMATS_3D.join(", ")))
|
||||
@@ -55,35 +102,109 @@ pub(crate) fn mesh_file_names(stem: &str, format: &str) -> Result<Vec<String>, S
|
||||
}
|
||||
}
|
||||
|
||||
/// A picture painted on one part of a 3D object ([`SolidMesh`]): a PNG, and for each corner of the
|
||||
/// part's mesh where it falls on the picture (0 to 1 across from the left, 0 to 1 down from the
|
||||
/// top). `opacity` is a grayscale PNG of the picture's alpha when some of it is not opaque.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub(crate) struct Texture {
|
||||
pub png: Arc<Vec<u8>>,
|
||||
pub opacity: Option<Arc<Vec<u8>>>,
|
||||
pub uv: Vec<[f64; 2]>,
|
||||
}
|
||||
|
||||
/// A distinct picture of a 3D object: the PNG and its opacity map.
|
||||
type Picture = (Arc<Vec<u8>>, Option<Arc<Vec<u8>>>);
|
||||
|
||||
/// The distinct pictures of `textures` in order of first use, and the index among them of each
|
||||
/// part's (`None` for a part without one).
|
||||
fn images(parts: usize, textures: &[Option<Texture>]) -> (Vec<Picture>, Vec<Option<usize>>) {
|
||||
let mut out: Vec<Picture> = vec![];
|
||||
let index = (0..parts)
|
||||
.map(|k| {
|
||||
let t = textures.get(k)?.as_ref()?;
|
||||
Some(out.iter().position(|(p, _)| Arc::ptr_eq(p, &t.png) || p == &t.png).unwrap_or_else(|| {
|
||||
out.push((t.png.clone(), t.opacity.clone()));
|
||||
out.len() - 1
|
||||
}))
|
||||
})
|
||||
.collect();
|
||||
(out, index)
|
||||
}
|
||||
|
||||
/// For each distinct picture of `textures`, whether it has an opacity map ([`mesh_file_names`]).
|
||||
pub(crate) fn image_maps(textures: &[Option<Texture>]) -> Vec<bool> {
|
||||
images(textures.len(), textures).0.iter().map(|(_, map)| map.is_some()).collect()
|
||||
}
|
||||
|
||||
/// The files of a 3D object named `stem` in `format` ([`FORMATS_3D`]): `(file name, bytes)`, the
|
||||
/// OBJ with its MTL after it.
|
||||
pub(crate) fn mesh_files(stem: &str, format: &str, parts: &[SolidMesh]) -> Result<Vec<(String, Vec<u8>)>, String> {
|
||||
let names = mesh_file_names(stem, format)?;
|
||||
let bytes = match format {
|
||||
/// OBJ with its MTL after it and the PNG files of `textures` last (an OBJ's opacity maps each after
|
||||
/// its texture). `textures` holds the picture of each part that has one, in the order of `parts`.
|
||||
pub(crate) fn mesh_files(stem: &str, format: &str, parts: &[SolidMesh], textures: &[Option<Texture>]) -> Result<Vec<(String, Vec<u8>)>, String> {
|
||||
let (images, image) = images(parts.len(), textures);
|
||||
let maps: Vec<bool> = images.iter().map(|(_, map)| map.is_some()).collect();
|
||||
let names = mesh_file_names(stem, format, &maps)?;
|
||||
let pictures: Vec<Arc<Vec<u8>>> = images.iter().map(|(p, _)| p.clone()).collect();
|
||||
let scene = Scene { parts, textures, image: &image, pictures: &pictures, maps: &maps };
|
||||
let pngs = || pictures.iter().map(|p| p.as_ref().clone());
|
||||
let bytes: Vec<Vec<u8>> = match format {
|
||||
"obj" => {
|
||||
let (obj, mtl) = obj(&obj_stem(stem), parts);
|
||||
vec![obj.into_bytes(), mtl.into_bytes()]
|
||||
let stem = obj_stem(stem);
|
||||
let (obj, mtl) = obj(&stem, &scene);
|
||||
let with_maps = images.iter().flat_map(|(p, map)| std::iter::once(p.as_ref().clone()).chain(map.as_ref().map(|m| m.as_ref().clone())));
|
||||
[obj.into_bytes(), mtl.into_bytes()].into_iter().chain(with_maps).collect()
|
||||
}
|
||||
"gltf" => vec![gltf(stem, &scene).into_bytes()],
|
||||
"usda" => std::iter::once(usda(stem, &scene).into_bytes()).chain(pngs()).collect(),
|
||||
_ => {
|
||||
let mut members = vec![(format!("{stem}.usda"), usda(stem, &scene).into_bytes())];
|
||||
members.extend(pngs().enumerate().map(|(k, png)| (texture_name(stem, k), png)));
|
||||
vec![super::zip::store_aligned(&members, 64)?]
|
||||
}
|
||||
"gltf" => vec![gltf(stem, parts).into_bytes()],
|
||||
"usda" => vec![usda(stem, parts).into_bytes()],
|
||||
_ => vec![super::zip::store_aligned(&[(format!("{stem}.usda"), usda(stem, parts).into_bytes())], 64)?],
|
||||
};
|
||||
Ok(names.into_iter().zip(bytes).collect())
|
||||
}
|
||||
|
||||
/// The distinct colors of `parts` in order, and each part's index among them.
|
||||
fn materials(parts: &[SolidMesh]) -> (Vec<[f32; 4]>, Vec<usize>) {
|
||||
let mut colors: Vec<[f32; 4]> = vec![];
|
||||
let index = parts
|
||||
/// The parts of an object with their pictures: `image` is each part's index among `pictures`, and
|
||||
/// `maps` says for each picture whether it has an opacity map.
|
||||
struct Scene<'a> {
|
||||
parts: &'a [SolidMesh],
|
||||
textures: &'a [Option<Texture>],
|
||||
image: &'a [Option<usize>],
|
||||
pictures: &'a [Arc<Vec<u8>>],
|
||||
maps: &'a [bool],
|
||||
}
|
||||
|
||||
impl Scene<'_> {
|
||||
/// Part `k`'s texture coordinates and picture, when it has a picture.
|
||||
fn texture(&self, k: usize) -> Option<(&[[f64; 2]], usize)> {
|
||||
let t = self.textures.get(k)?.as_ref()?;
|
||||
Some((t.uv.as_slice(), (*self.image.get(k)?)?))
|
||||
}
|
||||
}
|
||||
|
||||
/// A material: a color, with a picture that replaces its red, green and blue.
|
||||
#[derive(Clone, Copy, PartialEq)]
|
||||
struct Material {
|
||||
color: [f32; 4],
|
||||
image: Option<usize>,
|
||||
}
|
||||
|
||||
/// The distinct materials of `scene`'s parts in order, and each part's index among them.
|
||||
fn materials(scene: &Scene) -> (Vec<Material>, Vec<usize>) {
|
||||
let mut out: Vec<Material> = vec![];
|
||||
let index = scene
|
||||
.parts
|
||||
.iter()
|
||||
.map(|p| {
|
||||
colors.iter().position(|c| *c == p.color).unwrap_or_else(|| {
|
||||
colors.push(p.color);
|
||||
colors.len() - 1
|
||||
.enumerate()
|
||||
.map(|(k, p)| {
|
||||
let m = Material { color: p.color, image: scene.texture(k).map(|(_, i)| i) };
|
||||
out.iter().position(|c| *c == m).unwrap_or_else(|| {
|
||||
out.push(m);
|
||||
out.len() - 1
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
(colors, index)
|
||||
(out, index)
|
||||
}
|
||||
|
||||
/// An sRGB channel (0..1) as linear light.
|
||||
@@ -96,8 +217,9 @@ fn num(v: f64) -> String {
|
||||
format!("{v}")
|
||||
}
|
||||
|
||||
fn obj(stem: &str, parts: &[SolidMesh]) -> (String, String) {
|
||||
let (colors, material) = materials(parts);
|
||||
fn obj(stem: &str, scene: &Scene) -> (String, String) {
|
||||
let parts = scene.parts;
|
||||
let (materials, material) = materials(scene);
|
||||
let mut o = String::new();
|
||||
let _ = writeln!(o, "mtllib {stem}.mtl");
|
||||
let _ = writeln!(o, "o {stem}");
|
||||
@@ -106,33 +228,64 @@ fn obj(stem: &str, parts: &[SolidMesh]) -> (String, String) {
|
||||
let _ = writeln!(o, "v {} {} {}", num(v[0]), num(v[1]), num(v[2]));
|
||||
}
|
||||
}
|
||||
// OBJ's texture coordinates run up from the picture's bottom.
|
||||
for k in 0..parts.len() {
|
||||
for uv in scene.texture(k).map(|(uv, _)| uv).unwrap_or_default() {
|
||||
let _ = writeln!(o, "vt {} {}", num(uv[0]), num(1.0 - uv[1]));
|
||||
}
|
||||
}
|
||||
for p in parts {
|
||||
for n in &p.mesh.normals {
|
||||
let _ = writeln!(o, "vn {} {} {}", num(n[0]), num(n[1]), num(n[2]));
|
||||
}
|
||||
}
|
||||
let mut base = 1usize;
|
||||
let (mut base, mut uv_base) = (1usize, 1usize);
|
||||
for (k, p) in parts.iter().enumerate() {
|
||||
let _ = writeln!(o, "g Solid_{}", k + 1);
|
||||
let _ = writeln!(o, "usemtl Material_{}", material.get(k).copied().unwrap_or(0) + 1);
|
||||
let textured = scene.texture(k).filter(|(uv, _)| uv.len() == p.mesh.positions.len()).is_some();
|
||||
for t in &p.mesh.triangles {
|
||||
let [a, b, c] = t.map(|i| i as usize + base);
|
||||
let _ = writeln!(o, "f {a}//{a} {b}//{b} {c}//{c}");
|
||||
if textured {
|
||||
let [a, b, c] = t.map(|i| i as usize);
|
||||
let corner = |i: usize| format!("{}/{}/{}", i + base, i + uv_base, i + base);
|
||||
let _ = writeln!(o, "f {} {} {}", corner(a), corner(b), corner(c));
|
||||
} else {
|
||||
let [a, b, c] = t.map(|i| i as usize + base);
|
||||
let _ = writeln!(o, "f {a}//{a} {b}//{b} {c}//{c}");
|
||||
}
|
||||
}
|
||||
base += p.mesh.positions.len();
|
||||
uv_base += scene.texture(k).map_or(0, |(uv, _)| uv.len());
|
||||
}
|
||||
let mut m = String::new();
|
||||
for (k, c) in colors.iter().enumerate() {
|
||||
for (k, mat) in materials.iter().enumerate() {
|
||||
let c = mat.color;
|
||||
let _ = writeln!(m, "newmtl Material_{}", k + 1);
|
||||
let _ = writeln!(m, "Kd {} {} {}", num(f64::from(c[0])), num(f64::from(c[1])), num(f64::from(c[2])));
|
||||
let _ = writeln!(m, "d {}", num(f64::from(c[3])));
|
||||
match mat.image {
|
||||
// The picture holds the color; Kd multiplies it.
|
||||
Some(_) => {
|
||||
let _ = writeln!(m, "Kd 1 1 1");
|
||||
}
|
||||
None => {
|
||||
let _ = writeln!(m, "Kd {} {} {}", num(f64::from(c[0])), num(f64::from(c[1])), num(f64::from(c[2])));
|
||||
}
|
||||
}
|
||||
// A picture's opacity map holds the opacity, as gray levels.
|
||||
let _ = writeln!(m, "d {}", if mat.image.is_some() { "1".to_string() } else { num(f64::from(c[3])) });
|
||||
let _ = writeln!(m, "illum 1");
|
||||
if let Some(i) = mat.image {
|
||||
let _ = writeln!(m, "map_Kd -clamp on {}", texture_name(stem, i));
|
||||
if scene.maps.get(i).copied().unwrap_or(false) {
|
||||
let _ = writeln!(m, "map_d -clamp on {}", opacity_name(stem, i));
|
||||
}
|
||||
}
|
||||
}
|
||||
(o, m)
|
||||
}
|
||||
|
||||
fn gltf(stem: &str, parts: &[SolidMesh]) -> String {
|
||||
let (colors, material) = materials(parts);
|
||||
fn gltf(stem: &str, scene: &Scene) -> String {
|
||||
let parts = scene.parts;
|
||||
let (materials, material) = materials(scene);
|
||||
let mut buffer: Vec<u8> = vec![];
|
||||
let (mut views, mut accessors, mut primitives) = (vec![], vec![], vec![]);
|
||||
let mut view = |buffer: &mut Vec<u8>, bytes: Vec<u8>, target: u32| -> usize {
|
||||
@@ -154,16 +307,25 @@ fn gltf(stem: &str, parts: &[SolidMesh]) -> String {
|
||||
}));
|
||||
accessors.push(json!({ "bufferView": normals, "componentType": 5126, "count": count, "type": "VEC3" }));
|
||||
accessors.push(json!({ "bufferView": indices, "componentType": 5125, "count": p.mesh.triangles.len() * 3, "type": "SCALAR" }));
|
||||
primitives.push(json!({
|
||||
let mut primitive = json!({
|
||||
"attributes": { "POSITION": at, "NORMAL": at + 1 },
|
||||
"indices": at + 2,
|
||||
"material": material.get(k).copied().unwrap_or(0),
|
||||
}));
|
||||
});
|
||||
// glTF's texture coordinates run down from the picture's top, as the picture's own do.
|
||||
if let Some((uv, _)) = scene.texture(k).filter(|(uv, _)| uv.len() == count) {
|
||||
let bytes = uv.iter().flatten().flat_map(|x| (*x as f32).to_le_bytes()).collect();
|
||||
let coords = view(&mut buffer, bytes, 34962);
|
||||
primitive["attributes"]["TEXCOORD_0"] = json!(accessors.len());
|
||||
accessors.push(json!({ "bufferView": coords, "componentType": 5126, "count": count, "type": "VEC2" }));
|
||||
}
|
||||
primitives.push(primitive);
|
||||
}
|
||||
let materials: Vec<Value> = colors
|
||||
let materials: Vec<Value> = materials
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(k, c)| {
|
||||
.map(|(k, mat)| {
|
||||
let c = mat.color;
|
||||
let mut m = json!({
|
||||
"name": format!("Material_{}", k + 1),
|
||||
"pbrMetallicRoughness": {
|
||||
@@ -173,13 +335,18 @@ fn gltf(stem: &str, parts: &[SolidMesh]) -> String {
|
||||
},
|
||||
"doubleSided": true,
|
||||
});
|
||||
if let Some(i) = mat.image {
|
||||
// The picture holds the color and the opacity; the factor multiplies them.
|
||||
m["pbrMetallicRoughness"]["baseColorFactor"] = json!([1.0, 1.0, 1.0, 1.0]);
|
||||
m["pbrMetallicRoughness"]["baseColorTexture"] = json!({ "index": i });
|
||||
}
|
||||
if c[3] < 1.0 {
|
||||
m["alphaMode"] = json!("BLEND");
|
||||
}
|
||||
m
|
||||
})
|
||||
.collect();
|
||||
let doc = json!({
|
||||
let mut doc = json!({
|
||||
"asset": { "version": "2.0", "generator": "VectorCraft" },
|
||||
"scene": 0,
|
||||
"scenes": [{ "nodes": [0] }],
|
||||
@@ -193,6 +360,14 @@ fn gltf(stem: &str, parts: &[SolidMesh]) -> String {
|
||||
"bufferViews": views,
|
||||
"accessors": accessors,
|
||||
});
|
||||
if !scene.pictures.is_empty() {
|
||||
// Linear filtering, mipmaps, and coordinates held at the picture's edge.
|
||||
doc["samplers"] = json!([{ "magFilter": 9729, "minFilter": 9987, "wrapS": 33071, "wrapT": 33071 }]);
|
||||
doc["textures"] = Value::Array((0..scene.pictures.len()).map(|i| json!({ "sampler": 0, "source": i })).collect());
|
||||
doc["images"] = Value::Array(
|
||||
scene.pictures.iter().map(|p| json!({ "uri": format!("data:image/png;base64,{}", vectorcraft_format::base64_encode(p)) })).collect(),
|
||||
);
|
||||
}
|
||||
serde_json::to_string_pretty(&doc).unwrap_or_default()
|
||||
}
|
||||
|
||||
@@ -205,8 +380,9 @@ fn prim_name(name: &str) -> String {
|
||||
out
|
||||
}
|
||||
|
||||
fn usda(stem: &str, parts: &[SolidMesh]) -> String {
|
||||
let (colors, material) = materials(parts);
|
||||
fn usda(stem: &str, scene: &Scene) -> String {
|
||||
let parts = scene.parts;
|
||||
let (materials, material) = materials(scene);
|
||||
let root = prim_name(stem);
|
||||
let triple = |v: [f64; 3]| format!("({}, {}, {})", num(v[0]), num(v[1]), num(v[2]));
|
||||
let list = |items: Vec<String>| items.join(", ");
|
||||
@@ -238,23 +414,178 @@ fn usda(stem: &str, parts: &[SolidMesh]) -> String {
|
||||
linear(c[2])
|
||||
);
|
||||
let _ = writeln!(u, " float[] primvars:displayOpacity = [{}] (\n interpolation = \"constant\"\n )", c[3]);
|
||||
// USD's texture coordinates run up from the picture's bottom.
|
||||
if let Some((uv, _)) = scene.texture(k).filter(|(uv, _)| uv.len() == p.mesh.positions.len()) {
|
||||
let st = list(uv.iter().map(|t| format!("({}, {})", num(t[0]), num(1.0 - t[1]))).collect());
|
||||
let _ = writeln!(u, " texCoord2f[] primvars:st = [{st}] (\n interpolation = \"vertex\"\n )");
|
||||
}
|
||||
let _ = writeln!(u, " uniform token subdivisionScheme = \"none\"\n }}\n");
|
||||
}
|
||||
let _ = writeln!(u, " def Scope \"Materials\"\n {{");
|
||||
for (k, c) in colors.iter().enumerate() {
|
||||
let m = k + 1;
|
||||
for (k, mat) in materials.iter().enumerate() {
|
||||
let (m, c) = (k + 1, mat.color);
|
||||
let at = format!("/{root}/Materials/Material_{m}");
|
||||
let _ = writeln!(u, " def Material \"Material_{m}\"\n {{");
|
||||
let _ = writeln!(u, " token outputs:surface.connect = </{root}/Materials/Material_{m}/Surface.outputs:surface>\n");
|
||||
let _ = writeln!(u, " token outputs:surface.connect = <{at}/Surface.outputs:surface>\n");
|
||||
let _ = writeln!(u, " def Shader \"Surface\"\n {{");
|
||||
let _ = writeln!(u, " uniform token info:id = \"UsdPreviewSurface\"");
|
||||
let _ = writeln!(u, " color3f inputs:diffuseColor = ({}, {}, {})", linear(c[0]), linear(c[1]), linear(c[2]));
|
||||
let _ = writeln!(u, " float inputs:opacity = {}", c[3]);
|
||||
match mat.image {
|
||||
// The picture holds the color, and the opacity when the face is not opaque.
|
||||
Some(_) => {
|
||||
let _ = writeln!(u, " color3f inputs:diffuseColor.connect = <{at}/Texture.outputs:rgb>");
|
||||
if c[3] < 1.0 {
|
||||
let _ = writeln!(u, " float inputs:opacity.connect = <{at}/Texture.outputs:a>");
|
||||
} else {
|
||||
let _ = writeln!(u, " float inputs:opacity = 1");
|
||||
}
|
||||
}
|
||||
None => {
|
||||
let _ = writeln!(u, " color3f inputs:diffuseColor = ({}, {}, {})", linear(c[0]), linear(c[1]), linear(c[2]));
|
||||
let _ = writeln!(u, " float inputs:opacity = {}", c[3]);
|
||||
}
|
||||
}
|
||||
let _ = writeln!(u, " float inputs:roughness = 1");
|
||||
let _ = writeln!(u, " token outputs:surface\n }}\n }}");
|
||||
let _ = writeln!(u, " token outputs:surface\n }}");
|
||||
if let Some(i) = mat.image {
|
||||
let _ = writeln!(u, "\n def Shader \"Texture\"\n {{");
|
||||
let _ = writeln!(u, " uniform token info:id = \"UsdUVTexture\"");
|
||||
let _ = writeln!(u, " asset inputs:file = @{}@", texture_name(stem, i));
|
||||
let _ = writeln!(u, " float2 inputs:st.connect = <{at}/Coordinates.outputs:result>");
|
||||
let _ = writeln!(u, " token inputs:sourceColorSpace = \"sRGB\"");
|
||||
let _ = writeln!(u, " token inputs:wrapS = \"clamp\"");
|
||||
let _ = writeln!(u, " token inputs:wrapT = \"clamp\"");
|
||||
let _ = writeln!(u, " float3 outputs:rgb");
|
||||
if c[3] < 1.0 {
|
||||
let _ = writeln!(u, " float outputs:a");
|
||||
}
|
||||
let _ = writeln!(u, " }}");
|
||||
let _ = writeln!(u, "\n def Shader \"Coordinates\"\n {{");
|
||||
let _ = writeln!(u, " uniform token info:id = \"UsdPrimvarReader_float2\"");
|
||||
let _ = writeln!(u, " string inputs:varname = \"st\"");
|
||||
let _ = writeln!(u, " float2 outputs:result\n }}");
|
||||
}
|
||||
let _ = writeln!(u, " }}");
|
||||
}
|
||||
let _ = writeln!(u, " }}\n}}");
|
||||
u
|
||||
}
|
||||
|
||||
/// The pictures of the graphics on `parts` ([`SolidMesh::graphics`]), one for each part in order
|
||||
/// (`None` for a part without graphics, or whose graphics draw nothing): the part's color with its
|
||||
/// graphics drawn over it, flat and unshaded ([`vectorcraft_render::effects::mesh_graphics_art`]),
|
||||
/// over the bounds of the art points of its corners, `size` pixels along the longer side. Parts with
|
||||
/// the same color, face, graphics and bounds share one picture. `pixels` counts the pixels drawn so
|
||||
/// far, and every call of one export shares it: an error when it passes [`MAX_TEXTURE_PIXELS`].
|
||||
pub(crate) fn textures(doc: &Document, parts: &[SolidMesh], size: u32, pixels: &mut u64) -> Result<Vec<Option<Texture>>, String> {
|
||||
let mut renderer: Option<vectorcraft_render::Renderer> = None;
|
||||
// Each picture drawn: the part it was drawn for, its bounds, and the PNG with its opacity map
|
||||
// (`None`: nothing drawn).
|
||||
let mut drawn: Vec<Drawn> = vec![];
|
||||
let mut out = vec![];
|
||||
for part in parts {
|
||||
let Some(g) = &part.graphics else {
|
||||
out.push(None);
|
||||
continue;
|
||||
};
|
||||
let Some(frame) = texture_frame(g) else {
|
||||
out.push(None);
|
||||
continue;
|
||||
};
|
||||
let scale = f64::from(size) / frame.width().max(frame.height());
|
||||
let fit = |side: f64| ((side * scale).ceil() as u32).clamp(1, size);
|
||||
let (w, h) = (fit(frame.width()), fit(frame.height()));
|
||||
let same = |(p, r, _): &&Drawn| p.color == part.color && *r == frame && p.graphics.as_ref().is_some_and(|o| same_graphics(o, g));
|
||||
let png = match drawn.iter().find(same) {
|
||||
Some((_, _, png)) => png.clone(),
|
||||
None => {
|
||||
let png = match vectorcraft_render::effects::mesh_graphics_art(doc, NodeId(0), g)? {
|
||||
None => None,
|
||||
Some(art) => {
|
||||
*pixels = pixels.saturating_add(u64::from(w) * u64::from(h));
|
||||
if *pixels > MAX_TEXTURE_PIXELS {
|
||||
return Err(format!(
|
||||
"the graphics need more than {MAX_TEXTURE_PIXELS} pixels of textures: lower textureSize (now {size})"
|
||||
));
|
||||
}
|
||||
let renderer = renderer.get_or_insert_with(vectorcraft_render::Renderer::new);
|
||||
Some(picture(doc, renderer, (part.color, g.opacity, g.object), art, (frame, scale), (w, h))?)
|
||||
}
|
||||
};
|
||||
drawn.push((part, frame, png.clone()));
|
||||
png
|
||||
}
|
||||
};
|
||||
out.push(png.map(|(png, opacity)| {
|
||||
let uv = g.art.iter().map(|p| [(p.x - frame.x0) * scale / f64::from(w), (p.y - frame.y0) * scale / f64::from(h)]).collect();
|
||||
Texture { png, opacity, uv }
|
||||
}));
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Does [`textures`] draw a picture for one of `parts`: a part with graphics whose corners span an
|
||||
/// area and whose graphics draw something? Nothing is rendered.
|
||||
pub fn draws_textures(doc: &Document, parts: &[SolidMesh]) -> bool {
|
||||
parts.iter().any(|p| {
|
||||
p.graphics
|
||||
.as_ref()
|
||||
.is_some_and(|g| texture_frame(g).is_some() && matches!(vectorcraft_render::effects::mesh_graphics_art(doc, NodeId(0), g), Ok(Some(_))))
|
||||
})
|
||||
}
|
||||
|
||||
/// The part of the art's plane a picture of `g` covers: the bounds of its corners' art points, when
|
||||
/// they span an area.
|
||||
fn texture_frame(g: &MeshGraphics) -> Option<Rect> {
|
||||
g.art_bounds().filter(|r| r.width() > 1e-9 && r.height() > 1e-9 && r.width().is_finite() && r.height().is_finite())
|
||||
}
|
||||
|
||||
/// A picture [`textures`] drew: the part, the bounds and the PNG with its opacity map.
|
||||
type Drawn<'a> = (&'a SolidMesh, Rect, Option<Picture>);
|
||||
|
||||
/// Do `a` and `b` draw the same graphics on their face?
|
||||
fn same_graphics(a: &MeshGraphics, b: &MeshGraphics) -> bool {
|
||||
a.face == b.face && a.center == b.center && a.graphics == b.graphics && a.opacity == b.opacity && a.object == b.object
|
||||
}
|
||||
|
||||
/// `art` drawn over `color` as a PNG of `w` × `h` pixels whose top left is `frame`'s top left, at
|
||||
/// `scale` pixels a point, with a grayscale PNG of its alpha when some of it is not opaque. As on
|
||||
/// the canvas, the art is drawn at `face` (the opacity of the face's fill or stroke), the color at
|
||||
/// its own opacity without `object`'s, and `object` (the object's opacity) applies to the whole
|
||||
/// picture.
|
||||
fn picture(
|
||||
doc: &Document,
|
||||
renderer: &mut vectorcraft_render::Renderer,
|
||||
(color, face, object): ([f32; 4], f32, f32),
|
||||
mut art: Node,
|
||||
(frame, scale): (Rect, f64),
|
||||
(w, h): (u32, u32),
|
||||
) -> Result<Picture, String> {
|
||||
// The color reaches two pixels past the frame, so the picture's edge pixels are covered.
|
||||
let reach = 2.0 / scale;
|
||||
let back = Rect::new(frame.x0 - reach, frame.y0 - reach, frame.x0 + f64::from(w) / scale + reach, frame.y0 + f64::from(h) / scale + reach);
|
||||
let fill = Paint::solid(Color::rgb(color[0], color[1], color[2]));
|
||||
let mut ground = Node::path(NodeId(0), vectorcraft_geom::shapes::rectangle(back), Appearance::basic(fill, Paint::None, 0.0));
|
||||
let unit = |v: f32| if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 };
|
||||
let object = unit(object);
|
||||
ground.opacity = if object > 0.0 { unit(color[3] / object) } else { 0.0 };
|
||||
art.opacity *= unit(face);
|
||||
let mut group = Node::group(NodeId(0), vec![Arc::new(ground), Arc::new(art)]);
|
||||
group.opacity = object;
|
||||
let group = Arc::new(group);
|
||||
let (pw, ph) = (u16::try_from(w).map_err(|_| "texture too large")?, u16::try_from(h).map_err(|_| "texture too large")?);
|
||||
let view = Affine::scale(scale) * Affine::translate((-frame.x0, -frame.y0));
|
||||
let drawn = renderer.render_node(doc, &group, pw, ph, view).ok_or_else(|| "the graphics could not be drawn".to_string())?;
|
||||
let alpha: Vec<u8> = drawn.pixels.iter().skip(3).step_by(4).copied().collect();
|
||||
let opacity = if alpha.iter().all(|a| *a == 255) {
|
||||
None
|
||||
} else {
|
||||
let gray = image::GrayImage::from_raw(w, h, alpha).ok_or("the texture's opacity could not be drawn")?;
|
||||
let mut png = vec![];
|
||||
gray.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).map_err(|e| format!("PNG encoding failed: {e}"))?;
|
||||
Some(Arc::new(png))
|
||||
};
|
||||
Ok((Arc::new(drawn.to_png()?), opacity))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
@@ -7,7 +7,7 @@ use super::*;
|
||||
fn square(color: [f32; 4]) -> SolidMesh {
|
||||
let [a, b, c, d] = [[-5.0, -5.0, 0.0], [5.0, -5.0, 0.0], [5.0, 5.0, 0.0], [-5.0, 5.0, 0.0]];
|
||||
let mesh = Mesh { positions: vec![a, b, c, a, c, d], normals: vec![[0.0, 0.0, 1.0]; 6], triangles: vec![[0, 1, 2], [3, 4, 5]] };
|
||||
SolidMesh { mesh, color }
|
||||
SolidMesh::plain(mesh, color)
|
||||
}
|
||||
|
||||
const RED: [f32; 4] = [1.0, 0.0, 0.0, 1.0];
|
||||
@@ -18,9 +18,14 @@ fn text(files: &[(String, Vec<u8>)], name: &str) -> String {
|
||||
String::from_utf8(bytes.clone()).unwrap()
|
||||
}
|
||||
|
||||
/// [`mesh_files`] without textures.
|
||||
fn plain_files(stem: &str, format: &str, parts: &[SolidMesh]) -> Result<Vec<(String, Vec<u8>)>, String> {
|
||||
mesh_files(stem, format, parts, &[])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn obj_numbers_corners_across_solids_and_names_its_materials() {
|
||||
let files = mesh_files("Box", "obj", &[square(RED), square(BLUE), square(RED)]).unwrap();
|
||||
let files = plain_files("Box", "obj", &[square(RED), square(BLUE), square(RED)]).unwrap();
|
||||
assert_eq!(files.iter().map(|(n, _)| n.as_str()).collect::<Vec<_>>(), ["Box.obj", "Box.mtl"]);
|
||||
let obj = text(&files, "Box.obj");
|
||||
assert!(obj.starts_with("mtllib Box.mtl\no Box\n"));
|
||||
@@ -36,7 +41,7 @@ fn obj_numbers_corners_across_solids_and_names_its_materials() {
|
||||
|
||||
#[test]
|
||||
fn gltf_holds_its_buffer_and_every_accessor_fits_it() {
|
||||
let files = mesh_files("Box", "gltf", &[square(RED), square(BLUE)]).unwrap();
|
||||
let files = plain_files("Box", "gltf", &[square(RED), square(BLUE)]).unwrap();
|
||||
let g: Value = serde_json::from_str(&text(&files, "Box.gltf")).unwrap();
|
||||
assert_eq!(g["asset"]["version"], "2.0");
|
||||
let uri = g["buffers"][0]["uri"].as_str().unwrap();
|
||||
@@ -59,11 +64,13 @@ fn gltf_holds_its_buffer_and_every_accessor_fits_it() {
|
||||
assert_eq!(g["materials"][1]["alphaMode"], "BLEND");
|
||||
assert!(g["materials"][0].get("alphaMode").is_none());
|
||||
assert_eq!(g["materials"][0]["doubleSided"], true);
|
||||
// Without graphics there are no textures.
|
||||
assert!(g.get("images").is_none() && g.get("textures").is_none() && prims[0]["attributes"].get("TEXCOORD_0").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn usda_is_y_up_in_points_with_a_material_for_each_color() {
|
||||
let files = mesh_files("My Box", "usda", &[square(RED), square([0.5, 0.5, 0.5, 1.0])]).unwrap();
|
||||
let files = plain_files("My Box", "usda", &[square(RED), square([0.5, 0.5, 0.5, 1.0])]).unwrap();
|
||||
let u = text(&files, "My Box.usda");
|
||||
assert!(u.starts_with("#usda 1.0\n"));
|
||||
assert!(u.contains("defaultPrim = \"My_Box\"") && u.contains("upAxis = \"Y\"") && u.contains("def Xform \"My_Box\""), "{u}");
|
||||
@@ -75,11 +82,12 @@ fn usda_is_y_up_in_points_with_a_material_for_each_color() {
|
||||
// sRGB 0.5 is about 0.214 linear.
|
||||
assert!(u.contains("color3f inputs:diffuseColor = (0.21404"), "{u}");
|
||||
assert_eq!(u.matches('{').count(), u.matches('}').count());
|
||||
assert!(!u.contains("primvars:st") && !u.contains("UsdUVTexture"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn usdz_stores_the_layer_uncompressed_on_a_64_byte_boundary() {
|
||||
let files = mesh_files("Box", "usdz", &[square(RED)]).unwrap();
|
||||
let files = plain_files("Box", "usdz", &[square(RED)]).unwrap();
|
||||
let (name, zip) = &files[0];
|
||||
assert_eq!(name, "Box.usdz");
|
||||
// The local header: 30 bytes, the name, then the extra field.
|
||||
@@ -88,7 +96,7 @@ fn usdz_stores_the_layer_uncompressed_on_a_64_byte_boundary() {
|
||||
assert_eq!(u16_at(8), 0, "stored, not deflated");
|
||||
let start = 30 + u16_at(26) + u16_at(28);
|
||||
assert_eq!(start % 64, 0);
|
||||
let layer = mesh_files("Box", "usda", &[square(RED)]).unwrap().remove(0).1;
|
||||
let layer = plain_files("Box", "usda", &[square(RED)]).unwrap().remove(0).1;
|
||||
assert_eq!(&zip[start..start + layer.len()], layer.as_slice());
|
||||
let archive = super::super::zip::Archive::open(zip, 8).unwrap();
|
||||
assert_eq!(archive.read("Box.usda", usize::MAX).unwrap(), Some(layer));
|
||||
@@ -96,11 +104,11 @@ fn usdz_stores_the_layer_uncompressed_on_a_64_byte_boundary() {
|
||||
|
||||
#[test]
|
||||
fn an_obj_names_its_mtl_file_without_spaces_or_comment_marks() {
|
||||
let files = mesh_files("Box #1", "obj", &[square(RED)]).unwrap();
|
||||
let files = plain_files("Box #1", "obj", &[square(RED)]).unwrap();
|
||||
assert_eq!(files.iter().map(|(n, _)| n.as_str()).collect::<Vec<_>>(), ["Box__1.obj", "Box__1.mtl"]);
|
||||
assert!(text(&files, "Box__1.obj").starts_with("mtllib Box__1.mtl\n"));
|
||||
assert_eq!(mesh_file_names("Box #1", "obj").unwrap(), ["Box__1.obj", "Box__1.mtl"]);
|
||||
assert_eq!(mesh_file_names("Box #1", "usda").unwrap(), ["Box #1.usda"]);
|
||||
assert_eq!(mesh_file_names("Box #1", "obj", &[]).unwrap(), ["Box__1.obj", "Box__1.mtl"]);
|
||||
assert_eq!(mesh_file_names("Box #1", "usda", &[]).unwrap(), ["Box #1.usda"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -108,17 +116,17 @@ fn obj_and_usda_keep_coordinates_a_32_bit_float_would_merge() {
|
||||
let mut part = square(RED);
|
||||
part.mesh.positions[0] = [20_000_000.0, 0.0, 0.0];
|
||||
part.mesh.positions[1] = [20_000_001.0, 0.0, 0.0];
|
||||
let obj = text(&mesh_files("Box", "obj", std::slice::from_ref(&part)).unwrap(), "Box.obj");
|
||||
let obj = text(&plain_files("Box", "obj", std::slice::from_ref(&part)).unwrap(), "Box.obj");
|
||||
assert!(obj.contains("v 20000000 0 0\nv 20000001 0 0\n"), "{obj}");
|
||||
let usda = text(&mesh_files("Box", "usda", &[part]).unwrap(), "Box.usda");
|
||||
let usda = text(&plain_files("Box", "usda", &[part]).unwrap(), "Box.usda");
|
||||
assert!(usda.contains("(20000001, 0, 0)"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unknown_format_is_refused() {
|
||||
assert!(mesh_files("Box", "fbx", &[square(RED)]).is_err());
|
||||
assert!(mesh_file_names("Box", "").is_err());
|
||||
assert_eq!(mesh_file_names("Box", "obj").unwrap(), ["Box.obj", "Box.mtl"]);
|
||||
assert!(plain_files("Box", "fbx", &[square(RED)]).is_err());
|
||||
assert!(mesh_file_names("Box", "", &[]).is_err());
|
||||
assert_eq!(mesh_file_names("Box", "obj", &[]).unwrap(), ["Box.obj", "Box.mtl"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -128,3 +136,114 @@ fn prim_names_are_usd_identifiers() {
|
||||
assert_eq!(prim_name(""), "_");
|
||||
assert_eq!(prim_name("é/x"), "__x");
|
||||
}
|
||||
|
||||
/// A red square, then a blue one whose corners show picture `png` (u to the right, v down).
|
||||
fn textured(png: &[u8]) -> (Vec<SolidMesh>, Vec<Option<Texture>>) {
|
||||
let uv = vec![[0.0, 1.0], [1.0, 1.0], [1.0, 0.0], [0.0, 1.0], [1.0, 0.0], [0.0, 0.0]];
|
||||
let texture = Texture { png: Arc::new(png.to_vec()), opacity: None, uv };
|
||||
(vec![square(RED), square(BLUE)], vec![None, Some(texture)])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_format_carries_a_textured_part_with_its_coordinates_and_picture() {
|
||||
let png = b"\x89PNG picture".to_vec();
|
||||
let (parts, pictures) = textured(&png);
|
||||
// OBJ: vt runs up from the picture's bottom, the textured faces name it, and map_Kd the PNG
|
||||
// written beside it, with its name in one word.
|
||||
let files = mesh_files("My Box", "obj", &parts, &pictures).unwrap();
|
||||
assert_eq!(files.iter().map(|(n, _)| n.as_str()).collect::<Vec<_>>(), ["My_Box.obj", "My_Box.mtl", "My_Box-texture-1.png"]);
|
||||
assert_eq!(files[2].1, png);
|
||||
let obj = text(&files, "My_Box.obj");
|
||||
assert_eq!(obj.lines().filter(|l| l.starts_with("vt ")).collect::<Vec<_>>(), ["vt 0 0", "vt 1 0", "vt 1 1", "vt 0 0", "vt 1 1", "vt 0 1"]);
|
||||
assert_eq!(obj.lines().rfind(|l| l.starts_with("f ")), Some("f 10/4/10 11/5/11 12/6/12"));
|
||||
assert!(obj.contains("f 1//1 2//2 3//3"), "the plain part keeps no texture coordinates");
|
||||
let mtl = text(&files, "My_Box.mtl");
|
||||
assert!(mtl.contains("newmtl Material_2\nKd 1 1 1\nd 1\nillum 1\nmap_Kd -clamp on My_Box-texture-1.png\n"), "{mtl}");
|
||||
assert_eq!(mtl.matches("map_Kd").count(), 1);
|
||||
// glTF: TEXCOORD_0 down from the top, and the picture embedded as a data URI.
|
||||
let g: Value = serde_json::from_str(&text(&mesh_files("Box", "gltf", &parts, &pictures).unwrap(), "Box.gltf")).unwrap();
|
||||
let prims = g["meshes"][0]["primitives"].as_array().unwrap();
|
||||
assert!(prims[0]["attributes"].get("TEXCOORD_0").is_none());
|
||||
let uv = &g["accessors"][prims[1]["attributes"]["TEXCOORD_0"].as_u64().unwrap() as usize];
|
||||
assert_eq!((uv["type"].as_str(), uv["count"].as_u64(), uv["componentType"].as_u64()), (Some("VEC2"), Some(6), Some(5126)));
|
||||
let view = &g["bufferViews"][uv["bufferView"].as_u64().unwrap() as usize];
|
||||
let data = vectorcraft_format::base64_decode(g["buffers"][0]["uri"].as_str().unwrap().split(',').nth(1).unwrap()).unwrap();
|
||||
let at = view["byteOffset"].as_u64().unwrap() as usize;
|
||||
let first: Vec<f32> = (0..2).map(|k| f32::from_le_bytes(data[at + 4 * k..at + 4 * k + 4].try_into().unwrap())).collect();
|
||||
assert_eq!(first, [0.0, 1.0]);
|
||||
let material = &g["materials"][prims[1]["material"].as_u64().unwrap() as usize];
|
||||
assert_eq!(material["pbrMetallicRoughness"]["baseColorTexture"]["index"], 0);
|
||||
assert_eq!(material["pbrMetallicRoughness"]["baseColorFactor"], serde_json::json!([1.0, 1.0, 1.0, 1.0]));
|
||||
assert_eq!(g["textures"][0]["source"], 0);
|
||||
assert_eq!(g["samplers"][0]["wrapS"], 33071);
|
||||
let image = g["images"][0]["uri"].as_str().unwrap().strip_prefix("data:image/png;base64,").unwrap();
|
||||
assert_eq!(vectorcraft_format::base64_decode(image).unwrap(), png);
|
||||
// USDA: st up from the bottom, read by a primvar reader into a UV texture of the PNG beside it.
|
||||
let files = mesh_files("Box", "usda", &parts, &pictures).unwrap();
|
||||
assert_eq!(files.iter().map(|(n, _)| n.as_str()).collect::<Vec<_>>(), ["Box.usda", "Box-texture-1.png"]);
|
||||
let u = text(&files, "Box.usda");
|
||||
assert_eq!(u.matches("primvars:st").count(), 1);
|
||||
assert!(u.contains("texCoord2f[] primvars:st = [(0, 0), (1, 0), (1, 1), (0, 0), (1, 1), (0, 1)]"), "{u}");
|
||||
assert!(u.contains("color3f inputs:diffuseColor.connect = </Box/Materials/Material_2/Texture.outputs:rgb>"), "{u}");
|
||||
assert!(u.contains("asset inputs:file = @Box-texture-1.png@") && u.contains("uniform token info:id = \"UsdUVTexture\""));
|
||||
assert!(u.contains("float2 inputs:st.connect = </Box/Materials/Material_2/Coordinates.outputs:result>"));
|
||||
assert!(u.contains("string inputs:varname = \"st\""));
|
||||
assert_eq!(u.matches('{').count(), u.matches('}').count());
|
||||
// USDZ: the layer first, then the picture, each on a 64-byte boundary.
|
||||
let zip = mesh_files("Box", "usdz", &parts, &pictures).unwrap().remove(0).1;
|
||||
let archive = super::super::zip::Archive::open(&zip, 8).unwrap();
|
||||
assert_eq!(archive.read("Box.usda", usize::MAX).unwrap().map(String::from_utf8), Some(Ok(u)));
|
||||
assert_eq!(archive.read("Box-texture-1.png", usize::MAX).unwrap(), Some(png.clone()));
|
||||
let u16_at = |at: usize| u16::from_le_bytes([zip[at], zip[at + 1]]) as usize;
|
||||
let u32_at = |at: usize| u32::from_le_bytes([zip[at], zip[at + 1], zip[at + 2], zip[at + 3]]) as usize;
|
||||
let first = 30 + u16_at(26) + u16_at(28);
|
||||
let second = first + u32_at(18);
|
||||
assert_eq!(&zip[second..second + 4], &[0x50, 0x4b, 0x03, 0x04], "the picture comes second");
|
||||
let data = second + 30 + u16_at(second + 26) + u16_at(second + 28);
|
||||
assert_eq!((first % 64, data % 64), (0, 0));
|
||||
assert_eq!(&zip[data..data + png.len()], png.as_slice());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_textured_face_that_is_not_opaque_takes_its_opacity_from_the_picture() {
|
||||
let (parts, mut pictures) = textured(b"picture");
|
||||
if let Some(t) = pictures[1].as_mut() {
|
||||
t.opacity = Some(Arc::new(b"gray".to_vec()));
|
||||
}
|
||||
// OBJ: the opacity map, written after its texture, is the MTL's map_d.
|
||||
let files = mesh_files("My Box", "obj", &parts, &pictures).unwrap();
|
||||
let names: Vec<&str> = files.iter().map(|(n, _)| n.as_str()).collect();
|
||||
assert_eq!(names, ["My_Box.obj", "My_Box.mtl", "My_Box-texture-1.png", "My_Box-texture-1-opacity.png"]);
|
||||
assert_eq!(files[3].1, b"gray");
|
||||
assert_eq!(mesh_file_names("My Box", "obj", &image_maps(&pictures)).unwrap(), names);
|
||||
let mtl = text(&files, "My_Box.mtl");
|
||||
assert!(mtl.contains("d 1\nillum 1\nmap_Kd -clamp on My_Box-texture-1.png\nmap_d -clamp on My_Box-texture-1-opacity.png\n"), "{mtl}");
|
||||
let g: Value = serde_json::from_str(&text(&mesh_files("Box", "gltf", &parts, &pictures).unwrap(), "Box.gltf")).unwrap();
|
||||
let material = &g["materials"][1];
|
||||
assert_eq!((material["pbrMetallicRoughness"]["baseColorFactor"][3].as_f64(), material["alphaMode"].as_str()), (Some(1.0), Some("BLEND")));
|
||||
let usda = mesh_files("Box", "usda", &parts, &pictures).unwrap();
|
||||
assert_eq!(usda.len(), 2, "USD reads the opacity from the texture's alpha");
|
||||
let u = text(&usda, "Box.usda");
|
||||
assert!(u.contains("float inputs:opacity.connect = </Box/Materials/Material_2/Texture.outputs:a>") && u.contains("float outputs:a"), "{u}");
|
||||
// An opaque textured face reads no opacity from its picture.
|
||||
let (_, plain) = textured(b"picture");
|
||||
let opaque = vec![square(RED), square([0.0, 0.0, 1.0, 1.0])];
|
||||
let u = text(&mesh_files("Box", "usda", &opaque, &plain).unwrap(), "Box.usda");
|
||||
assert!(!u.contains("outputs:a") && u.contains("float inputs:opacity = 1"), "{u}");
|
||||
let mtl = text(&mesh_files("Box", "obj", &opaque, &plain).unwrap(), "Box.mtl");
|
||||
assert!(!mtl.contains("map_d") && mtl.contains("Kd 1 1 1\nd 1\n"), "{mtl}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parts_sharing_a_picture_write_it_once() {
|
||||
let (mut parts, mut pictures) = textured(b"one");
|
||||
parts.push(square(BLUE));
|
||||
pictures.push(pictures[1].clone());
|
||||
assert_eq!(image_maps(&pictures), [false]);
|
||||
let files = mesh_files("Box", "obj", &parts, &pictures).unwrap();
|
||||
assert_eq!(files.len(), 3);
|
||||
assert_eq!(text(&files, "Box.mtl").matches("newmtl").count(), 2, "the blue parts share the textured material");
|
||||
assert_eq!(mesh_file_names("Box", "usda", &[false, true]).unwrap(), ["Box.usda", "Box-texture-1.png", "Box-texture-2.png"]);
|
||||
assert_eq!(mesh_file_names("A @b", "gltf", &[false, false]).unwrap(), ["A @b.gltf"]);
|
||||
assert_eq!(texture_name("A @b#c", 0), "A__b_c-texture-1.png");
|
||||
}
|
||||
|
||||
@@ -417,9 +417,13 @@ fn encode_carrying_at(
|
||||
}
|
||||
let (flat, flattened) = flatten_for(cmd, doc, set, p)?;
|
||||
vectorcraft_doc::cancel::check()?;
|
||||
if flattened {
|
||||
if let Some(o) = flattened {
|
||||
let kind = if set.standard.flattens() { set.standard.label() } else { set.compatibility.label() };
|
||||
notes.push(Note::loss(format!("transparency is flattened into opaque art and images ({kind} files have none): see the flattener preset")));
|
||||
let line_ppi = o.line_art_ppi.round() as u32;
|
||||
let grad_ppi = o.gradient_ppi.round() as u32;
|
||||
notes.push(Note::loss(format!(
|
||||
"transparency is flattened into opaque art and images ({kind} files have none) at {line_ppi} ppi line art and text, {grad_ppi} ppi gradients and meshes: see the flattener preset"
|
||||
)));
|
||||
}
|
||||
let r = super::super::rasterfx::export_pdf_with_report(flat.as_ref().unwrap_or(doc), &opts).map_err(|e| pdf_error(cmd, e))?;
|
||||
notes.extend(r.warnings.into_iter().map(Note::loss));
|
||||
@@ -438,9 +442,9 @@ pub const DEFAULT_FLATTENER: &str = "High Resolution";
|
||||
/// discarded overprints are dropped. Layers the pages leave out (non-printing ones, unless asked
|
||||
/// for) are left out of the flattening, hidden. → the document to write (`None`: `doc` as it is)
|
||||
/// and whether its transparency was flattened.
|
||||
fn flatten_for(cmd: &str, doc: &Document, set: &PdfSettings, p: &Value) -> Result<(Option<Document>, bool)> {
|
||||
fn flatten_for(cmd: &str, doc: &Document, set: &PdfSettings, p: &Value) -> Result<(Option<Document>, Option<FlattenOptions>)> {
|
||||
if !set.pdf13() {
|
||||
return Ok((None, false));
|
||||
return Ok((None, None));
|
||||
}
|
||||
let printed = if set.include_non_printing || set.create_layers { None } else { without_non_printing(&doc.layers) };
|
||||
let shown = printed.map(|layers| {
|
||||
@@ -456,8 +460,8 @@ fn flatten_for(cmd: &str, doc: &Document, set: &PdfSettings, p: &Value) -> Resul
|
||||
// its art: it is clipped to its regions (opaque inside them).
|
||||
o.clip_complex_regions = true;
|
||||
Ok(match flatten_document(shown.as_ref().unwrap_or(doc), &o)? {
|
||||
Some(flat) => (Some(flat), true),
|
||||
None => (shown, false),
|
||||
Some(flat) => (Some(flat), Some(o)),
|
||||
None => (shown, None),
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -500,6 +500,48 @@ pub(super) fn to_rgb(h: &Header<'_>, v: impl Fn(usize) -> f32, cmyk: &impl Fn([f
|
||||
}
|
||||
}
|
||||
|
||||
/// An opaque CMYK composite as its original 8- or 16-bit ink samples. Other modes,
|
||||
/// composites with transparency, and images beyond the native CMYK pixel or allocation limit return `None`.
|
||||
pub(super) fn decode_cmyk(bytes: &[u8], max_alloc: u64) -> Result<Option<craft_image_codecs::Image>, String> {
|
||||
use craft_image_codecs::{ChannelLayout, Image, SampleType};
|
||||
let mut r = Reader::new(bytes);
|
||||
let h = header(&mut r)?;
|
||||
if h.mode != Mode::Cmyk || (h.channels > 4 && merged_alpha(h.layers, h.psb)) {
|
||||
return Ok(None);
|
||||
}
|
||||
let pixels = u64::from(h.width) * u64::from(h.height);
|
||||
if pixels > vectorcraft_doc::cmyk::MAX_CMYK_PIXELS {
|
||||
return Ok(None);
|
||||
}
|
||||
let sample_bytes = usize::from(h.depth / 8);
|
||||
let samples = pixels * 4 * sample_bytes as u64;
|
||||
let icc = resources(h.resources, false)
|
||||
.find(|(id, _, _)| *id == 1039)
|
||||
.map(|(_, _, data)| data)
|
||||
.filter(|data| data.len() <= 16 << 20 && vectorcraft_doc::cmyk::icc_color_space(data) == Some(*b"CMYK"));
|
||||
if samples.saturating_mul(2).saturating_add(icc.map_or(0, |p| p.len() as u64)) > max_alloc {
|
||||
return Ok(None);
|
||||
}
|
||||
let count = pixels as usize;
|
||||
let data = channel_data(r.rest(), &h, 4, row_bytes(h.width as usize, h.depth))?;
|
||||
let mut out = Vec::with_capacity(samples as usize);
|
||||
for i in 0..count {
|
||||
for channel in 0..4 {
|
||||
let at = (channel * count + i) * sample_bytes;
|
||||
if h.depth == 8 {
|
||||
out.push(255 - data.get(at).copied().ok_or(TRUNCATED)?);
|
||||
} else {
|
||||
let pair = data.get(at..at + 2).ok_or(TRUNCATED)?.try_into().map_err(|_| TRUNCATED)?;
|
||||
out.extend((65535 - u16::from_be_bytes(pair)).to_ne_bytes());
|
||||
}
|
||||
}
|
||||
}
|
||||
let sample = if h.depth == 16 { SampleType::U16 } else { SampleType::U8 };
|
||||
let mut image = Image::from_raw(h.width, h.height, ChannelLayout::Cmyk, sample, out).map_err(|e| e.to_string())?;
|
||||
image.icc = icc.map(<[u8]>::to_vec);
|
||||
Ok(Some(image))
|
||||
}
|
||||
|
||||
/// A Photoshop document's merged image as straight RGBA. CMYK converts through `cmyk` (ink
|
||||
/// amounts 0..1 → sRGB). Fails, without allocating, when the image would need more than
|
||||
/// `max_alloc` bytes.
|
||||
|
||||
@@ -135,26 +135,25 @@ fn formats_list_use_artboards() {
|
||||
assert!(opts("vectorcraft").get("useArtboards").is_none());
|
||||
}
|
||||
|
||||
/// An export's reply gives what the file loses before its notes on the options, whatever order
|
||||
/// the encoder gave them: the WebP encoder notes that lossy WebP isn't applied before the export
|
||||
/// notes the type it drew in the fallback font. With only notes on the options, they keep their
|
||||
/// order.
|
||||
/// An export's reply gives what the file loses before its notes on the options: the type the
|
||||
/// export drew in the fallback font comes before the note on an option WebP doesn't read. With
|
||||
/// only notes on the options, they keep their order.
|
||||
#[test]
|
||||
fn what_the_file_loses_comes_before_a_note_on_the_options() {
|
||||
let lossy = "lossy WebP isn't available yet: the file is lossless (exact, but larger)";
|
||||
let unused = "`interlaced` was not used: WebP files don't read it";
|
||||
let warnings = |s: &mut Session, p: Value| -> Vec<String> {
|
||||
let r = s.execute("document.export", &p).unwrap();
|
||||
r["warnings"].as_array().unwrap().iter().filter_map(Value::as_str).map(str::to_string).collect()
|
||||
};
|
||||
let mut s = session(60.0, 40.0, 1);
|
||||
assert_eq!(warnings(&mut s, json!({"format": "webp", "lossless": false})), [lossy]);
|
||||
assert_eq!(warnings(&mut s, json!({"format": "webp", "interlaced": true})), [unused]);
|
||||
s.execute("text.create", &json!({"x": 5, "y": 20, "text": "Ab", "font": "Nonexistent Sans Probe"})).unwrap();
|
||||
let w = warnings(&mut s, json!({"format": "webp", "lossless": false}));
|
||||
let w = warnings(&mut s, json!({"format": "webp", "interlaced": true}));
|
||||
assert_eq!(w.len(), 2, "{w:?}");
|
||||
assert!(w[0].contains("fallback font") && w[0].contains("Nonexistent Sans Probe"), "{w:?}");
|
||||
assert_eq!(w[1], lossy);
|
||||
assert_eq!(w[1], unused);
|
||||
// document.serialize gives them in the same order.
|
||||
let r = s.execute("document.serialize", &json!({"format": "webp", "lossless": false})).unwrap();
|
||||
let r = s.execute("document.serialize", &json!({"format": "webp", "interlaced": true})).unwrap();
|
||||
assert_eq!(r["warnings"], json!(w));
|
||||
}
|
||||
|
||||
|
||||
@@ -97,6 +97,132 @@ fn every_colour_mode_and_depth_reads() {
|
||||
assert_eq!(pixels(&psd(1, 1, (1, 1), 8, 8, &[0; 40], &[], &[], &raw(&[&[64]]))), [[64, 64, 64, 255]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cmyk_psd_place_keeps_the_native_ink_samples() {
|
||||
let f = psd(1, 4, (2, 1), 8, 4, &[], &[], &[], &raw(&[&[191, 255], &[127, 0], &[63, 127], &[223, 0]]));
|
||||
let p = json!({"name": "inks.psd", "dataBase64": vectorcraft_format::base64_encode(&f)});
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 40, "height": 20})).unwrap();
|
||||
let info = s.execute("file.place.info", &p).unwrap();
|
||||
assert_eq!(info["colorMode"], "CMYK");
|
||||
let placed = s.execute("file.place", &p).unwrap();
|
||||
let id = NodeId(placed["ids"][0].as_u64().unwrap());
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let NodeKind::Image(im) = &d.node(id).unwrap().kind else { panic!("placed PSD is an image") };
|
||||
let blob = d.images.get(&im.key).unwrap();
|
||||
assert!(blob.is_cmyk());
|
||||
assert_eq!(blob.cmyk().unwrap().data, [64, 128, 192, 32, 0, 255, 128, 255]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cmyk_psd_native_budget_keeps_the_rgba_fallback_available() {
|
||||
let bytes = psd(1, 4, (2, 1), 16, 4, &[], &[], &[], &raw(&[&[0xff; 4], &[0xff; 4], &[0xff; 4], &[0; 4]]));
|
||||
assert!(super::psdread::decode_cmyk(&bytes, 24).unwrap().is_none());
|
||||
assert_eq!(decode(&bytes, 24, naive).unwrap().into_raw(), [0, 0, 0, 255, 0, 0, 0, 255]);
|
||||
assert!(decode(&bytes, 1, naive).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cmyk_psd_depth_and_compression_preserve_exact_samples() {
|
||||
for version in [1, 2] {
|
||||
for depth in [8, 16] {
|
||||
let values = if depth == 8 { [191u16, 127, 63, 223] } else { [0xcdef, 0x89ab, 0x4567, 0x0123] };
|
||||
let planes: Vec<Vec<u8>> = values.iter().map(|v| if depth == 8 { vec![*v as u8] } else { v.to_be_bytes().to_vec() }).collect();
|
||||
let uncompressed = planes.concat();
|
||||
for method in 0..=3u16 {
|
||||
let mut data = method.to_be_bytes().to_vec();
|
||||
match method {
|
||||
0 => data.extend(&uncompressed),
|
||||
1 => {
|
||||
for p in &planes {
|
||||
let count = (p.len() + 1) as u32;
|
||||
if version == 2 { data.extend(count.to_be_bytes()) } else { data.extend((count as u16).to_be_bytes()) }
|
||||
}
|
||||
for p in &planes {
|
||||
data.push((p.len() - 1) as u8);
|
||||
data.extend(p);
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
// One sample per row has the same bytes with or without prediction.
|
||||
let mut z = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default());
|
||||
std::io::Write::write_all(&mut z, &uncompressed).unwrap();
|
||||
data.extend(z.finish().unwrap());
|
||||
}
|
||||
}
|
||||
let bytes = psd(version, 4, (1, 1), depth, 4, &[], &[], &[], &data);
|
||||
let img = raster_image(&bytes).unwrap();
|
||||
assert!(img.blob.is_cmyk(), "version {version}, depth {depth}, compression {method}");
|
||||
assert_eq!(img.blob.is_cmyk16(), depth == 16);
|
||||
let decoded = craft_image_codecs::decode(&img.blob.bytes).unwrap();
|
||||
let expected: Vec<u8> =
|
||||
values.iter().flat_map(|v| if depth == 8 { vec![255 - *v as u8] } else { (65535 - v).to_ne_bytes().to_vec() }).collect();
|
||||
assert_eq!(decoded.data(), expected);
|
||||
assert!(super::psdread::decode_cmyk(&bytes, 1).unwrap().is_none());
|
||||
assert!(super::psdread::decode_cmyk(&bytes[..bytes.len() - data.len() + 2], 1 << 30).is_err());
|
||||
}
|
||||
}
|
||||
}
|
||||
let planes: [&[u8]; 5] = [&[255], &[255], &[255], &[255], &[128]];
|
||||
let saved = psd(1, 5, (1, 1), 8, 4, &[], &[], &[], &raw(&planes));
|
||||
assert!(raster_image(&saved).unwrap().blob.is_cmyk(), "a saved selection is not transparency");
|
||||
let alpha = psd(1, 5, (1, 1), 8, 4, &[], &[], &layer_count(-1, false), &raw(&planes));
|
||||
let img = raster_image(&alpha).unwrap();
|
||||
assert!(!img.blob.is_cmyk());
|
||||
assert_eq!(craft_image_codecs::decode(&img.blob.bytes).unwrap().to_rgba8()[3], 128);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cmyk_psd_links_keep_inks_profile_resolution_and_clipping() {
|
||||
let profile = vectorcraft_color::cms::icc_bytes(vectorcraft_color::cms::GENERIC_CMYK).unwrap();
|
||||
let mut res = Vec::new();
|
||||
res.extend((144u32 << 16).to_be_bytes());
|
||||
res.extend([0, 1, 0, 1]);
|
||||
res.extend((144u32 << 16).to_be_bytes());
|
||||
res.extend([0, 1, 0, 1]);
|
||||
let make = |clip: &[u8], ink: u8| {
|
||||
let resources = [resource(1039, b"", &profile), resource(1005, b"", &res), clip.to_vec()].concat();
|
||||
psd(1, 4, (2, 1), 8, 4, &[], &resources, &[], &raw(&[&[255 - ink; 2], &[127; 2], &[63; 2], &[223; 2]]))
|
||||
};
|
||||
let dir = vectorcraft_testkit::TempDir::new("psd-cmyk-links");
|
||||
let cut = write_file(&dir, "cut.psd", &make(&triangle_resources(), 64));
|
||||
let square = write_file(&dir, "square.psd", &make(&square_resources(), 96));
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 20, "height": 10, "colorMode": "cmyk"})).unwrap();
|
||||
assert_eq!(s.execute("file.place.info", &json!({"path": cut})).unwrap()["colorMode"], "CMYK");
|
||||
let r = s.execute("file.place", &json!({"path": cut, "at": [0.5, 0.25]})).unwrap();
|
||||
let group = NodeId(r["ids"][0].as_u64().unwrap());
|
||||
let id = r["image"].as_u64().unwrap();
|
||||
assert_eq!(r["width"], 1.0);
|
||||
assert_eq!(r["height"], 0.5);
|
||||
let check = |s: &mut Session, ink, linked| {
|
||||
let info = s.execute("links.info", &json!({"id": id})).unwrap();
|
||||
assert_eq!(info["colorMode"], "CMYK");
|
||||
assert_eq!(info["linked"], linked);
|
||||
assert_eq!(info["ppi"], json!([144.0, 144.0]));
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let NodeKind::Image(im) = &d.node(NodeId(id)).unwrap().kind else { panic!("placed image") };
|
||||
let blob = d.images.get(&im.key).unwrap();
|
||||
assert_eq!(blob.cmyk().unwrap().data, [ink, 128, 192, 32, ink, 128, 192, 32]);
|
||||
assert_eq!(blob.cmyk_icc_profile().as_deref(), Some(profile.as_ref()));
|
||||
assert_eq!(
|
||||
super::load::image_clip(blob),
|
||||
Some(clipping_path(&make(&if ink == 64 { triangle_resources() } else { square_resources() }, ink)).unwrap())
|
||||
);
|
||||
};
|
||||
check(&mut s, 64, true);
|
||||
let triangle = clip_group(&s.doc().unwrap().doc, group);
|
||||
s.execute("links.relink", &json!({"ids": [id], "path": square})).unwrap();
|
||||
check(&mut s, 96, true);
|
||||
assert_ne!(clip_group(&s.doc().unwrap().doc, group).0, triangle.0);
|
||||
std::fs::write(&square, make(&triangle_resources(), 64)).unwrap();
|
||||
s.execute("links.update", &json!({"ids": [id]})).unwrap();
|
||||
check(&mut s, 64, true);
|
||||
assert_eq!(clip_group(&s.doc().unwrap().doc, group), triangle);
|
||||
s.execute("links.embed", &json!({"ids": [id]})).unwrap();
|
||||
check(&mut s, 64, false);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transparency_comes_back_straight_and_extra_channels_without_it_stay_out() {
|
||||
// Half-transparent red, stored on white: (255, 127, 127) with alpha 128.
|
||||
|
||||
@@ -546,20 +546,19 @@ fn type_in_a_missing_family_is_named_once_for_every_format() {
|
||||
assert!(fallback[0].contains("Nonexistent Sans Probe"), "{fallback:?}");
|
||||
}
|
||||
|
||||
/// What a later file loses comes before a note on the options that an earlier file gave: the
|
||||
/// first artboard's WebP gives only the lossy WebP note, the second's also says its type doesn't
|
||||
/// fit.
|
||||
/// What a later file loses comes before a note on the options: the second artboard's WebP says
|
||||
/// its type doesn't fit, before the note on the row's option that WebP doesn't read.
|
||||
#[test]
|
||||
fn what_any_file_loses_comes_before_the_notes_on_the_options() {
|
||||
let mut s = session(2);
|
||||
let second = s.doc().unwrap().doc.artboards[1].rect;
|
||||
let area = json!({"width": 30, "height": 8});
|
||||
s.execute("text.create", &json!({"x": second.x0 + 2.0, "y": second.y0 + 2.0, "size": 12, "area": area, "text": "Ab\nCd\nEf\nGh"})).unwrap();
|
||||
let r = export(&mut s, json!({"formats": [{"format": "webp", "lossless": false}]}));
|
||||
let r = export(&mut s, json!({"formats": [{"format": "webp", "interlaced": true}]}));
|
||||
let warnings: Vec<&str> = r["warnings"].as_array().unwrap().iter().filter_map(Value::as_str).collect();
|
||||
assert_eq!(warnings.len(), 2, "{warnings:?}");
|
||||
assert!(warnings[0].contains("doesn't fit its frame"), "{warnings:?}");
|
||||
assert!(warnings[1].starts_with("lossy WebP"), "{warnings:?}");
|
||||
assert!(warnings[1].starts_with("`formats[0].interlaced` was not used"), "{warnings:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::json;
|
||||
use vectorcraft_doc::Document;
|
||||
use vectorcraft_doc::{Document, Node, NodeKind};
|
||||
|
||||
use super::*;
|
||||
|
||||
@@ -212,6 +212,44 @@ fn a_chosen_artboard_s_svg_keeps_nested_brush_art_but_not_unpainted_or_clipped_a
|
||||
assert!(kept.node(compounds[1]).is_some(), "a compound path that is brushed itself");
|
||||
}
|
||||
|
||||
/// The art over an artboard, among 300 instances with drop shadows and 2,000 symbols, is found
|
||||
/// reading the symbol list once, and keeps the instances over it.
|
||||
#[test]
|
||||
fn art_over_an_artboard_reads_the_symbol_list_once() {
|
||||
let mut d = Document::new(100.0, 100.0);
|
||||
let square = |d: &mut Document, side: f64| {
|
||||
let r = vectorcraft_geom::Rect::new(-side, -side, side, side);
|
||||
let ap =
|
||||
vectorcraft_doc::Appearance::basic(vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK), vectorcraft_color::Paint::None, 0.0);
|
||||
Arc::new(Node::path(d.alloc_id(), vectorcraft_geom::shapes::rectangle(r), ap))
|
||||
};
|
||||
for i in 0..2000 {
|
||||
let art = square(&mut d, 0.5);
|
||||
d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: format!("Filler {i}"), art });
|
||||
}
|
||||
let art = square(&mut d, 2.0);
|
||||
d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Mark".into(), art });
|
||||
let layer = d.layers[0].id;
|
||||
// Twenty rows of 15: the first ten over the artboard, the rest below it.
|
||||
let ids: Vec<_> = (0..300)
|
||||
.map(|i| {
|
||||
let xf = vectorcraft_geom::Affine::translate((f64::from(i % 15) * 6.0 + 5.0, f64::from(i / 15) * 10.0 + 5.0));
|
||||
let mut n = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Mark".into(), xf });
|
||||
n.appearance.effects.push(vectorcraft_doc::Effect {
|
||||
id: "stylize.dropShadow".into(),
|
||||
params: json!({"x": 1, "y": 1, "blur": 0}),
|
||||
visible: true,
|
||||
});
|
||||
d.insert(Some(layer), usize::MAX, n).unwrap()
|
||||
})
|
||||
.collect();
|
||||
let before = vectorcraft_doc::symbols_read();
|
||||
let kept = export::art_over(&d, d.artboards[0].rect, &mut vectorcraft_render::Renderer::new());
|
||||
let read = vectorcraft_doc::symbols_read() - before;
|
||||
assert!(read <= d.symbols.len(), "{read} symbols read, {} in the document", d.symbols.len());
|
||||
assert_eq!(ids.iter().filter(|id| kept.node(**id).is_some()).count(), 150);
|
||||
}
|
||||
|
||||
/// #3544: an SVG of one artboard on its own (an `artboard` or `range`, Export for Screens, an asset)
|
||||
/// has the artboard's (or asset's) name as `<title>`; Save's SVG and Export for Screens' Full
|
||||
/// Document keep the document's.
|
||||
|
||||
@@ -53,41 +53,115 @@ fn text_export_writes_the_stories_in_stacking_order() {
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
/// The chunk types of RIFF WebP file `file`, in order.
|
||||
fn webp_chunks(file: &[u8]) -> Vec<[u8; 4]> {
|
||||
assert_eq!((&file[..4], &file[8..12]), (&b"RIFF"[..], &b"WEBP"[..]));
|
||||
let mut chunks = Vec::new();
|
||||
let mut at = 12;
|
||||
while at + 8 <= file.len() {
|
||||
let len = u32::from_le_bytes([file[at + 4], file[at + 5], file[at + 6], file[at + 7]]) as usize;
|
||||
chunks.push([file[at], file[at + 1], file[at + 2], file[at + 3]]);
|
||||
at += 8 + len + len % 2;
|
||||
}
|
||||
chunks
|
||||
}
|
||||
|
||||
/// The size and straight RGBA pixels of image file `file`.
|
||||
fn rgba(file: &[u8]) -> (u32, u32, Vec<u8>) {
|
||||
let img = craft_image_codecs::decode(file).unwrap();
|
||||
let (w, h) = img.dimensions();
|
||||
(w, h, img.to_rgba8())
|
||||
}
|
||||
|
||||
/// A 120 × 80 pt document filled with a grid of rectangles in 96 colors.
|
||||
fn varied_art() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 120, "height": 80})).unwrap();
|
||||
for row in 0..8 {
|
||||
for col in 0..12 {
|
||||
s.execute("shape.rectangle", &json!({"x": col * 10, "y": row * 10, "width": 10, "height": 10})).unwrap();
|
||||
let color = format!("#{:02x}{:02x}{:02x}", col * 21, row * 32, (col * 7 + row * 23) % 256);
|
||||
s.execute("paint.setFill", &json!({"color": color})).unwrap();
|
||||
}
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn webp_is_lossless_and_says_so_when_lossy_is_asked_for() {
|
||||
fn webp_is_lossless_by_default_and_lossy_when_asked() {
|
||||
let mut s = varied_art();
|
||||
let export = |s: &mut Session, p: Value| -> (Vec<u8>, Value) {
|
||||
let r = s.execute("document.export", &merge(json!({"format": "webp", "background": "white"}), p)).unwrap();
|
||||
(b64(&r), r["warnings"].clone())
|
||||
};
|
||||
let (lossless, warnings) = export(&mut s, json!({}));
|
||||
assert_eq!(webp_chunks(&lossless), [*b"VP8L"], "lossless by default");
|
||||
assert_eq!(warnings, json!([]));
|
||||
// Quality doesn't change a lossless file.
|
||||
assert_eq!(export(&mut s, json!({"lossless": true, "quality": 10})).0, lossless);
|
||||
|
||||
let (lossy, warnings) = export(&mut s, json!({"lossless": false}));
|
||||
assert_eq!(webp_chunks(&lossy), [*b"VP8 "], "opaque art is a plain lossy file");
|
||||
assert_eq!(warnings, json!([]), "no note: the file is lossy");
|
||||
assert_eq!(export(&mut s, json!({"lossless": false, "quality": 90})).0, lossy, "quality 90 by default");
|
||||
// At quality 90 each channel stays within 4 levels of the exact pixels on average.
|
||||
let ((w, h, exact), (lw, lh, near)) = (rgba(&lossless), rgba(&lossy));
|
||||
assert_eq!((lw, lh), (w, h));
|
||||
assert_eq!((w, h), (120, 80));
|
||||
let diff: u64 = exact.iter().zip(&near).map(|(a, b)| u64::from(a.abs_diff(*b))).sum();
|
||||
let mean = diff as f64 / exact.len() as f64;
|
||||
assert!(mean <= 4.0, "mean difference {mean}");
|
||||
// Lower quality, smaller file.
|
||||
let low = export(&mut s, json!({"lossless": false, "quality": 10})).0;
|
||||
let high = export(&mut s, json!({"lossless": false, "quality": 95})).0;
|
||||
assert_eq!(webp_chunks(&low), [*b"VP8 "]);
|
||||
assert!(low.len() < high.len(), "{} vs {} bytes", low.len(), high.len());
|
||||
for q in [0, 100] {
|
||||
assert_eq!(webp_chunks(&export(&mut s, json!({"lossless": false, "quality": q})).0), [*b"VP8 "], "quality {q}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lossy_webp_keeps_translucent_pixels() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 30, "height": 20})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 2, "y": 2, "width": 10, "height": 10})).unwrap();
|
||||
let r = s.execute("document.export", &json!({"format": "webp"})).unwrap();
|
||||
let file = b64(&r);
|
||||
assert_eq!((&file[..4], &file[8..12], &file[12..16]), (&b"RIFF"[..], &b"WEBP"[..], &b"VP8L"[..]), "lossless bitstream");
|
||||
assert_eq!(r["warnings"], json!([]));
|
||||
let r = s.execute("document.export", &json!({"format": "webp", "lossless": false, "quality": 60, "background": "black"})).unwrap();
|
||||
assert_eq!(&b64(&r)[12..16], b"VP8L");
|
||||
assert!(r["warnings"][0].as_str().unwrap().contains("lossless"), "{r}");
|
||||
assert_eq!(
|
||||
craft_image_codecs::decode(&b64(&r))
|
||||
.map(|__cimg| {
|
||||
let (__w, __h) = __cimg.dimensions();
|
||||
match (__cimg.layout(), __cimg.sample_type()) {
|
||||
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
|
||||
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
|
||||
}
|
||||
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
|
||||
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
|
||||
}
|
||||
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
|
||||
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
|
||||
}
|
||||
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
|
||||
}
|
||||
})
|
||||
.unwrap()
|
||||
.to_rgba8()
|
||||
.get_pixel(29, 19)
|
||||
.0,
|
||||
[0, 0, 0, 255]
|
||||
);
|
||||
s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 20, "height": 20})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap();
|
||||
s.execute("transparency.set", &json!({"opacity": 50})).unwrap();
|
||||
let file = |s: &mut Session, lossless: bool| b64(&s.execute("document.export", &json!({"format": "webp", "lossless": lossless})).unwrap());
|
||||
let (lossless, lossy) = (file(&mut s, true), file(&mut s, false));
|
||||
assert_eq!(webp_chunks(&lossy), [*b"VP8X", *b"ALPH", *b"VP8 "]);
|
||||
let ((w, h, exact), (lw, lh, near)) = (rgba(&lossless), rgba(&lossy));
|
||||
assert_eq!((lw, lh), (w, h));
|
||||
let at = |px: &[u8], x: u32, y: u32| -> [u8; 4] {
|
||||
let i = 4 * (y * w + x) as usize;
|
||||
[px[i], px[i + 1], px[i + 2], px[i + 3]]
|
||||
};
|
||||
// The alpha is written exactly: half covered under the rectangle, clear past it.
|
||||
let alphas = |px: &[u8]| px.chunks(4).map(|p| p[3]).collect::<Vec<u8>>();
|
||||
assert_eq!(alphas(&near), alphas(&exact));
|
||||
assert!((120..=135).contains(&at(&near, 5, 5)[3]), "{:?}", at(&near, 5, 5));
|
||||
assert_eq!(at(&near, 28, 10)[3], 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn webp_quality_out_of_its_range_is_refused() {
|
||||
let mut s = varied_art();
|
||||
for q in [json!(101), json!(255), json!(256), json!(-1), json!(60.5), json!("high"), json!(true)] {
|
||||
let p = json!({"format": "webp", "lossless": false, "quality": q});
|
||||
let e = s.execute("document.export", &p).unwrap_err().to_string();
|
||||
assert!(e.contains("quality"), "{q}: {e}");
|
||||
// In Export for Screens too, in a row or in the format's settings.
|
||||
let row = json!({"formats": [{"format": "webp", "lossless": false, "quality": q}]});
|
||||
assert!(s.execute("document.exportForScreens", &row).is_err(), "{q}");
|
||||
let settings = json!({"formats": [{"format": "webp"}], "settings": {"webp": {"lossless": false, "quality": q}}});
|
||||
assert!(s.execute("document.exportForScreens", &settings).is_err(), "{q}");
|
||||
}
|
||||
// A lossless file refuses it as well: the value is not a WebP quality.
|
||||
assert!(s.execute("document.export", &json!({"format": "webp", "quality": 101})).is_err());
|
||||
let r = s.execute("document.exportForScreens", &json!({"formats": [{"format": "webp", "lossless": false, "quality": 100}]})).unwrap();
|
||||
let file = b64(&r["files"][0]);
|
||||
assert_eq!(webp_chunks(&file), [*b"VP8 "]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -247,10 +247,11 @@ impl Resources {
|
||||
fn expand(&mut self, d: &Document) {
|
||||
let mut symbols: Vec<String> = self.symbols.iter().cloned().collect();
|
||||
let mut patterns: Vec<String> = self.patterns.iter().cloned().collect();
|
||||
let boxes = d.symbol_boxes();
|
||||
while !symbols.is_empty() || !patterns.is_empty() {
|
||||
let mut more = Resources::default();
|
||||
for name in symbols.drain(..) {
|
||||
if let Some(sym) = d.symbols.iter().find(|sym| sym.name == name) {
|
||||
if let Some(sym) = boxes.symbol(&name) {
|
||||
more.add(&sym.art);
|
||||
}
|
||||
}
|
||||
@@ -511,7 +512,7 @@ pub(super) fn art_fonts(d: &Document, art: &[Node]) -> BTreeSet<UsedFont> {
|
||||
/// art of a placed document (`d` as [`Document::with_placed_art`] gives it, for that art's
|
||||
/// resources).
|
||||
pub(super) fn printed_type(d: &Document, layers: &[Arc<Node>], areas: &[Rect]) -> (BTreeSet<UsedFont>, BTreeSet<NodeId>) {
|
||||
let mut walk = Printed { d, own: true, fonts: BTreeSet::new(), overflow: BTreeSet::new(), symbols: BTreeSet::new(), patterns: BTreeSet::new() };
|
||||
let mut walk = Printed::new(d);
|
||||
for l in layers {
|
||||
walk.node(l, Some(areas));
|
||||
}
|
||||
@@ -523,7 +524,7 @@ pub(super) fn printed_type(d: &Document, layers: &[Arc<Node>], areas: &[Rect]) -
|
||||
/// found as [`printed_type`] finds them for Print: visible objects of the document that aren't on
|
||||
/// a template layer.
|
||||
pub(super) fn export_overflow_warning(d: &Document, layers: &[Arc<Node>], areas: Option<&[Rect]>) -> Option<String> {
|
||||
let mut walk = Printed { d, own: true, fonts: BTreeSet::new(), overflow: BTreeSet::new(), symbols: BTreeSet::new(), patterns: BTreeSet::new() };
|
||||
let mut walk = Printed::new(d);
|
||||
for l in layers {
|
||||
walk.node(l, areas);
|
||||
}
|
||||
@@ -534,6 +535,9 @@ pub(super) fn export_overflow_warning(d: &Document, layers: &[Arc<Node>], areas:
|
||||
/// The walk of [`printed_type`].
|
||||
struct Printed<'a> {
|
||||
d: &'a Document,
|
||||
/// `d`'s symbols, found by name. Each object is measured in boxes of its own made from these
|
||||
/// ([`vectorcraft_doc::SymbolBoxes::unmeasured`]).
|
||||
boxes: vectorcraft_doc::SymbolBoxes<'a>,
|
||||
/// Whether the walk is among the objects of the document, not in art drawn for one.
|
||||
own: bool,
|
||||
fonts: BTreeSet<UsedFont>,
|
||||
@@ -544,7 +548,13 @@ struct Printed<'a> {
|
||||
patterns: BTreeSet<String>,
|
||||
}
|
||||
|
||||
impl Printed<'_> {
|
||||
impl<'a> Printed<'a> {
|
||||
/// A walk of `d` among its own objects, nothing found yet.
|
||||
fn new(d: &'a Document) -> Self {
|
||||
let boxes = d.symbol_boxes();
|
||||
Self { d, boxes, own: true, fonts: BTreeSet::new(), overflow: BTreeSet::new(), symbols: BTreeSet::new(), patterns: BTreeSet::new() }
|
||||
}
|
||||
|
||||
/// Adds the fonts of `n` and its descendants that print, and the ids of those that don't fit
|
||||
/// while [`Printed::own`] is set: those whose bounds meet one of `areas`, or with `None` (in the
|
||||
/// art of a symbol, opacity mask, pattern or placed document, in brush pieces, or in a live
|
||||
@@ -625,7 +635,7 @@ impl Printed<'_> {
|
||||
let clipped = match (clip, areas) {
|
||||
(false, _) => None,
|
||||
(true, Some(a)) => Some(self.clip(n, a)),
|
||||
(true, None) => vectorcraft_render::painted_bounds(self.d, n).map(|c| vec![c]),
|
||||
(true, None) => vectorcraft_render::painted_bounds_with(&self.boxes.unmeasured(), n).map(|c| vec![c]),
|
||||
};
|
||||
for c in children {
|
||||
self.node(c, clipped.as_deref().or(areas));
|
||||
@@ -641,9 +651,8 @@ impl Printed<'_> {
|
||||
|
||||
/// Adds the fonts of symbol `name`'s art, the first time it is shown.
|
||||
fn symbol(&mut self, name: &str) {
|
||||
let d = self.d;
|
||||
if self.symbols.insert(name.to_string())
|
||||
&& let Some(s) = d.symbols.iter().find(|s| s.name == name)
|
||||
&& let Some(s) = self.boxes.symbol(name)
|
||||
{
|
||||
self.art(&s.art);
|
||||
}
|
||||
@@ -660,12 +669,13 @@ impl Printed<'_> {
|
||||
|
||||
/// Whether what `n` paints, its effects applied, meets one of `areas`.
|
||||
fn meets(&self, n: &Node, areas: &[Rect]) -> bool {
|
||||
vectorcraft_render::painted_bounds(self.d, n).is_some_and(|b| areas.iter().any(|r| b.intersect(*r).area() > 0.0 || r.contains_rect(b)))
|
||||
vectorcraft_render::painted_bounds_with(&self.boxes.unmeasured(), n)
|
||||
.is_some_and(|b| areas.iter().any(|r| b.intersect(*r).area() > 0.0 || r.contains_rect(b)))
|
||||
}
|
||||
|
||||
/// The parts of `areas` inside the bounds of clip group `n` (its clipping path's).
|
||||
fn clip(&self, n: &Node, areas: &[Rect]) -> Vec<Rect> {
|
||||
let Some(c) = vectorcraft_render::painted_bounds(self.d, n) else { return areas.to_vec() };
|
||||
let Some(c) = vectorcraft_render::painted_bounds_with(&self.boxes.unmeasured(), n) else { return areas.to_vec() };
|
||||
areas.iter().filter(|r| c.intersect(**r).area() > 0.0 || r.contains_rect(c)).map(|r| r.intersect(c)).collect()
|
||||
}
|
||||
}
|
||||
@@ -2378,4 +2388,40 @@ mod dirty_tests {
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(!s.doc().unwrap().is_dirty(), "back to the saved state");
|
||||
}
|
||||
|
||||
/// The walk Print and the exports make over 300 instances with drop shadows, among 2,000
|
||||
/// symbols, reads the symbol list once to find their symbols.
|
||||
#[test]
|
||||
fn printed_type_reads_the_symbol_list_once() {
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
for i in 0..2000 {
|
||||
let art = Node::path(
|
||||
d.alloc_id(),
|
||||
vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 1.0, 1.0)),
|
||||
vectorcraft_doc::Appearance::basic(Paint::None, Paint::None, 0.0),
|
||||
);
|
||||
d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: format!("Filler {i}"), art: Arc::new(art) });
|
||||
}
|
||||
let art = Node::path(
|
||||
d.alloc_id(),
|
||||
vectorcraft_geom::shapes::rectangle(Rect::new(-10.0, -10.0, 10.0, 10.0)),
|
||||
vectorcraft_doc::Appearance::basic(Paint::solid(vectorcraft_color::Color::BLACK), Paint::None, 0.0),
|
||||
);
|
||||
d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Mark".into(), art: Arc::new(art) });
|
||||
let l = d.layers[0].id;
|
||||
for i in 0..300 {
|
||||
let xf = vectorcraft_geom::Affine::translate((f64::from(i % 20) * 10.0, f64::from(i / 20) * 10.0));
|
||||
let mut n = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Mark".into(), xf });
|
||||
n.appearance.effects.push(vectorcraft_doc::Effect {
|
||||
id: "stylize.dropShadow".into(),
|
||||
params: json!({"x": 1, "y": 1, "blur": 0}),
|
||||
visible: true,
|
||||
});
|
||||
d.insert(Some(l), usize::MAX, n).unwrap();
|
||||
}
|
||||
let before = vectorcraft_doc::symbols_read();
|
||||
printed_type(&d, &d.layers, &[Rect::new(0.0, 0.0, 100.0, 100.0)]);
|
||||
let read = vectorcraft_doc::symbols_read() - before;
|
||||
assert!(read <= d.symbols.len(), "{read} symbols read, {} in the document", d.symbols.len());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -713,12 +713,12 @@ type FileClip = (PathData, FillRule);
|
||||
|
||||
/// The clipping path the file of image content `blob` draws it through, in its pixel space, as it
|
||||
/// was kept when the file was read: a DCS file's ([`ImageBlob::separated_clip`]) or a PSD or PSB
|
||||
/// file's ([`fileio::png_clip`]).
|
||||
/// file's ([`fileio::image_clip`]).
|
||||
fn file_clip(blob: &ImageBlob) -> Option<FileClip> {
|
||||
if let Some(path) = blob.separated_clip() {
|
||||
return Some((path, FillRule::NonZero));
|
||||
}
|
||||
(blob.mime == "image/png").then(|| fileio::png_clip(&blob.bytes)).flatten().map(|path| (path, FillRule::EvenOdd))
|
||||
fileio::image_clip(blob).map(|path| (path, FillRule::EvenOdd))
|
||||
}
|
||||
|
||||
/// What happens to the clip of an object a link update remakes.
|
||||
|
||||
@@ -357,6 +357,7 @@ pub(super) fn isolate(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
&& prev != isolation
|
||||
{
|
||||
crate::cmd::settle_interaction(s)?;
|
||||
add_drawn_live_paint(s, prev, Some(isolation))?;
|
||||
let st = s.doc_mut()?;
|
||||
crate::cmd::distortcmds::finish_edit_text(st, prev);
|
||||
}
|
||||
@@ -369,6 +370,19 @@ pub(super) fn isolate(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
ok()
|
||||
}
|
||||
|
||||
/// Leaving isolation mode in `isolated` for `next` (None: out of isolation mode) adds the paths drawn
|
||||
/// in the Live Paint group isolation put new art in to that group, as `livePaint.merge` does, in one
|
||||
/// undo step ([`crate::cmd::buildcmds::merge_drawn_in_isolation`]), unless `next` is that group or is
|
||||
/// inside it; → the group when paths were added.
|
||||
fn add_drawn_live_paint(s: &mut Session, isolated: NodeId, next: Option<NodeId>) -> Result<Option<NodeId>> {
|
||||
let d = &s.doc()?.doc;
|
||||
let Some(g) = crate::cmd::buildcmds::isolated_live_paint(d, isolated) else { return Ok(None) };
|
||||
if next.is_some_and(|n| d.ancestry(n).is_some_and(|a| a.contains(&g))) {
|
||||
return Ok(None);
|
||||
}
|
||||
Ok(crate::cmd::buildcmds::merge_drawn_in_isolation(s, g)?.then_some(g))
|
||||
}
|
||||
|
||||
pub(super) fn exit_isolation(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// Opacity mask editing, pattern editing and symbol editing isolate their editing layer. Leaving
|
||||
// isolation mode then leaves that mode, as Stop Editing Opacity Mask and the isolation bar's
|
||||
@@ -378,10 +392,11 @@ pub(super) fn exit_isolation(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
&& let Some(inner) = st.isolation.filter(|i| *i != layer && st.doc.ancestry(*i).is_some_and(|a| a.contains(&layer)))
|
||||
{
|
||||
crate::cmd::settle_interaction(s)?;
|
||||
let left = add_drawn_live_paint(s, inner, Some(layer))?.unwrap_or(inner);
|
||||
let st = s.doc_mut()?;
|
||||
crate::cmd::distortcmds::finish_edit_text(st, inner);
|
||||
st.isolation = Some(layer);
|
||||
st.selection.set([inner]);
|
||||
st.selection.set([left]);
|
||||
st.revision += 1;
|
||||
return ok();
|
||||
}
|
||||
@@ -396,6 +411,8 @@ pub(super) fn exit_isolation(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
};
|
||||
if let Some(leave_mode) = leave_mode {
|
||||
if let Some(i) = st.isolation {
|
||||
crate::cmd::settle_interaction(s)?;
|
||||
add_drawn_live_paint(s, i, None)?;
|
||||
crate::cmd::distortcmds::finish_edit_text(s.doc_mut()?, i);
|
||||
}
|
||||
leave_mode(s, p)?;
|
||||
@@ -405,10 +422,11 @@ pub(super) fn exit_isolation(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let prev = s.active().and_then(|d| d.isolation);
|
||||
if let Some(i) = prev {
|
||||
crate::cmd::settle_interaction(s)?;
|
||||
let left = add_drawn_live_paint(s, i, None)?.unwrap_or(i);
|
||||
let st = s.doc_mut()?;
|
||||
st.isolation = None;
|
||||
crate::cmd::distortcmds::finish_edit_text(st, i);
|
||||
let target = st.doc.parent_of(i).filter(|p| st.doc.node(*p).is_some_and(|n| n.extras().shaper.is_some())).unwrap_or(i);
|
||||
let target = st.doc.parent_of(left).filter(|p| st.doc.node(*p).is_some_and(|n| n.extras().shaper.is_some())).unwrap_or(left);
|
||||
st.selection.set([target]);
|
||||
// A guide path isolated while Lock Guides is on isn't selected (#1534).
|
||||
crate::deselect_hidden(&menu, &st.doc, &mut st.selection);
|
||||
|
||||
@@ -56,6 +56,7 @@ pub(crate) fn object_bounds_transform(s: &Session, p: &Value, id: NodeId) -> Res
|
||||
/// direct-selected anchors are what changes ([`Bounds::Anchors`]).
|
||||
fn bounds_transform(s: &Session, p: &Value, ids: Vec<NodeId>, least: f64, anchors: bool) -> Result<Bounds> {
|
||||
check_numbers(p, &["x", "y", "width", "height", "reference"], "object.setBounds")?;
|
||||
let refi = reference_index(p)?;
|
||||
let st = s.doc()?;
|
||||
check_switches(p, &TRANSFORM_SWITCHES, "object.setBounds")?;
|
||||
check_switches(p, &["proportional"], "object.setBounds")?;
|
||||
@@ -90,7 +91,6 @@ fn bounds_transform(s: &Session, p: &Value, ids: Vec<NodeId>, least: f64, anchor
|
||||
let margins = |b: Rect| [g.x0 - b.x0, g.y0 - b.y0, b.x1 - g.x1, b.y1 - g.y1];
|
||||
let (m, all) = (margins(vs), margins(v));
|
||||
let fixed = [all[0] - m[0], all[1] - m[1], all[2] - m[2], all[3] - m[3]];
|
||||
let refi = p.get("reference").and_then(Value::as_u64).unwrap_or(4).min(8) as usize;
|
||||
let rp = vectorcraft_geom::reference_point(v, refi);
|
||||
let (w, h) = wanted_size(p, v);
|
||||
// The geometric scale that gives the visual size: margins grow by the strokes' scale `f`. It is
|
||||
@@ -262,7 +262,7 @@ fn wanted_size(p: &Value, b: Rect) -> (f64, f64) {
|
||||
/// `b`, the box around the anchors (and the objects selected whole) square to the page, and only
|
||||
/// the anchors, their handles with them, and those objects move or scale.
|
||||
fn set_anchor_bounds(s: &mut Session, p: &Value, ids: Vec<NodeId>, b: Rect) -> Result<Value> {
|
||||
let refi = p.get("reference").and_then(Value::as_u64).unwrap_or(4).min(8) as usize;
|
||||
let refi = reference_index(p)?;
|
||||
let rp = vectorcraft_geom::reference_point(b, refi);
|
||||
let (w, h) = wanted_size(p, b);
|
||||
// A single anchor, or anchors in a line, have no size to scale on that side.
|
||||
@@ -272,6 +272,14 @@ fn set_anchor_bounds(s: &mut Session, p: &Value, ids: Vec<NodeId>, b: Rect) -> R
|
||||
apply_transform(s, "Transform", ids, Affine::translate(to - rp) * scale, p, true)
|
||||
}
|
||||
|
||||
fn reference_index(p: &Value) -> Result<usize> {
|
||||
let reference = crate::cmd::number_or(p, "reference", 4.0, "object.setBounds")?;
|
||||
if !reference.is_finite() || reference < 0.0 || reference.fract() != 0.0 {
|
||||
return Err(crate::cmd::bad("object.setBounds", "`reference` must be a whole number"));
|
||||
}
|
||||
Ok(reference.min(8.0) as usize)
|
||||
}
|
||||
|
||||
/// The visual box of `ids` square to `frame`, as [`Document::oriented_bounds`] measures it, with
|
||||
/// symbol instances measured without the strokes in their art
|
||||
/// ([`vectorcraft_doc::SymbolBoxes::without_art_strokes`]).
|
||||
|
||||
@@ -245,7 +245,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
crate::cmd::maskedit::outside_mask_editing,
|
||||
isolate
|
||||
),
|
||||
cmd!("object.exitIsolation", "Exit Isolation Mode", [], None, "{}", has_doc, exit_isolation),
|
||||
cmd!(
|
||||
"object.exitIsolation",
|
||||
"Exit Isolation Mode",
|
||||
[],
|
||||
None,
|
||||
"{} leave isolation mode; leaving an isolated Live Paint group adds the paths, compound paths and groups of them drawn in it (shown and unlocked with everything in them) to the group as livePaint.merge does, in one undo step, and leaves type, images and other objects in it as they are; object.isolate on a level outside the group does the same",
|
||||
has_doc,
|
||||
exit_isolation
|
||||
),
|
||||
cmd!(
|
||||
"object.setProps",
|
||||
"Object Properties",
|
||||
@@ -287,7 +295,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Set Bounds",
|
||||
[],
|
||||
None,
|
||||
"{x?, y?, width?, height?, reference?: 0..8 (9-point grid; a number past 8 is read as 8), proportional?, strokes?, corners?, copy?: bool, patterns?: bool (Transform Patterns), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size), objects?: bool (Transform Objects, as object.move)} (Transform panel; width/height and the reference point follow the bounding box, rotated with rotated objects; x, y are page coordinates; with Use Preview Bounds the values measure the visual bounds; with the typeGlyphBounds preference, each point type object selected as an object (not inside a selected group) is measured by its glyphs' ink (underline and strikethrough included), which the scale gives the size asked for; strokes/corners as object.scale; with anchor points selected (Direct Selection) and no copy, the values are the box around those points, square to the page, and only they move or scale, as with object.move (#1824))",
|
||||
"{x?, y?, width?, height?, reference?: whole number >= 0 (9-point grid 0..8; 0.0 equals 0; a whole number past 8 is read as 8; omitted/null: center, 4), proportional?, strokes?, corners?, copy?: bool, patterns?: bool (Transform Patterns), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size), objects?: bool (Transform Objects, as object.move)} (Transform panel; width/height and the reference point follow the bounding box, rotated with rotated objects; x, y are page coordinates; with Use Preview Bounds the values measure the visual bounds; with the typeGlyphBounds preference, each point type object selected as an object (not inside a selected group) is measured by its glyphs' ink (underline and strikethrough included), which the scale gives the size asked for; strokes/corners as object.scale; with anchor points selected (Direct Selection) and no copy, the values are the box around those points, square to the page, and only they move or scale, as with object.move (#1824))",
|
||||
has_selection,
|
||||
set_bounds
|
||||
),
|
||||
|
||||
@@ -1276,7 +1276,7 @@ fn aligned_between(tab: &vectorcraft_doc::TabStop, from: f64, x: f64) -> bool {
|
||||
|
||||
/// The frames of the story that type object `id` belongs to (its thread in thread order, else `id`
|
||||
/// alone), each with the length of its text in bytes.
|
||||
fn story_frames(s: &Session, id: NodeId) -> Vec<(NodeId, usize)> {
|
||||
pub(crate) fn story_frames(s: &Session, id: NodeId) -> Vec<(NodeId, usize)> {
|
||||
let Some(st) = s.active() else { return vec![] };
|
||||
let d = &st.doc;
|
||||
let frames = d.text_threads.iter().find(|thread| thread.contains(&id)).cloned().unwrap_or_else(|| vec![id]);
|
||||
@@ -1314,6 +1314,16 @@ fn move_editing_selection(
|
||||
at + inserted.iter().filter(|(b, _)| *b <= at).map(|(_, n)| n).sum::<usize>()
|
||||
};
|
||||
let (anchor, caret) = (story(anchor), story(caret));
|
||||
select_story_range(s, id, anchor, caret)
|
||||
}
|
||||
|
||||
/// The Type tool's anchor and caret become story positions `anchor` and `caret` of the story that
|
||||
/// frame `id` belongs to, as its frames are now. The caret stays in `id` while its place is there,
|
||||
/// and else goes to the frame that holds it, with the anchor in that frame; that frame becomes the
|
||||
/// selection when it was not selected.
|
||||
pub(crate) fn select_story_range(s: &mut Session, id: NodeId, anchor: usize, caret: usize) -> Result<()> {
|
||||
let start_of = |frames: &[(NodeId, usize)], f: NodeId| frames.iter().take_while(|(g, _)| *g != f).map(|(_, n)| n).sum::<usize>();
|
||||
let len_of = |frames: &[(NodeId, usize)], f: NodeId| frames.iter().find(|(g, _)| *g == f).map_or(0, |(_, n)| *n);
|
||||
let after = story_frames(s, id);
|
||||
let fits = |f: NodeId| (start_of(&after, f)..=start_of(&after, f) + len_of(&after, f)).contains(&caret);
|
||||
let frame = if fits(id) { Some(id) } else { after.iter().map(|(f, _)| *f).find(|f| fits(*f)) };
|
||||
|
||||
@@ -649,6 +649,7 @@ pub const UNCHECKED: &[&str] = &[
|
||||
"transparency.setOpacityMask",
|
||||
"transparency.unlinkOpacityMask",
|
||||
"type.pathOptions",
|
||||
"webExport.optimizeToFileSize",
|
||||
"webExport.presets.save",
|
||||
"webExport.settings",
|
||||
];
|
||||
@@ -663,18 +664,28 @@ fn pdf_option_tree() -> Value {
|
||||
tree
|
||||
}
|
||||
|
||||
/// The parameter error of command `id` for `key`, a key with the objects it is in (`marks.ofset`),
|
||||
/// when a key those objects take is near it: `near`, written the same way (`marks.offset`). Each
|
||||
/// is one value of the message, so a catalog can match the message and translate it.
|
||||
fn misspelled(id: &str, key: &str, near: &str) -> crate::EngineError {
|
||||
bad(id, format!("unknown parameter `{key}`; did you mean `{near}`?"))
|
||||
}
|
||||
|
||||
/// `given`, the object at `within` (`marks.`), has only keys of `schema`, the objects inside it too.
|
||||
fn check_option_tree(id: &str, within: &str, given: &serde_json::Map<String, Value>, schema: &serde_json::Map<String, Value>) -> Result<()> {
|
||||
for (key, value) in given {
|
||||
match (schema.get(key), value) {
|
||||
(None, _) => {
|
||||
let keys: Vec<&str> = schema.keys().map(String::as_str).collect();
|
||||
let why = match nearest(key, &keys) {
|
||||
Some(near) => format!("did you mean `{within}{near}`?"),
|
||||
None => format!("`{}` takes: {}", within.trim_end_matches('.'), keys.join(", ")),
|
||||
};
|
||||
let key = shown_key(key);
|
||||
return Err(bad(id, format!("unknown parameter `{within}{key}`; {why}")));
|
||||
let near = nearest(key, &keys);
|
||||
let key = format!("{within}{}", shown_key(key));
|
||||
return Err(match near {
|
||||
Some(near) => misspelled(id, &key, &format!("{within}{near}")),
|
||||
None => {
|
||||
let (object, keys) = (within.trim_end_matches('.'), keys.join(", "));
|
||||
bad(id, format!("unknown parameter `{key}`; `{object}` takes: {keys}"))
|
||||
}
|
||||
});
|
||||
}
|
||||
(Some(Value::Object(inner)), Value::Object(value)) => check_option_tree(id, &format!("{within}{key}."), value, inner)?,
|
||||
_ => {}
|
||||
@@ -691,14 +702,11 @@ fn check_option_keys(id: &str, within: &str, given: &serde_json::Map<String, Val
|
||||
for (key, value) in given {
|
||||
if !keys.contains(&key.as_str()) {
|
||||
let near = nearest(key, keys);
|
||||
let key = shown_key(key);
|
||||
return Err(bad(
|
||||
id,
|
||||
match near {
|
||||
Some(near) => format!("unknown parameter `{within}{key}`; did you mean `{within}{near}`?"),
|
||||
None => format!("unknown parameter `{within}{key}`; {why_not}"),
|
||||
},
|
||||
));
|
||||
let key = format!("{within}{}", shown_key(key));
|
||||
return Err(match near {
|
||||
Some(near) => misspelled(id, &key, &format!("{within}{near}")),
|
||||
None => bad(id, format!("unknown parameter `{key}`; {why_not}")),
|
||||
});
|
||||
}
|
||||
if let (Some(Value::Object(schema)), Value::Object(value)) = (trees.get(key), value) {
|
||||
check_option_tree(id, &format!("{within}{key}."), value, schema)?;
|
||||
@@ -797,12 +805,15 @@ fn check_screen_rows(id: &str, within: &str, p: &serde_json::Map<String, Value>)
|
||||
let formats = screen_formats();
|
||||
for (format, options) in settings {
|
||||
if !formats.contains(&format.as_str()) {
|
||||
let why = match nearest(format, &formats) {
|
||||
Some(near) => format!("did you mean `{within}settings.{near}`?"),
|
||||
None => format!("`{within}settings` takes: {}", formats.join(", ")),
|
||||
};
|
||||
let format = shown_key(format);
|
||||
return Err(bad(id, format!("unknown parameter `{within}settings.{format}`; {why}")));
|
||||
let near = nearest(format, &formats);
|
||||
let key = format!("{within}settings.{}", shown_key(format));
|
||||
return Err(match near {
|
||||
Some(near) => misspelled(id, &key, &format!("{within}settings.{near}")),
|
||||
None => {
|
||||
let (object, keys) = (format!("{within}settings"), formats.join(", "));
|
||||
bad(id, format!("unknown parameter `{key}`; `{object}` takes: {keys}"))
|
||||
}
|
||||
});
|
||||
}
|
||||
if let Value::Object(options) = options {
|
||||
check_option_keys(id, &format!("{within}settings.{format}."), options, &keys, NO_FORMAT, trees)?;
|
||||
|
||||
@@ -91,7 +91,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Placed File Info",
|
||||
[],
|
||||
None,
|
||||
"{path | name | dataBase64 (a file's path, or its name with its bytes), page?, crop?, password?, thumbnail?: px, link?: bool, dxf?: {…}, layers?, hiddenLayers?, importSlices? (all as file.place)} what file.place would place, without placing it → {name, format, width, height (pt at 100%), pixelWidth?, pixelHeight?, ppi?: [x, y], colorMode?: RGB|Grayscale|CMYK (raster images), plates?: [ink names] (a DCS file), slices?: the user slices a PSD or PSB file would bring in, warnings, thumbnailBase64?: PNG of at most `thumbnail` (≤ 512) px on its longer side}",
|
||||
"{path | name | dataBase64 (a file's path, or its name with its bytes), page?, crop?, password?, thumbnail?: px, link?: bool, dxf?: {…}, layers?, hiddenLayers?, importSlices? (all as file.place)} what file.place would place, without placing it → {name, format, width, height (pt at 100%), pixelWidth?, pixelHeight?, ppi?: [x, y], colorMode?: RGB|Grayscale|CMYK (raster images; opaque CMYK PSD/PSB merged images keep 8- or 16-bit inks within VectorCraft's 67,108,864-pixel native CMYK limit and allocation allowance; other CMYK composites use the RGB decoder's allocation limit), plates?: [ink names] (a DCS file), slices?: the user slices a PSD or PSB file would bring in, warnings, thumbnailBase64?: PNG of at most `thumbnail` (≤ 512) px on its longer side}",
|
||||
always,
|
||||
info
|
||||
),
|
||||
|
||||
@@ -23,7 +23,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Print Setup",
|
||||
[],
|
||||
None,
|
||||
"{preset?: name ([Default] or a saved print preset, any case: print.presets.list; its settings replace the document's, as choosing it in the Print dialog does), settings?: {copies: 1 (1–999), collate: true, reverse, artboards: all|range|ignore (all the art as one page), range: \"1-3, 5\" (1-based, with artboards: range), skipBlank (leave out artboards with no art that prints), media: letter|legal|tabloid|a3|a4|a5|a6|b4|b5|b4 (jis)|b5 (jis)|b6 (jis)|japanese postcard|japanese double postcard|japanese envelope #3|japanese envelope #4|kaku #2|kaku #3|yonroku-ban|custom (a paper is named by its id or its dialog label, any case and spacing, so `B5 (JIS)` works; b4 and b5 stay the ISO 216 sizes, 250 × 353 and 176 × 250 mm, and the JIS sizes are b4 (jis) 257 × 364 mm, b5 (jis) 182 × 257 mm and b6 (jis) 128 × 182 mm), width, height (custom paper, 72–14400 pt), orientation: portrait|landscape|portraitFlipped|landscapeFlipped, autoRotate: true (turn the paper to each artboard; orientation ignored), transverse (the page a quarter turn on the paper), printLayers: visiblePrintable|visible|all (template layers never print), placement: {origin: topLeft|top|topRight|left|center|right|bottomLeft|bottom|bottomRight (the point of the printed area, the artboard with its bleed and marks, on the same point of the imageable area), x, y (pt, right and down)}, scaling: none|fit|custom|tileFull|tileImageable, scale: {width: 100, height: 100 (1–1000 % with custom and tiling), linked: true (width and height stay equal: give one and the other follows, and turning it on sets the height to the width; a different width and height without linked turn it off, and with linked: true, or linked: null over a linked scale, are an error; a saved scale without linked reads it as false)}, overlap: 0 (pt between tiles), tileRange: \"\" (1-based tiles across then down; empty: all), copiesPerSheet: false (not with tiling: as many copies of each artboard, with its bleed and marks, as fit the imageable area, across then down, not turned; the placement places the grid; an artboard that doesn't fit prints one copy per sheet, with a warning), gutter: 0 (pt between copies, 0–720), margin: 0 (pt the device can't print around the paper: the imageable area is inside it), marks: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25, offset: 6} (as document.exportPdf, at the paper's scale; page information adds the tile and the ink), bleed: {useDocument: true (the document's bleed, document.setup), top, bottom, left, right} (pt), output: {mode: composite|separations (one gray page per ink that prints), emulsion: up|down (down mirrors), image: positive|negative, spotsToProcess, overprintBlack: false (separations: solid 100% K or 100% gray fills, strokes and characters, to within half a percent, overprint in the printed copy, gradients when every stop is (every point of a freeform one); rich, RGB, spot-linked and lighter blacks knock out; composite ignores it), inks: [{name: \"Cyan\"|…|a spot swatch, print: true, frequency (lpi, default 60), angle (screen angle, degrees counter-clockwise as PostScript setscreen takes it; default C 15, M 75, Y 0, K 45, spots 45)}]}, graphics: {autoFlatness: true, flatness: 1 (0.2–100), fonts: none|subset|complete}, color: {intent: perceptual|relativeColorimetric|saturation|absoluteColorimetric, preserveNumbers: true (CMYK colors keep their values), profile: \"\" (the printer profile, an RGB or CMYK one: composite PDF colors are converted to it with the intent, separations separate with a CMYK one; empty: as they are)}, advanced: {printAsBitmap (composite pages print as one image each, at the document's raster effects resolution, or lower for a page larger than 64 Mpx or 32,768 px a side), overprints: preserve|discard|simulate (composite output; preserve writes them to overprint (/OP), simulate prints them as Overprint Preview shows them; separations always keep them), flattenerPreset: \"\" (a flattener preset, built-in or saved: transparency is flattened before printing; empty: it prints live; PostScript defaults to medium)}, tileOrigin: {placed: false, x, y} (where the Print Tiling tool put the pages: print.tiling.set)}} store the print settings with the document, over the ones it has or the preset's (null keeps a value), as one undo step; no settings or preset → {settings} (the current ones, defaults if never set up)",
|
||||
"{preset?: name ([Default] or a saved print preset, any case: print.presets.list; its settings replace the document's, as choosing it in the Print dialog does), settings?: {copies: 1 (1–999), collate: true, reverse, artboards: all|range|ignore (all the art as one page), range: \"1-3, 5\" (1-based, with artboards: range), skipBlank (leave out artboards with no art that prints), media: letter|legal|tabloid|a3|a4|a5|a6|b4|b5|b4 (jis)|b5 (jis)|b6 (jis)|japanese postcard|japanese double postcard|japanese envelope #3|japanese envelope #4|kaku #2|kaku #3|yonroku-ban|custom (a paper is named by its id or its dialog label, any case and spacing, so `B5 (JIS)` works; b4 and b5 stay the ISO 216 sizes, 250 × 353 and 176 × 250 mm, and the JIS sizes are b4 (jis) 257 × 364 mm, b5 (jis) 182 × 257 mm and b6 (jis) 128 × 182 mm), width, height (custom paper, 72–14400 pt), orientation: portrait|landscape|portraitFlipped|landscapeFlipped, autoRotate: true (turn the paper to each artboard; orientation ignored), transverse (the page a quarter turn on the paper), printLayers: visiblePrintable|visible|all (template layers never print), placement: {origin: topLeft|top|topRight|left|center|right|bottomLeft|bottom|bottomRight (the point of the printed area, the artboard with its bleed and marks, on the same point of the imageable area), x, y (pt, right and down)}, scaling: none|fit|custom|tileFull|tileImageable, scale: {width: 100, height: 100 (1–1000 % with custom and tiling), linked: true (width and height stay equal: give one and the other follows, and turning it on sets the height to the width; a different width and height without linked turn it off, and with linked: true, or linked: null over a linked scale, are an error; a saved scale without linked reads it as false)}, overlap: 0 (pt between tiles), tileRange: \"\" (1-based tiles across then down; empty: all), copiesPerSheet: false (not with tiling: as many copies of each artboard, with its bleed and marks, as fit the imageable area, across then down, not turned; the placement places the grid; an artboard that doesn't fit prints one copy per sheet, with a warning), gutter: 0 (pt between copies, 0–720), margin: 0 (pt the device can't print around the paper: the imageable area is inside it), marks: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25, offset: 6} (as document.exportPdf, at the paper's scale; page information adds the tile and the ink), bleed: {useDocument: true (the document's bleed, document.setup), top, bottom, left, right} (pt), output: {mode: composite|separations (one gray page per ink that prints), emulsion: up|down (down mirrors), image: positive|negative, spotsToProcess, overprintBlack: false (separations: solid 100% K or 100% gray fills, strokes and characters, to within half a percent, overprint in the printed copy, gradients when every stop is (every point of a freeform one); rich, RGB, spot-linked and lighter blacks are not marked, and paints already set to overprint keep it; composite ignores it), inks: [{name: \"Cyan\"|…|a spot swatch, print: true, frequency (lpi, default 60), angle (screen angle, degrees counter-clockwise as PostScript setscreen takes it; default C 15, M 75, Y 0, K 45, spots 45), convertToProcess: false (a spot ink only: it prints on the process plates, with no plate of its own, and its print, frequency and angle are kept for when it prints as a spot ink again; spotsToProcess converts every spot ink whatever it says)}]}, graphics: {autoFlatness: true, flatness: 1 (0.2–100), fonts: none|subset|complete}, color: {intent: perceptual|relativeColorimetric|saturation|absoluteColorimetric, preserveNumbers: true (CMYK colors keep their values), profile: \"\" (the printer profile, an RGB or CMYK one: composite PDF colors are converted to it with the intent, separations separate with a CMYK one; empty: as they are)}, advanced: {printAsBitmap (composite pages print as one image each, at the document's raster effects resolution, or lower for a page larger than 64 Mpx or 32,768 px a side), overprints: preserve|discard|simulate (composite output; preserve writes them to overprint (/OP), simulate prints them as Overprint Preview shows them; separations always keep them), flattenerPreset: \"\" (a flattener preset, built-in or saved: transparency is flattened before printing; empty: it prints live; PostScript defaults to medium)}, tileOrigin: {placed: false, x, y} (where the Print Tiling tool put the pages: print.tiling.set)}} store the print settings with the document, over the ones it has or the preset's (null keeps a value), as one undo step; no settings or preset → {settings} (the current ones, defaults if never set up)",
|
||||
has_doc,
|
||||
setup
|
||||
),
|
||||
@@ -32,7 +32,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Print Preview",
|
||||
[],
|
||||
None,
|
||||
"{preset?: name (as print.setup's: its settings instead of the document's), settings?: {…settings of print.setup} (over the document's or the preset's)} → {pages (copies included), sheets: [{artboard (0-based; null with artboards ignored), tile? (1-based), ink? (separations), width, height (pt, the page), orientation, scale: [width %, height %], transform: [a, b, c, d, e, f] (document space → the page, pt, y down), area: [x0, y0, x1, y1] (the document region the page prints), trim: [x0, y0, x1, y1] (the artboard on the page; with copies per sheet, the box around every copy's), copies?: [[x0, y0, x1, y1]…] (copies per sheet: each copy's artboard on the page, across then down)}] (one copy, in order), tiles: [{artboard, columns, rows, printed: [1-based tiles], tiles: [[x0, y0, x1, y1]…] (document space)}], inks: [{name, spot, print, frequency, angle}] (separations), warnings (art larger than the imageable area, type that prints in the fallback font, type that doesn't fit its frame, options not applied yet…), settings} without printing",
|
||||
"{preset?: name (as print.setup's: its settings instead of the document's), settings?: {…settings of print.setup} (over the document's or the preset's)} → {pages (copies included), sheets: [{artboard (0-based; null with artboards ignored), tile? (1-based), ink? (separations), width, height (pt, the page), orientation, scale: [width %, height %], transform: [a, b, c, d, e, f] (document space → the page, pt, y down), area: [x0, y0, x1, y1] (the document region the page prints), trim: [x0, y0, x1, y1] (the artboard on the page; with copies per sheet, the box around every copy's), copies?: [[x0, y0, x1, y1]…] (copies per sheet: each copy's artboard on the page, across then down)}] (one copy, in order), tiles: [{artboard, columns, rows, printed: [1-based tiles], tiles: [[x0, y0, x1, y1]…] (document space)}], inks: [{name, spot, print, frequency, angle}] (separations: the plates), documentInks: [{name, spot, print, frequency, angle, convertToProcess?: true (a spot ink printing as process, with no plate)}] (separations: every ink of the document), warnings (art larger than the imageable area, type that prints in the fallback font, type that doesn't fit its frame, options not applied yet…), settings} without printing",
|
||||
has_doc,
|
||||
preview
|
||||
),
|
||||
|
||||
@@ -66,11 +66,13 @@ impl FlattenReport {
|
||||
lowest
|
||||
.into_iter()
|
||||
.map(|r| {
|
||||
let name = r.name.map(|name| format!(" ({name})")).unwrap_or_default();
|
||||
format!(
|
||||
"raster effects on object {}{name}: requested {:.1} ppi, achieved {:.1} ppi due to the 64 million pixel cap",
|
||||
r.id.0, self.requested_ppi, r.achieved_ppi
|
||||
)
|
||||
// The id and the name are one value of the message, so a catalog can match it.
|
||||
let object = match r.name {
|
||||
Some(name) => format!("{} ({name})", r.id.0),
|
||||
None => r.id.0.to_string(),
|
||||
};
|
||||
let (requested, achieved) = (self.requested_ppi, r.achieved_ppi);
|
||||
format!("raster effects on object {object}: requested {requested:.1} ppi, achieved {achieved:.1} ppi due to the 64 million pixel cap")
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -127,4 +129,23 @@ mod tests {
|
||||
assert_eq!(warnings.len(), 1);
|
||||
assert!(warnings[0].contains(&format!("object {}", original.id.0)), "{:?}", warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_warning_names_the_object_by_its_id_and_its_name() {
|
||||
let mut doc = Document::new(100.0, 100.0);
|
||||
doc.raster_effects_ppi = 300.0;
|
||||
let mut named = Node::group(NodeId(7), vec![]);
|
||||
named.name = Some("Logo".into());
|
||||
let unnamed = Node::group(NodeId(8), vec![]);
|
||||
let mut report = FlattenReport::new(Which::All, &doc);
|
||||
report.record(&named, &image(72.0));
|
||||
report.record(&unnamed, &image(150.0));
|
||||
assert_eq!(
|
||||
report.warnings(),
|
||||
[
|
||||
"raster effects on object 7 (Logo): requested 300.0 ppi, achieved 72.0 ppi due to the 64 million pixel cap",
|
||||
"raster effects on object 8: requested 300.0 ppi, achieved 150.0 ppi due to the 64 million pixel cap",
|
||||
]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Select menu.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::collections::{BTreeSet, HashSet};
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::Paint;
|
||||
@@ -466,7 +466,8 @@ fn reselect(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
|
||||
fn inverse(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let st = s.doc()?;
|
||||
let ids: Vec<NodeId> = selectable(&st.doc, st.isolation).into_iter().filter(|id| !st.selection.contains(*id)).collect();
|
||||
let selected: HashSet<NodeId> = st.selection.objects.iter().copied().collect();
|
||||
let ids: Vec<NodeId> = selectable(&st.doc, st.isolation).into_iter().filter(|id| !selected.contains(id)).collect();
|
||||
s.select(|_, sel| sel.set(ids.iter().copied()))?;
|
||||
ok()
|
||||
}
|
||||
@@ -497,11 +498,7 @@ fn set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let ids = checked_ids_param(s, p, "ids", "select.add")?;
|
||||
s.select(|_, sel| {
|
||||
for i in ids {
|
||||
sel.add(i);
|
||||
}
|
||||
})?;
|
||||
s.select(|_, sel| sel.add_all(ids))?;
|
||||
selection_result(s)
|
||||
}
|
||||
|
||||
@@ -512,11 +509,7 @@ fn toggle(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let value = p.get("id").ok_or_else(|| bad("select.toggle", "missing id or ids"))?;
|
||||
vec![checked_id(s, value, "select.toggle")?]
|
||||
};
|
||||
s.select(|_, sel| {
|
||||
for id in ids {
|
||||
sel.toggle(id);
|
||||
}
|
||||
})?;
|
||||
s.select(|_, sel| sel.toggle_all(ids))?;
|
||||
selection_result(s)
|
||||
}
|
||||
|
||||
|
||||
@@ -19,7 +19,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"New Swatch",
|
||||
["Window", "Swatches"],
|
||||
None,
|
||||
"{name?, color? | colors?: [colour] (one swatch each, in one undo step; #rrggbbaa and #rgba are refused) | swatch? | gradient? | pattern?: name (default: the current fill), tint?: 0..100 (% of the global or spot `swatch`, or of the one the current fill links to), mode?: \"gray\"|\"rgb\"|\"hsb\"|\"lab\"|\"cmyk\"|\"web\" (convert the colour; lab: CIE L*a*b*, how spot colours are usually defined), global?, spot? (a spot colour, always global), group?: colour group name (solid colours only; default: ungrouped), none?: true (the None paint), paint?: paint.setFill params, keepModel?: bool (as paint.setFill)} save a colour, gradient or pattern as a swatch. A tint of a global or spot colour (below 100%, without mode, global or spot) becomes a tint swatch, \"Name 40%\", linked to its base: it follows edits to the base and applies as that tint of it. A gradient swatch keeps the gradient's aspect (with or without start/end) and holds no link to the swatch its gradient came from, and a pattern swatch holds the pattern untransformed. Names are unique (\"Sky 2\"); a colour's default name is its values (\"C=10 M=20 Y=30 K=0\", \"R=255 G=128 B=0\", \"Gray K=40\", \"L=55 a=60 b=40\") → {name, names: [every new swatch]}",
|
||||
"{name?, color? | colors?: [colour | {swatch, tint?}] (one swatch each, in one undo step; #rrggbbaa and #rgba are refused; `{swatch, tint}` is the paint paint.setFill gives, so a tint of a global or spot color becomes a tint swatch) | swatch? | gradient? | pattern?: name (default: the current fill), tint?: 0..100 (% of the global or spot `swatch`, or of the one the current fill links to), mode?: \"gray\"|\"rgb\"|\"hsb\"|\"lab\"|\"cmyk\"|\"web\" (convert the colour; lab: CIE L*a*b*, how spot colours are usually defined), global?, spot? (a spot colour, always global), group?: colour group name (solid colours only; default: ungrouped), none?: true (the None paint), paint?: paint.setFill params, keepModel?: bool (as paint.setFill)} save a colour, gradient or pattern as a swatch. A tint of a global or spot colour (below 100%, without mode, global or spot) becomes a tint swatch, \"Name 40%\", linked to its base: it follows edits to the base and applies as that tint of it. A gradient swatch keeps the gradient's aspect (with or without start/end) and holds no link to the swatch its gradient came from, and a pattern swatch holds the pattern untransformed. Names are unique (\"Sky 2\"); a colour's default name is its values (\"C=10 M=20 Y=30 K=0\", \"R=255 G=128 B=0\", \"Gray K=40\", \"L=55 a=60 b=40\") → {name, names: [every new swatch]}",
|
||||
has_doc,
|
||||
swatch_new
|
||||
),
|
||||
@@ -37,7 +37,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"New Color Group",
|
||||
["Window", "Swatches"],
|
||||
None,
|
||||
"{name?, swatches?: [names] (solid colours move into the group; gradients, patterns and None stay), colors?: [colour] (added as new swatches; #rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), fromArtwork?: false (add the unique colours of the selected art: fills, strokes, text, gradient stops and mesh points; a colour linked to a global swatch moves that swatch into the group), toGlobal?: true (with fromArtwork: the new swatches are global and the selected art's matching unlinked colours link to them), includeTints?: false (with fromArtwork: tints of global swatches also get swatches of their own)} → {name, swatches: [names in the group], linked: paints linked}",
|
||||
"{name?, swatches?: [names] (solid colours move into the group; gradients, patterns and None stay), colors?: [colour | {swatch, tint?}] (added as new swatches; #rrggbbaa and #rgba are refused; `{swatch, tint}` below 100% of a global or spot color adds a tint swatch, \"Name 40%\", linked to it, and any other `{swatch}` its color), keepModel?: bool (as paint.setFill), fromArtwork?: false (add the unique colours of the selected art: fills, strokes, text, gradient stops and mesh points; a colour linked to a global swatch moves that swatch into the group), toGlobal?: true (with fromArtwork: the new swatches are global and the selected art's matching unlinked colours link to them), includeTints?: false (with fromArtwork: tints of global swatches also get swatches of their own)} → {name, swatches: [names in the group], linked: paints linked}",
|
||||
has_doc,
|
||||
swatch_new_group
|
||||
),
|
||||
@@ -146,9 +146,11 @@ fn swatch_new(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let stored = |c: Color| if mode.is_some() { c } else { super::paint::new_color(s, p, c) };
|
||||
let cs: Vec<Paint> = cs
|
||||
.iter()
|
||||
.map(|c| color_value(c).map(|c| Paint::solid(stored(c))))
|
||||
.collect::<Option<_>>()
|
||||
.ok_or_else(|| bad(C, "bad colour in `colors`"))?;
|
||||
.map(|c| match swatch_entry(s, c, C)? {
|
||||
Some(paint) => Ok(paint),
|
||||
None => color_value(c).map(|c| Paint::solid(stored(c))).ok_or_else(|| bad(C, "bad colour in `colors`")),
|
||||
})
|
||||
.collect::<Result<_>>()?;
|
||||
if cs.is_empty() {
|
||||
return Err(bad(C, "`colors` is empty"));
|
||||
}
|
||||
@@ -216,6 +218,16 @@ fn swatch_new(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "name": names[0], "names": names }))
|
||||
}
|
||||
|
||||
/// A `colors` entry of `swatch.new` or `swatch.newGroup` that names a color swatch,
|
||||
/// `{swatch, tint?}`: the paint `paint.setFill {swatch, tint}` applies (a tint of a global or spot
|
||||
/// color stays linked to it). `None` for an entry without `swatch`.
|
||||
fn swatch_entry(s: &Session, v: &Value, cmd: &str) -> Result<Option<Paint>> {
|
||||
let Some(name) = v.get("swatch") else { return Ok(None) };
|
||||
let name = name.as_str().ok_or_else(|| bad(cmd, format!("`swatch` in `colors` must be a swatch name, not {name}")))?;
|
||||
let tint = super::paint::tint_param(v, cmd)?;
|
||||
super::paint::swatch_solid(&s.doc()?.doc, name, tint).map(Some).map_err(|e| bad(cmd, e))
|
||||
}
|
||||
|
||||
/// A gradient or pattern `paint`, parsed from the paint params `p`, as a new or edited swatch
|
||||
/// stores it.
|
||||
fn stored_paint(paint: Paint, p: &Value) -> Paint {
|
||||
@@ -475,10 +487,20 @@ fn swatch_new_group(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut names = str_list(p, "swatches");
|
||||
super::paint::check_keep_model(p, C)?;
|
||||
check_switches(p, &["fromArtwork", "toGlobal", "includeTints"], C)?;
|
||||
let colors: Vec<Color> = p
|
||||
// A `{swatch, tint}` entry below 100% becomes a tint swatch linked to its base; any other
|
||||
// entry becomes a process color swatch.
|
||||
let colors: Vec<Paint> = p
|
||||
.get("colors")
|
||||
.and_then(Value::as_array)
|
||||
.map(|a| a.iter().map(|v| color_value(v).map(|c| super::paint::new_color(s, p, c)).ok_or_else(|| bad(C, format!("bad color {v}")))).collect())
|
||||
.map(|a| {
|
||||
a.iter()
|
||||
.map(|v| match swatch_entry(s, v, C)? {
|
||||
Some(paint @ Paint::Solid { swatch: Some(_), tint, .. }) if tint < 1.0 => Ok(paint),
|
||||
Some(paint) => paint.color().map(Paint::solid).ok_or_else(|| bad(C, format!("bad color {v}"))),
|
||||
None => color_value(v).map(|c| Paint::solid(super::paint::new_color(s, p, c))).ok_or_else(|| bad(C, format!("bad color {v}"))),
|
||||
})
|
||||
.collect::<Result<Vec<_>>>()
|
||||
})
|
||||
.transpose()?
|
||||
.unwrap_or_default();
|
||||
let from_art = bool_or(p, "fromArtwork", false);
|
||||
@@ -486,15 +508,15 @@ fn swatch_new_group(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let tints = bool_or(p, "includeTints", false);
|
||||
let requested = name_param(p, "name");
|
||||
let (name, members, linked) = s.edit("New Color Group", |d, sel| {
|
||||
// New swatches: (colour, global).
|
||||
let mut new: Vec<(Color, bool)> = colors.iter().map(|c| (*c, false)).collect();
|
||||
// New swatches: (paint, global).
|
||||
let mut new: Vec<(Paint, bool)> = colors.iter().map(|c| (c.clone(), false)).collect();
|
||||
if from_art {
|
||||
if sel.objects.is_empty() {
|
||||
return Err(bad(C, "select artwork to make a group of its colours"));
|
||||
}
|
||||
let mut art = vec![];
|
||||
artwork_colors(d, &sel.objects, tints, &mut names, &mut art);
|
||||
new.extend(art.into_iter().map(|c| (c, to_global)));
|
||||
new.extend(art.into_iter().map(|c| (Paint::solid(c), to_global)));
|
||||
}
|
||||
let name = d.free_swatch_name(requested.as_deref().unwrap_or("Color Group"));
|
||||
// Colour groups hold solid colours only.
|
||||
@@ -505,12 +527,13 @@ fn swatch_new_group(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut free = d.free_swatch_names();
|
||||
free.insert(&name);
|
||||
group.swatches.iter().for_each(|sw| free.insert(&sw.name));
|
||||
for (c, global) in new {
|
||||
let nm = free.take(&color_name(c));
|
||||
if global {
|
||||
for (paint, global) in new {
|
||||
// A tint swatch is named "Name 40%", a colour after its values.
|
||||
let nm = free.take_new(&paint);
|
||||
if global && let Some(c) = paint.color() {
|
||||
links.push((c, nm.clone()));
|
||||
}
|
||||
group.swatches.push(Swatch { name: nm, paint: Paint::solid(c), global, spot: false });
|
||||
group.swatches.push(Swatch { name: nm, paint, global, spot: false });
|
||||
}
|
||||
let members: Vec<String> = group.swatches.iter().map(|w| w.name.clone()).collect();
|
||||
d.swatch_groups.push(group);
|
||||
|
||||
@@ -270,7 +270,7 @@ fn range_of(p: &Value, len: usize, cmd: &str) -> Result<(usize, usize)> {
|
||||
Ok((a.min(b), a.max(b)))
|
||||
}
|
||||
|
||||
fn edit_range(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
pub(crate) fn edit_range(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "text.editRange";
|
||||
let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing `id`"))?;
|
||||
let t = text_ref(s, id)?;
|
||||
|
||||
@@ -10,8 +10,8 @@ use super::object::choice;
|
||||
use super::threads::ThreadIndex;
|
||||
use super::typecmd::{area_text, block_gaps, needed_room, refresh_bounds};
|
||||
use super::{
|
||||
CommandSpec, EngineError, Result, Session, bad, checked_ids_param, cmd, find_command, has_clipboard, has_doc, has_selection, number_or,
|
||||
switch_or, targets, text_param,
|
||||
CommandSpec, EngineError, Result, Session, bad, checked_ids_param, cmd, find_command, has_clipboard, has_doc, has_selection, named_ids,
|
||||
number_or, switch_or, targets, text_param,
|
||||
};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
@@ -111,7 +111,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Insert Character",
|
||||
["Type"],
|
||||
None,
|
||||
"{char: \"bullet\"|\"copyright\"|\"ellipsis\"|\"paragraph\"|\"registered\"|\"section\"|\"trademark\"|\"emDash\"|\"enDash\"|\"discretionaryHyphen\"|\"nonBreakingHyphen\"|\"doubleLeftQuote\"|\"doubleRightQuote\"|\"singleLeftQuote\"|\"singleRightQuote\"|\"emSpace\"|\"enSpace\"|\"hairSpace\"|\"sixthSpace\"|\"thinSpace\"|\"nonBreakingSpace\"|\"figureSpace\"|\"punctuationSpace\"|\"thirdSpace\"|\"quarterSpace\"|\"tab\"|\"forcedLineBreak\"|\"paragraphReturn\" | text: string | code: Windows Alt+0 code (0–255 in Windows-1252, a Unicode code point above: 176 → °, 151 → —) | unicode: hex code point (\"00B0\" or \"U+00B0\"), ids?|id?: object ids (default: the selection)} append to the selected text objects",
|
||||
"{char: \"bullet\"|\"copyright\"|\"ellipsis\"|\"paragraph\"|\"registered\"|\"section\"|\"trademark\"|\"emDash\"|\"enDash\"|\"discretionaryHyphen\"|\"nonBreakingHyphen\"|\"doubleLeftQuote\"|\"doubleRightQuote\"|\"singleLeftQuote\"|\"singleRightQuote\"|\"emSpace\"|\"enSpace\"|\"hairSpace\"|\"sixthSpace\"|\"thinSpace\"|\"nonBreakingSpace\"|\"figureSpace\"|\"punctuationSpace\"|\"thirdSpace\"|\"quarterSpace\"|\"tab\"|\"forcedLineBreak\"|\"paragraphReturn\" | text: string | code: Windows Alt+0 code (0–255 in Windows-1252, a Unicode code point above: 176 → °, 151 → —) | unicode: hex code point (\"00B0\" or \"U+00B0\"), ids?|id?: object ids (default: the selection)} insert at the Type tool's caret, replacing its selection, while it edits text and no ids are given; otherwise append to the selected text objects. forcedLineBreak is U+2028, a new line in the same paragraph; paragraphReturn is a line feed, which starts a new paragraph",
|
||||
has_selection,
|
||||
insert_char
|
||||
),
|
||||
@@ -786,8 +786,9 @@ fn to_point(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let plain = t.plain_text();
|
||||
let baseline = lay.lines.first().map(|l| l.baseline).unwrap_or(fb.y0 + t.first_style().size * 0.8);
|
||||
// Soft wraps → explicit breaks (replace the space before the wrap when there is one).
|
||||
let mut breaks: Vec<usize> =
|
||||
lay.lines.iter().skip(1).map(|l| l.start).filter(|&b| b > 0 && plain.as_bytes().get(b - 1) != Some(&b'\n')).collect();
|
||||
// A line after a paragraph return or a forced line break (U+2028) already starts there.
|
||||
let hard = |b: usize| plain.get(..b).is_some_and(|s| s.ends_with(['\n', '\u{2028}']));
|
||||
let mut breaks: Vec<usize> = lay.lines.iter().skip(1).map(|l| l.start).filter(|&b| b > 0 && !hard(b)).collect();
|
||||
breaks.sort_unstable();
|
||||
breaks.dedup();
|
||||
for b in breaks.into_iter().rev() {
|
||||
@@ -1525,8 +1526,9 @@ pub(crate) fn special_char(name: &str) -> Option<&'static str> {
|
||||
"thirdSpace" => "\u{2004}",
|
||||
"quarterSpace" => "\u{2005}",
|
||||
"tab" => "\t",
|
||||
// Our text model breaks lines at paragraph returns only.
|
||||
"forcedLineBreak" | "paragraphReturn" => "\n",
|
||||
// A line break inside the paragraph, as Shift+Enter types it.
|
||||
"forcedLineBreak" => "\u{2028}",
|
||||
"paragraphReturn" => "\n",
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
@@ -1576,6 +1578,11 @@ fn insert_char(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
(None, None, None, Some(u)) => unicode_char(u).ok_or_else(|| bad(C, format!("`{u}` is no Unicode character")))?.to_string(),
|
||||
(None, None, None, None) => return Err(bad(C, "give `char`, `text`, `code` or `unicode`")),
|
||||
};
|
||||
if named_ids(p)?.is_none()
|
||||
&& let Some(r) = insert_at_type_caret(s, &text)?
|
||||
{
|
||||
return Ok(r);
|
||||
}
|
||||
let ids = texts(s, p, C)?;
|
||||
// When `text` is empty and every object ends with a run of text, the document and its undo
|
||||
// history stay as they are.
|
||||
@@ -1606,6 +1613,44 @@ fn insert_char(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(ids_json(&ids))
|
||||
}
|
||||
|
||||
/// `type.insert` while the Type tool edits text: `text` replaces the tool's selection (inserts at
|
||||
/// its caret) as one undo step, and the caret goes after it. `None` when no text is being edited.
|
||||
fn insert_at_type_caret(s: &mut Session, text: &str) -> Result<Option<Value>> {
|
||||
let tool = s.tool_options();
|
||||
let Some(id) = tool.get("editing").and_then(Value::as_u64).map(NodeId) else { return Ok(None) };
|
||||
let d = &s.doc()?.doc;
|
||||
let Some(NodeKind::Text(t)) = d.node(id).map(|n| &n.kind) else { return Ok(None) };
|
||||
let len = vectorcraft_text::edit::runs_len(&t.runs);
|
||||
let g = |k: &str| tool.get(k).and_then(Value::as_u64).map_or(len, |v| (v as usize).min(len));
|
||||
let (x, y) = (g("start"), g("end"));
|
||||
let (a, b) = (x.min(y), x.max(y));
|
||||
// After Select All in threaded text the whole story is selected: the other frames' text goes
|
||||
// in the same edit, as when typing replaces it.
|
||||
let story: Vec<NodeId> = tool.get("story").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_u64).map(NodeId).collect();
|
||||
let clear: Vec<u64> = if a == 0 && b == len && story.contains(&id) {
|
||||
let has_text = |f: &NodeId| matches!(d.node(*f).map(|n| &n.kind), Some(NodeKind::Text(o)) if !o.runs.iter().all(|r| r.text.is_empty()));
|
||||
story.iter().filter(|f| **f != id && has_text(f)).map(|f| f.0).collect()
|
||||
} else {
|
||||
vec![]
|
||||
};
|
||||
if text.is_empty() && a == b && clear.is_empty() {
|
||||
return Ok(Some(ids_json(&[id])));
|
||||
}
|
||||
// A typing session ends first: the insertion is a step of its own.
|
||||
if tool.get("typing").and_then(Value::as_bool) == Some(true) {
|
||||
s.set_tool_option("commitTyping", &Value::Bool(true));
|
||||
s.commit_interaction()?;
|
||||
}
|
||||
// The frame's place in the story once the edit has cleared the frames in `clear`.
|
||||
let start: usize =
|
||||
super::panelcmds::story_frames(s, id).iter().take_while(|(f, _)| *f != id).filter(|(f, _)| !clear.contains(&f.0)).map(|(_, n)| n).sum();
|
||||
let r = super::textedit::edit_range(s, &json!({"id": id.0, "start": a, "end": b, "insert": text, "clear": clear}))?;
|
||||
let caret = r.get("caret").and_then(Value::as_u64).map_or(a + text.len(), |c| c as usize);
|
||||
// Threaded text re-flows in the edit: the caret goes to the frame its place moved to.
|
||||
super::panelcmds::select_story_range(s, id, start + caret, start + caret)?;
|
||||
Ok(Some(ids_json(&[id])))
|
||||
}
|
||||
|
||||
// ---------- Find and Replace ----------
|
||||
|
||||
fn is_word(c: char) -> bool {
|
||||
|
||||
@@ -45,6 +45,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_doc,
|
||||
preview
|
||||
),
|
||||
cmd!(
|
||||
query "webExport.optimizeToFileSize",
|
||||
"Optimize to File Size",
|
||||
[],
|
||||
None,
|
||||
"{desiredK: the desired file size in K (1024 bytes; above 0, at most 1048576), startWith?: current (default: the format given, its JPEG quality or GIF/PNG-8 colors lowered; GIF then takes lossy 100)|auto (GIF for art with transparency or at most 256 colors (blended over the matte without transparency), else JPEG; the other one when the first can't reach the size and the art is opaque), use?: allSlices (default: the image, or the image slices' files together)|eachSlice (every image slice's file)|currentSlice (the `slice` given, else the selected image slice, else the first), slice?: n (1-based, from slice.list), preset?, …the settings of document.exportForWeb} the settings whose files fit in the size, searched by encoding at most 32 trial settings (each one encodes every image it measures); slices share one setting, which every scope changes → {targetBytes, achieved (false: no setting tried fits, and settings are the smallest one found), bytes (as use measures them), format, settings, trials, images, warnings}; writes nothing and changes no remembered setting",
|
||||
has_doc,
|
||||
optimize_to_file_size
|
||||
),
|
||||
cmd!(
|
||||
query "webExport.settings",
|
||||
"Save for Web Settings",
|
||||
@@ -1054,6 +1063,297 @@ fn preview(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
// ---------- Optimize to File Size ----------
|
||||
|
||||
/// The most trial settings `webExport.optimizeToFileSize` encodes. Each trial encodes every image
|
||||
/// it measures once.
|
||||
pub const OPTIMIZE_TRIALS: usize = 32;
|
||||
/// The largest desired file size, in K (1 GiB).
|
||||
pub const MAX_DESIRED_K: f64 = 1_048_576.0;
|
||||
|
||||
/// Where Optimize to File Size starts.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum StartWith {
|
||||
/// The current format, with its JPEG quality or palette colors lowered.
|
||||
Current,
|
||||
/// GIF or JPEG, by the image's content.
|
||||
Auto,
|
||||
}
|
||||
|
||||
/// The pixels `px` (`[x0, y0, x1, y1]`) of `r` as an image: borrowed when `px` is the whole render,
|
||||
/// else a copy.
|
||||
fn file_pixels(r: &WebRender, px: [u32; 4]) -> std::borrow::Cow<'_, [u8]> {
|
||||
if px == [0, 0, r.width, r.height] { std::borrow::Cow::Borrowed(r.rgba.as_slice()) } else { std::borrow::Cow::Owned(crop(r, px)) }
|
||||
}
|
||||
|
||||
/// The settings Optimize to File Size found.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct SizeFit {
|
||||
pub settings: WebSettings,
|
||||
/// The size the settings give the measured images.
|
||||
pub bytes: usize,
|
||||
/// Whether `bytes` is within the target.
|
||||
pub achieved: bool,
|
||||
/// The trial settings encoded.
|
||||
pub trials: usize,
|
||||
}
|
||||
|
||||
/// The files a search measures and the trials it has left.
|
||||
struct Trials<'a> {
|
||||
doc: &'a Document,
|
||||
r: &'a WebRender,
|
||||
/// The pixels (`[x0, y0, x1, y1]`) of each file in `r`.
|
||||
files: &'a [[u32; 4]],
|
||||
/// Measure the largest file (else the files together).
|
||||
each: bool,
|
||||
left: usize,
|
||||
used: usize,
|
||||
}
|
||||
|
||||
impl Trials<'_> {
|
||||
/// The size `s` gives the files, encoded one at a time; `None` when no trial is left.
|
||||
fn size(&mut self, s: &WebSettings) -> std::result::Result<Option<usize>, String> {
|
||||
if self.left == 0 {
|
||||
return Ok(None);
|
||||
}
|
||||
self.left -= 1;
|
||||
self.used += 1;
|
||||
let mut out = 0usize;
|
||||
for &px in self.files {
|
||||
let n = optimize(self.doc, &file_pixels(self.r, px), px[2] - px[0], px[3] - px[1], s)?.bytes.len();
|
||||
out = if self.each { out.max(n) } else { out.saturating_add(n) };
|
||||
}
|
||||
Ok(Some(out))
|
||||
}
|
||||
}
|
||||
|
||||
/// `(settings, bytes)` of a trial.
|
||||
pub type Trial = (WebSettings, usize);
|
||||
|
||||
/// Keep `(s, n)` in `smallest` when it is the smallest trial so far.
|
||||
fn keep_smallest(smallest: &mut Option<Trial>, s: WebSettings, n: usize) {
|
||||
if smallest.as_ref().is_none_or(|(_, b)| n < *b) {
|
||||
*smallest = Some((s, n));
|
||||
}
|
||||
}
|
||||
|
||||
/// The values [`highest_within`] measures spread over its range before it narrows a step.
|
||||
pub const OPTIMIZE_SAMPLES: u16 = 6;
|
||||
|
||||
/// Measures the size a setting gives; `None` when no trial is left.
|
||||
pub type MeasureSize<'a> = dyn FnMut(&WebSettings) -> std::result::Result<Option<usize>, String> + 'a;
|
||||
|
||||
/// The highest value in `lo..hi` that `set` gives `start` whose size is within `target`, when the
|
||||
/// value `hi` is over it. A lower value can give a larger file, so the search measures up to
|
||||
/// [`OPTIMIZE_SAMPLES`] values spread over the range, from `hi - 1` down, stops at the first that
|
||||
/// fits, and halves the step between it and the measured value above it, keeping the highest value
|
||||
/// measured within `target`. `None` when no value measured fits or no trial is left; the trials over
|
||||
/// the target go to `smallest`.
|
||||
pub fn highest_within(
|
||||
size: &mut MeasureSize,
|
||||
start: &WebSettings,
|
||||
(lo, hi): (u16, u16),
|
||||
set: fn(&mut WebSettings, u16),
|
||||
target: usize,
|
||||
smallest: &mut Option<Trial>,
|
||||
) -> std::result::Result<Option<Trial>, String> {
|
||||
let with = |v: u16| {
|
||||
let mut s = start.clone();
|
||||
set(&mut s, v);
|
||||
s
|
||||
};
|
||||
if lo >= hi {
|
||||
return Ok(None);
|
||||
}
|
||||
let span = u32::from(hi - lo);
|
||||
let samples = u32::from(OPTIMIZE_SAMPLES).min(span);
|
||||
let (mut above, mut found) = (hi, None);
|
||||
for i in (0..samples).rev() {
|
||||
let step = if samples == 1 { 0 } else { (span - 1) * i / (samples - 1) };
|
||||
let v = lo.saturating_add(u16::try_from(step).unwrap_or(0));
|
||||
let s = with(v);
|
||||
let Some(n) = size(&s)? else { return Ok(None) };
|
||||
if n <= target {
|
||||
found = Some((v, (s, n)));
|
||||
break;
|
||||
}
|
||||
keep_smallest(smallest, s, n);
|
||||
above = v;
|
||||
}
|
||||
let Some((mut lo, mut best)) = found else { return Ok(None) };
|
||||
let mut hi = above;
|
||||
while hi - lo > 1 {
|
||||
let mid = lo + (hi - lo) / 2;
|
||||
let s = with(mid);
|
||||
let Some(n) = size(&s)? else { break };
|
||||
if n <= target {
|
||||
lo = mid;
|
||||
best = (s, n);
|
||||
} else {
|
||||
keep_smallest(smallest, s, n);
|
||||
hi = mid;
|
||||
}
|
||||
}
|
||||
Ok(Some(best))
|
||||
}
|
||||
|
||||
/// Sets the JPEG quality, for [`highest_within`].
|
||||
pub fn set_quality(s: &mut WebSettings, v: u16) {
|
||||
s.quality = u8::try_from(v).unwrap_or(100);
|
||||
}
|
||||
|
||||
/// Sets the palette colors, for [`highest_within`].
|
||||
pub fn set_colors(s: &mut WebSettings, v: u16) {
|
||||
s.colors = v;
|
||||
}
|
||||
|
||||
/// The best settings of `start`'s format within `target`: `start` when it fits, else the highest
|
||||
/// JPEG quality or the most palette colors [`highest_within`] finds that fit, and for GIF, when none
|
||||
/// is found, lossy 100 with the most colors that fit. When nothing tried fits, the smallest trial, not achieved.
|
||||
/// `None` when no trial is left.
|
||||
fn search_format(t: &mut Trials, start: &WebSettings, target: usize) -> std::result::Result<Option<SizeFit>, String> {
|
||||
let fit = |(settings, bytes): Trial, achieved: bool| SizeFit { settings, bytes, achieved, trials: 0 };
|
||||
let Some(n) = t.size(start)? else { return Ok(None) };
|
||||
if n <= target {
|
||||
return Ok(Some(fit((start.clone(), n), true)));
|
||||
}
|
||||
let mut smallest = Some((start.clone(), n));
|
||||
let found = match start.format {
|
||||
WebFormat::Jpg => highest_within(&mut |s: &WebSettings| t.size(s), start, (1, u16::from(start.quality)), set_quality, target, &mut smallest)?,
|
||||
WebFormat::Gif | WebFormat::Png8 => {
|
||||
match highest_within(&mut |s: &WebSettings| t.size(s), start, (2, start.colors), set_colors, target, &mut smallest)? {
|
||||
None if start.format == WebFormat::Gif && start.lossy < 100 => {
|
||||
let lossy = WebSettings { lossy: 100, ..start.clone() };
|
||||
match t.size(&lossy)? {
|
||||
Some(n) if n <= target => Some((lossy, n)),
|
||||
Some(n) => {
|
||||
keep_smallest(&mut smallest, lossy.clone(), n);
|
||||
highest_within(&mut |s: &WebSettings| t.size(s), &lossy, (2, lossy.colors), set_colors, target, &mut smallest)?
|
||||
}
|
||||
None => None,
|
||||
}
|
||||
}
|
||||
found => found,
|
||||
}
|
||||
}
|
||||
WebFormat::Png24 => None,
|
||||
};
|
||||
Ok(match (found, smallest) {
|
||||
(Some(f), _) => Some(fit(f, true)),
|
||||
(None, Some(s)) => Some(fit(s, false)),
|
||||
(None, None) => None,
|
||||
})
|
||||
}
|
||||
|
||||
/// The format Auto Select GIF/JPEG starts with, and whether the files (`[x0, y0, x1, y1]` of `r`)
|
||||
/// are opaque: GIF for files with transparent pixels (when `transparency` keeps them) or at most
|
||||
/// 256 colors, else JPEG. The colors counted are the ones the files are written with: without
|
||||
/// `transparency`, the pixels blended over `matte`.
|
||||
fn auto_format(r: &WebRender, files: &[[u32; 4]], transparency: bool, matte: [u8; 3]) -> (WebFormat, bool) {
|
||||
let stride = r.width as usize * 4;
|
||||
let row =
|
||||
move |y: u32, x0: u32, x1: u32| r.rgba.get(y as usize * stride + x0 as usize * 4..y as usize * stride + x1 as usize * 4).unwrap_or_default();
|
||||
let pixels = || files.iter().flat_map(move |&[x0, y0, x1, y1]| (y0..y1).flat_map(move |y| row(y, x0, x1).as_chunks::<4>().0.iter()));
|
||||
let opaque = !transparency || pixels().all(|p| p[3] == 255);
|
||||
if !opaque {
|
||||
return (WebFormat::Gif, false);
|
||||
}
|
||||
let mut seen = HashSet::new();
|
||||
// An opaque pixel blends to itself.
|
||||
let few = pixels().all(|p| {
|
||||
seen.insert(flatten(p, matte).next().unwrap_or_default());
|
||||
seen.len() <= 256
|
||||
});
|
||||
(if few { WebFormat::Gif } else { WebFormat::Jpg }, true)
|
||||
}
|
||||
|
||||
/// Optimize to File Size: the settings, from `s`, whose files (the pixels `[x0, y0, x1, y1]` of
|
||||
/// `r`) fit in `target` bytes, measured together, or with `each` the largest one. At most
|
||||
/// [`OPTIMIZE_TRIALS`] trial settings are encoded, and a trial encodes the files one at a time.
|
||||
pub fn optimize_to_size(
|
||||
doc: &Document,
|
||||
r: &WebRender,
|
||||
files: &[[u32; 4]],
|
||||
s: &WebSettings,
|
||||
start: StartWith,
|
||||
each: bool,
|
||||
target: usize,
|
||||
) -> std::result::Result<SizeFit, String> {
|
||||
let mut t = Trials { doc, r, files, each, left: OPTIMIZE_TRIALS, used: 0 };
|
||||
let with = |format: WebFormat| WebSettings { format, ..s.clone() };
|
||||
let found = match start {
|
||||
_ if files.is_empty() => None,
|
||||
StartWith::Current => search_format(&mut t, s, target)?,
|
||||
StartWith::Auto => {
|
||||
let (first, opaque) = auto_format(r, files, s.transparency, s.matte_rgb()?.unwrap_or([255; 3]));
|
||||
let other = if first == WebFormat::Gif { WebFormat::Jpg } else { WebFormat::Gif };
|
||||
match search_format(&mut t, &with(first), target)? {
|
||||
Some(a) if !a.achieved && opaque => match search_format(&mut t, &with(other), target)? {
|
||||
Some(b) if b.achieved || b.bytes < a.bytes => Some(b),
|
||||
_ => Some(a),
|
||||
},
|
||||
a => a,
|
||||
}
|
||||
}
|
||||
};
|
||||
let mut best = found.ok_or("Optimize to File Size: there is no image to measure")?;
|
||||
best.trials = t.used;
|
||||
Ok(best)
|
||||
}
|
||||
|
||||
fn optimize_to_file_size(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const O: &str = "webExport.optimizeToFileSize";
|
||||
let k = p
|
||||
.get("desiredK")
|
||||
.and_then(Value::as_f64)
|
||||
.filter(|k| k.is_finite() && *k > 0.0 && *k <= MAX_DESIRED_K)
|
||||
.ok_or_else(|| bad(O, "give `desiredK`, the desired file size in K (1024 bytes): a number above 0 and at most 1048576"))?;
|
||||
let target = ((k * 1024.0).floor() as usize).max(1);
|
||||
let start = match p.get("startWith").map(Value::as_str) {
|
||||
None | Some(Some("current")) => StartWith::Current,
|
||||
Some(Some("auto")) => StartWith::Auto,
|
||||
Some(_) => return Err(bad(O, "`startWith` is `current` or `auto`")),
|
||||
};
|
||||
let scope = match p.get("use").map(Value::as_str) {
|
||||
None if p.get("slice").is_some() => "currentSlice",
|
||||
None => "allSlices",
|
||||
Some(Some(u @ ("allSlices" | "eachSlice" | "currentSlice"))) => u,
|
||||
Some(_) => return Err(bad(O, "`use` is `allSlices`, `eachSlice` or `currentSlice`")),
|
||||
};
|
||||
let slice = match p.get("slice").map(|v| v.as_u64().filter(|n| *n >= 1 && scope == "currentSlice")) {
|
||||
None => None,
|
||||
Some(Some(n)) => Some(n),
|
||||
Some(None) => return Err(bad(O, "`slice` is a slice number from `slice.list`, with `use: currentSlice`")),
|
||||
};
|
||||
let settings = s.web_settings(p).map_err(|e| bad(O, e))?;
|
||||
let st = s.doc()?;
|
||||
let doc = &st.doc;
|
||||
let failed = vectorcraft_render::decode_failures();
|
||||
let r = render(doc, &settings).map_err(|e| bad(O, e))?;
|
||||
let warnings = undecoded(failed);
|
||||
let areas = doc.slice_layout();
|
||||
let selected = super::slices::selected_slices(doc, &st.selection);
|
||||
let cells = cells(&areas, &selected, &settings, &r).map_err(|e| bad(O, e))?;
|
||||
let image_cells: Vec<&Cell> =
|
||||
cells.iter().filter(|c| c.area.id.and_then(|id| doc.slice_options(id)).is_none_or(|o| o.kind == SliceKind::Image)).collect();
|
||||
let picked: Vec<&Cell> = match (scope, slice) {
|
||||
("currentSlice", Some(n)) => {
|
||||
let c = image_cells.iter().find(|c| c.area.number as u64 == n);
|
||||
vec![*c.ok_or_else(|| bad(O, format!("no slice {n} in the image (see slice.list)")))?]
|
||||
}
|
||||
("currentSlice", None) => {
|
||||
image_cells.iter().find(|c| c.area.id.is_some_and(|id| selected.contains(&id))).or(image_cells.first()).copied().into_iter().collect()
|
||||
}
|
||||
_ => image_cells,
|
||||
};
|
||||
let files: Vec<[u32; 4]> = if cells.is_empty() { vec![[0, 0, r.width, r.height]] } else { picked.iter().map(|c| c.px).collect() };
|
||||
let fit = optimize_to_size(doc, &r, &files, &settings, start, scope == "eachSlice", target).map_err(|e| bad(O, e))?;
|
||||
Ok(json!({
|
||||
"targetBytes": target, "achieved": fit.achieved, "bytes": fit.bytes, "format": fit.settings.format.id(),
|
||||
"settings": fit.settings.to_json(), "trials": fit.trials, "images": files.len(), "warnings": warnings,
|
||||
}))
|
||||
}
|
||||
|
||||
fn settings(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const S: &str = "webExport.settings";
|
||||
let base = if bool_or(p, "reset", false) { WebSettings::default() } else { s.last_web_settings() };
|
||||
|
||||
@@ -3313,6 +3313,26 @@ fn flare_ring_seed_moves_only_the_rings() {
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flare_small_ring_seeds_spread_the_first_ring_along_the_path() {
|
||||
let mut s = session();
|
||||
let mut positions = Vec::new();
|
||||
for seed in [0, 1, 2, 5, 11, (1u64 << 53) - 1] {
|
||||
let p = json!({"cx": 20, "cy": 30, "x2": 1020, "y2": 30, "rays": 0, "rings": 1, "ringSeed": seed});
|
||||
let id = NodeId(s.execute("shape.flare", &p).unwrap()["id"].as_u64().unwrap());
|
||||
let NodeKind::Group { children, .. } = &s.doc().unwrap().doc.node(id).unwrap().kind else { panic!("flare is a group") };
|
||||
let ring = children.iter().find(|n| n.name.as_deref() == Some("Ring")).unwrap();
|
||||
let center = ring.geometric_bounds().unwrap().center();
|
||||
assert!((20.0..=1020.0).contains(¢er.x), "seed {seed}: {center:?}");
|
||||
assert!((center.y - 30.0).abs() < 1e-9);
|
||||
positions.push(center.x);
|
||||
}
|
||||
assert!((positions[0] - positions[1]).abs() > 1.0, "neighboring small seeds visibly move the first ring: {positions:?}");
|
||||
let lo = positions[..5].iter().copied().fold(f64::INFINITY, f64::min);
|
||||
let hi = positions[..5].iter().copied().fold(f64::NEG_INFINITY, f64::max);
|
||||
assert!(hi - lo > 250.0, "small seeds spread the first ring along the path: {positions:?}");
|
||||
}
|
||||
|
||||
/// `shape.ellipse` without `anchors`, or with 4, draws the live ellipse it always drew.
|
||||
#[test]
|
||||
fn ellipse_with_four_anchors_is_the_live_ellipse() {
|
||||
|
||||
@@ -246,6 +246,163 @@ fn export_3d_writes_into_a_folder_or_one_zip() {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A blue 100 × 100 square extruded straight on, with a red 10 × 20 graphic "Mark" mapped onto its
|
||||
/// front at its center and onto its back 30 pt to the right (as the back is seen from behind),
|
||||
/// collected as a 3D asset in `format`.
|
||||
fn mapped(format: &str) -> (Session, u64) {
|
||||
let mut s = session();
|
||||
let mark = run(&mut s, "path.create", json!({"d": "M300 300L310 300L310 320L300 320Z"}))["id"].clone();
|
||||
run(&mut s, "paint.setFill", json!({"color": "#ff0000"}));
|
||||
run(&mut s, "threeD.addGraphic", json!({"name": "Mark", "ids": [mark]}));
|
||||
let id = run(&mut s, "path.create", json!({"d": "M100 100L200 100L200 200L100 200Z"}))["id"].as_u64().unwrap();
|
||||
run(&mut s, "paint.setFill", json!({"color": "#0000ff"}));
|
||||
run(&mut s, "effect.apply", json!({"effect": "threeD.extrude", "params": {"rotationX": 0.0, "rotationY": 0.0, "rotationZ": 0.0, "depth": 20.0}}));
|
||||
run(&mut s, "threeD.mapGraphic", json!({"symbol": "Mark", "ids": [id]}));
|
||||
run(&mut s, "threeD.mapGraphic", json!({"symbol": "Mark", "face": "back", "x": 30.0, "ids": [id]}));
|
||||
run(&mut s, "layer.setProps", json!({"id": id, "name": "Box"}));
|
||||
let asset = run(&mut s, "assets.add3D", json!({"ids": [id], "format": format}))["assets"][0].as_u64().unwrap();
|
||||
(s, asset)
|
||||
}
|
||||
|
||||
/// The color of pixel `(x, y)` of PNG `png`.
|
||||
fn pixel(png: &[u8], x: u32, y: u32) -> [u8; 4] {
|
||||
image::load_from_memory(png).unwrap().to_rgba8().get_pixel(x, y).0
|
||||
}
|
||||
|
||||
fn is_red(p: [u8; 4]) -> bool {
|
||||
p[0] > 200 && p[1] < 50 && p[2] < 50 && p[3] == 255
|
||||
}
|
||||
|
||||
fn is_blue(p: [u8; 4]) -> bool {
|
||||
p[0] < 50 && p[1] < 50 && p[2] > 200 && p[3] == 255
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn export_3d_paints_mapped_graphics_on_their_caps_in_every_format() {
|
||||
for (format, names) in [
|
||||
("usda", vec!["Box.usda", "Box-texture-1.png", "Box-texture-2.png"]),
|
||||
("usdz", vec!["Box.usdz"]),
|
||||
("gltf", vec!["Box.gltf"]),
|
||||
("obj", vec!["Box.obj", "Box.mtl", "Box-texture-1.png", "Box-texture-2.png"]),
|
||||
] {
|
||||
let (mut s, _) = mapped(format);
|
||||
let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 128})));
|
||||
assert_eq!(out.iter().map(|(n, _)| n.as_str()).collect::<Vec<_>>(), names, "{format}");
|
||||
}
|
||||
// The front's picture: the cap's 100 pt across 128 pixels, blue with the red graphic at the
|
||||
// middle; the back's: the graphic 30 pt to the right as seen from behind, which is to the left
|
||||
// in the art's plane.
|
||||
let (mut s, _) = mapped("usda");
|
||||
let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 128})));
|
||||
let (front, back) = (&out[1].1, &out[2].1);
|
||||
assert_eq!(image::load_from_memory(front).unwrap().to_rgba8().dimensions(), (128, 128));
|
||||
assert!(is_red(pixel(front, 64, 64)) && is_blue(pixel(front, 2, 2)) && is_blue(pixel(front, 64, 10)));
|
||||
let at = |pt: f64| (pt * 1.28) as u32;
|
||||
assert!(is_red(pixel(back, at(20.0), 64)) && is_blue(pixel(back, 64, 64)), "{:?}", pixel(back, 64, 64));
|
||||
// The USDA's front cap shows the front picture through st, up from the picture's bottom.
|
||||
let usda = String::from_utf8(out[0].1.clone()).unwrap();
|
||||
assert_eq!(usda.matches("primvars:st").count(), 2);
|
||||
assert_eq!(usda.matches("def Mesh").count(), 3, "the walls, the front cap and the back cap");
|
||||
// glTF holds both pictures, and a cap's coordinates stay inside its picture.
|
||||
let (mut s, _) = mapped("gltf");
|
||||
let out = files(&run(&mut s, "assets.export3D", json!({})));
|
||||
let g: Value = serde_json::from_slice(&out[0].1).unwrap();
|
||||
assert_eq!(g["images"].as_array().map(Vec::len), Some(2));
|
||||
let png = vectorcraft_format::base64_decode(g["images"][0]["uri"].as_str().unwrap().split(',').nth(1).unwrap()).unwrap();
|
||||
assert_eq!(image::load_from_memory(&png).unwrap().to_rgba8().dimensions(), (1024, 1024), "1024 pixels by default");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_texture_takes_the_opacity_of_the_fill_and_of_the_object_as_the_canvas_draws_them() {
|
||||
let half = |a: u8| (120..=135).contains(&a);
|
||||
// A half-opaque fill: the face and the graphic over it are each drawn at half opacity, so the
|
||||
// graphic covers three quarters.
|
||||
let (mut s, asset) = mapped("usda");
|
||||
let doc = &s.active().unwrap().doc;
|
||||
let id = doc.asset(asset).unwrap().nodes[0];
|
||||
let fill = doc.node(id).unwrap().appearance.items.iter().position(|i| matches!(i, vectorcraft_doc::AppearanceItem::Fill(_))).unwrap();
|
||||
run(&mut s, "select.set", json!({"ids": [id.0]}));
|
||||
run(&mut s, "transparency.set", json!({"item": fill, "opacity": 50}));
|
||||
let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 128})));
|
||||
let (on, around) = (pixel(&out[1].1, 64, 64), pixel(&out[1].1, 2, 2));
|
||||
assert!(on[0] > on[2] && (185..=197).contains(&on[3]), "{on:?}");
|
||||
assert!(around[2] > 200 && half(around[3]), "{around:?}");
|
||||
let usda = String::from_utf8(out[0].1.clone()).unwrap();
|
||||
assert!(usda.contains("float inputs:opacity.connect"), "the texture's alpha is the opacity");
|
||||
// An OBJ's opacity map has the alpha as gray levels.
|
||||
run(&mut s, "assets.set3DFormat", json!({"assets": [asset], "format": "obj"}));
|
||||
let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 128})));
|
||||
assert_eq!(out[3].0, "Box-texture-1-opacity.png");
|
||||
let gray = image::load_from_memory(&out[3].1).unwrap().to_luma8();
|
||||
let (g_on, g_around) = (gray.get_pixel(64, 64).0[0], gray.get_pixel(2, 2).0[0]);
|
||||
assert!((185..=197).contains(&g_on) && half(g_around), "{g_on} {g_around}");
|
||||
// A half-opaque object: the face and the graphic are drawn opaque, and the whole picture at
|
||||
// half opacity.
|
||||
let (mut s, asset) = mapped("usda");
|
||||
let id = s.active().unwrap().doc.asset(asset).unwrap().nodes[0];
|
||||
run(&mut s, "transparency.set", json!({"ids": [id.0], "opacity": 50}));
|
||||
let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 128})));
|
||||
let (on, around) = (pixel(&out[1].1, 64, 64), pixel(&out[1].1, 2, 2));
|
||||
assert!(on[0] > 200 && on[2] < 50 && half(on[3]), "{on:?}");
|
||||
assert!(around[2] > 200 && around[0] < 50 && half(around[3]), "{around:?}");
|
||||
// A gradient whose stops are clear: the face is clear, and the graphic keeps its opacity.
|
||||
let (mut s, asset) = mapped("usda");
|
||||
let id = s.active().unwrap().doc.asset(asset).unwrap().nodes[0];
|
||||
run(&mut s, "select.set", json!({"ids": [id.0]}));
|
||||
let clear = json!({"stops": [{"offset": 0, "color": "#0000ff", "opacity": 0}, {"offset": 1, "color": "#0000ff", "opacity": 0}]});
|
||||
run(&mut s, "paint.setFill", json!({"gradient": clear}));
|
||||
let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 128})));
|
||||
let (on, around) = (pixel(&out[1].1, 64, 64), pixel(&out[1].1, 2, 2));
|
||||
assert!(is_red(on), "{on:?}");
|
||||
assert_eq!(around[3], 0, "{around:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn export_3d_keeps_flat_colors_without_graphics_and_refuses_bad_texture_sizes() {
|
||||
let (mut s, asset) = mapped("obj");
|
||||
for bad in [json!(64), json!(5000), json!(512.5), json!("512"), json!(-1)] {
|
||||
assert!(s.execute("assets.export3D", &json!({"textureSize": bad})).is_err(), "{bad}");
|
||||
}
|
||||
// Without its graphics the box is one plain mesh, as before.
|
||||
let id = s.doc().unwrap().doc.asset(asset).unwrap().nodes[0].0;
|
||||
run(&mut s, "select.set", json!({"ids": [id]}));
|
||||
run(&mut s, "effect.setParams", json!({"index": 0, "params": {"graphics": []}}));
|
||||
let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 128})));
|
||||
assert_eq!(out.iter().map(|(n, _)| n.as_str()).collect::<Vec<_>>(), ["Box.obj", "Box.mtl"]);
|
||||
let obj = String::from_utf8(out[0].1.clone()).unwrap();
|
||||
assert!(!obj.contains("vt ") && obj.lines().filter(|l| l.starts_with("g ")).count() == 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn texture_pixels_are_counted_across_one_export() {
|
||||
let (s, asset) = mapped("gltf");
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let node = d.node(d.asset(asset).unwrap().nodes[0]).unwrap();
|
||||
let parts = vectorcraft_render::effects::three_d_meshes_in(Some(d), node).unwrap();
|
||||
let mut pixels = 0;
|
||||
let made = crate::cmd::fileio::textures(d, &parts, 128, &mut pixels).unwrap();
|
||||
assert_eq!((made.iter().flatten().count(), pixels), (2, 2 * 128 * 128));
|
||||
let mut pixels = crate::cmd::fileio::MAX_TEXTURE_PIXELS - 128 * 128;
|
||||
let e = crate::cmd::fileio::textures(d, &parts, 128, &mut pixels).unwrap_err();
|
||||
assert!(e.contains("textureSize"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_graphics_that_draw_count_as_textures() {
|
||||
let parts_of = |s: &Session, asset: u64| {
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let node = d.node(d.asset(asset).unwrap().nodes[0]).unwrap();
|
||||
vectorcraft_render::effects::three_d_meshes_in(Some(d), node).unwrap()
|
||||
};
|
||||
let (mut s, asset) = mapped("obj");
|
||||
assert!(crate::cmd::fileio::draws_textures(&s.doc().unwrap().doc, &parts_of(&s, asset)));
|
||||
// With its symbol gone the graphic draws nothing, so the export writes no texture.
|
||||
run(&mut s, "symbol.delete", json!({"name": "Mark"}));
|
||||
assert!(!crate::cmd::fileio::draws_textures(&s.doc().unwrap().doc, &parts_of(&s, asset)));
|
||||
let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 128})));
|
||||
assert_eq!(out.iter().map(|(n, _)| n.as_str()).collect::<Vec<_>>(), ["Box.obj", "Box.mtl"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn three_d_assets_round_trip_through_the_native_format() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -428,6 +428,75 @@ fn transform_panel_sizes_follow_the_turned_box() {
|
||||
assert!(near(angle(&s, a), 45.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_bounds_whole_number_references_match_integer_references() {
|
||||
for direct in [false, true] {
|
||||
for index in 0..=9 {
|
||||
let run = |reference: Value| {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 10.0, 20.0, 100.0, 50.0);
|
||||
sel(&mut s, &[a]);
|
||||
if direct {
|
||||
s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 0], [0, 2]], "mode": "set"})).unwrap();
|
||||
}
|
||||
let before = anchors(&s, a);
|
||||
let selection = s.doc().unwrap().selection.clone();
|
||||
let n = undo_len(&s);
|
||||
s.execute("object.setBounds", &json!({"x": 200, "y": 300, "reference": reference})).unwrap();
|
||||
assert_eq!(undo_len(&s), n + 1);
|
||||
assert_eq!(s.doc().unwrap().selection, selection);
|
||||
if !direct {
|
||||
let b = selection_box(&s);
|
||||
assert!(b.reference_point(index.min(8)).distance(Point::new(200.0, 300.0)) < 1e-6, "{b:?}");
|
||||
}
|
||||
let after = anchors(&s, a);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(anchors(&s, a), before);
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
assert_eq!(anchors(&s, a), after);
|
||||
after
|
||||
};
|
||||
assert_eq!(run(json!(index as f64)), run(json!(index)), "reference {index}, direct {direct}");
|
||||
if index == 8 {
|
||||
assert_eq!(run(json!(u64::MAX)), run(json!(8)), "large reference, direct {direct}");
|
||||
assert_eq!(run(json!(1e100)), run(json!(8)), "large float reference, direct {direct}");
|
||||
}
|
||||
}
|
||||
}
|
||||
for reference in [None, Some(Value::Null)] {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 10.0, 20.0, 100.0, 50.0);
|
||||
sel(&mut s, &[a]);
|
||||
let mut p = json!({"x": 200, "y": 300});
|
||||
if let Some(reference) = reference {
|
||||
p["reference"] = reference;
|
||||
}
|
||||
s.execute("object.setBounds", &p).unwrap();
|
||||
assert!(selection_box(&s).center().distance(Point::new(200.0, 300.0)) < 1e-6);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_bounds_rejects_invalid_references_without_changes() {
|
||||
for direct in [false, true] {
|
||||
for reference in [json!(-1), json!(-1.0), json!(0.5), json!(8.5), json!("0"), json!(true), json!([]), json!({})] {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 10.0, 20.0, 100.0, 50.0);
|
||||
sel(&mut s, &[a]);
|
||||
if direct {
|
||||
s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 0], [0, 2]], "mode": "set"})).unwrap();
|
||||
}
|
||||
let before = anchors(&s, a);
|
||||
let selection = s.doc().unwrap().selection.clone();
|
||||
let n = undo_len(&s);
|
||||
assert!(s.execute("object.setBounds", &json!({"x": 200, "y": 300, "reference": reference})).is_err(), "{reference}, direct {direct}");
|
||||
assert_eq!(anchors(&s, a), before);
|
||||
assert_eq!(s.doc().unwrap().selection, selection);
|
||||
assert_eq!(undo_len(&s), n);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reset_bounding_box_squares_the_box_in_one_step() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -4762,6 +4762,279 @@ fn live_paint_refuses_type_and_images_and_changes_nothing() {
|
||||
assert!(!vectorcraft_tools::builder::live_paint_takes(&node(&s, text_group)));
|
||||
}
|
||||
|
||||
/// A horizontal open path across [`live`]'s group at `y`, drawn with the Pen's defaults.
|
||||
fn line_across(s: &mut Session, y: f64) -> NodeId {
|
||||
let r = s.execute("path.create", &json!({"anchors": [{"x": -10, "y": y}, {"x": 160, "y": y}]})).unwrap();
|
||||
NodeId(r["id"].as_u64().unwrap())
|
||||
}
|
||||
|
||||
/// Paths drawn in an isolated Live Paint group join it when isolation mode ends: they go among its
|
||||
/// sources and cut the faces they cross, which take their sources' fill, a painted face they do not
|
||||
/// cross keeps its fill, and the whole addition is one undo step, which Undo takes back to the
|
||||
/// drawn paths in the group and Redo makes again.
|
||||
#[test]
|
||||
fn live_paint_isolation_adds_drawn_paths_on_exit() {
|
||||
use vectorcraft_tools::builder::{face_at, faces, sources};
|
||||
let green = Paint::solid(Color::from_hex("#00ff00").unwrap());
|
||||
let mut s = session();
|
||||
let g = live(&mut s);
|
||||
s.execute("livePaint.fill", &json!({"group": g.0, "point": [125, 50], "color": "#00ff00"})).unwrap();
|
||||
s.execute("object.isolate", &json!({"id": g.0})).unwrap();
|
||||
// Two lines from left of the group that end in its right face, so they cut only the other two.
|
||||
let line = |s: &mut Session, y: f64| {
|
||||
let r = s.execute("path.create", &json!({"anchors": [{"x": -10, "y": y}, {"x": 105, "y": y}]})).unwrap();
|
||||
NodeId(r["id"].as_u64().unwrap())
|
||||
};
|
||||
let (a, b) = (line(&mut s, 30.0), line(&mut s, 70.0));
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(a), Some(g), "a path drawn in isolation goes into the group");
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
s.execute("object.exitIsolation", &json!({})).unwrap();
|
||||
let d = s.doc().unwrap();
|
||||
assert_eq!(d.isolation, None);
|
||||
assert_eq!(d.history.undo.len(), steps + 1, "both paths join in one undo step");
|
||||
assert_eq!(d.selection.objects, vec![g]);
|
||||
let n = node(&s, g);
|
||||
let src = sources(&n).unwrap();
|
||||
assert_eq!(src.children().unwrap().len(), 4);
|
||||
for id in [a, b] {
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(id), Some(src.id), "{id} joined the sources");
|
||||
}
|
||||
assert_eq!(faces(&n).len(), 7, "two lines cut each of the two faces they cross in three");
|
||||
assert_eq!(face_at(&n, Point::new(125.0, 50.0)).unwrap().appearance.fill_paint(), green, "the face the lines do not cross keeps its fill");
|
||||
let red = Paint::solid(Color::rgb(1.0, 0.0, 0.0));
|
||||
for y in [15.0, 85.0] {
|
||||
assert_eq!(face_at(&n, Point::new(25.0, y)).unwrap().appearance.fill_paint(), red, "a new face takes its source's fill");
|
||||
}
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
let n = node(&s, g);
|
||||
assert_eq!(faces(&n).len(), 3);
|
||||
assert_eq!(sources(&n).unwrap().children().unwrap().len(), 2);
|
||||
for id in [a, b] {
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(id), Some(g), "Undo puts {id} back in the group as drawn");
|
||||
}
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
assert_eq!(faces(&node(&s, g)).len(), 7);
|
||||
}
|
||||
|
||||
/// Leaving isolation mode in a Live Paint group with nothing drawn in it records no undo step and
|
||||
/// leaves the document as it is. Type, and a path that is hidden, stay in the group as they are,
|
||||
/// while a group of paths drawn beside them joins it.
|
||||
#[test]
|
||||
fn live_paint_isolation_adds_only_paths_it_takes() {
|
||||
use vectorcraft_tools::builder::{faces, sources};
|
||||
let mut s = session();
|
||||
let g = live(&mut s);
|
||||
s.execute("object.isolate", &json!({"id": g.0})).unwrap();
|
||||
let before = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len());
|
||||
s.execute("object.exitIsolation", &json!({})).unwrap();
|
||||
assert!(s.doc().unwrap().doc == before.0, "an exit with nothing drawn changes nothing");
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), before.1, "and records no undo step");
|
||||
s.execute("object.isolate", &json!({"id": g.0})).unwrap();
|
||||
let text = NodeId(s.execute("text.create", &json!({"x": 20, "y": 20, "text": "Hi"})).unwrap()["id"].as_u64().unwrap());
|
||||
let hidden = line_across(&mut s, 50.0);
|
||||
s.edit("t", |d, _| {
|
||||
d.node_mut(hidden).unwrap().visible = false;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
s.execute("object.exitIsolation", &json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps, "type and a hidden path add nothing");
|
||||
assert_eq!(faces(&node(&s, g)).len(), 3);
|
||||
s.execute("object.isolate", &json!({"id": g.0})).unwrap();
|
||||
let (a, b) = (line_across(&mut s, 30.0), line_across(&mut s, 70.0));
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
let paths = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(paths), Some(g));
|
||||
s.execute("object.exitIsolation", &json!({})).unwrap();
|
||||
let n = node(&s, g);
|
||||
assert_eq!(faces(&n).len(), 9, "the group of paths joined");
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_eq!(d.parent_of(paths), Some(sources(&n).unwrap().id));
|
||||
for id in [text, hidden] {
|
||||
assert_eq!(d.parent_of(id), Some(g), "{id} stays in the group");
|
||||
assert!(d.node(id).is_some());
|
||||
}
|
||||
}
|
||||
|
||||
/// A group drawn in an isolated Live Paint group that holds a locked path stays in it as it is when
|
||||
/// isolation mode ends, as a locked path drawn there does.
|
||||
#[test]
|
||||
fn live_paint_isolation_leaves_a_group_holding_a_locked_path() {
|
||||
use vectorcraft_tools::builder::faces;
|
||||
let mut s = session();
|
||||
let g = live(&mut s);
|
||||
s.execute("object.isolate", &json!({"id": g.0})).unwrap();
|
||||
let (a, b) = (line_across(&mut s, 30.0), line_across(&mut s, 70.0));
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
let paths = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
s.edit("t", |d, _| {
|
||||
d.node_mut(b).unwrap().locked = true;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
s.execute("object.exitIsolation", &json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps);
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(paths), Some(g));
|
||||
assert_eq!(faces(&node(&s, g)).len(), 3);
|
||||
}
|
||||
|
||||
/// Type drawn in an isolated Live Paint group stays in it when Gap Options or Merge make the group's
|
||||
/// faces and edges again, including type in a Live Paint group merged into another, and Release
|
||||
/// puts it beside the released paths.
|
||||
#[test]
|
||||
fn live_paint_keeps_type_drawn_in_it_through_gap_options_merge_and_release() {
|
||||
let mut s = session();
|
||||
let g = live(&mut s);
|
||||
s.execute("object.isolate", &json!({"id": g.0})).unwrap();
|
||||
let text = NodeId(s.execute("text.create", &json!({"x": 20, "y": 20, "text": "Hi"})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("object.exitIsolation", &json!({})).unwrap();
|
||||
s.execute("livePaint.gapOptions", &json!({"ids": [g.0], "detect": true})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(text), Some(g), "Gap Options keeps the type");
|
||||
let c = rect(&mut s, 120.0, 20.0, 100.0, 20.0);
|
||||
s.execute("livePaint.merge", &json!({"ids": [g.0, c.0]})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(text), Some(g), "Merge keeps the type");
|
||||
let other = rect(&mut s, 300.0, 300.0, 50.0, 50.0);
|
||||
let h = NodeId(s.execute("livePaint.make", &json!({"ids": [other.0]})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("object.isolate", &json!({"id": h.0})).unwrap();
|
||||
let text2 = NodeId(s.execute("text.create", &json!({"x": 310, "y": 320, "text": "Yo"})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("object.exitIsolation", &json!({})).unwrap();
|
||||
s.execute("livePaint.merge", &json!({"ids": [g.0, h.0]})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(text2), Some(g), "the type of the merged group moves with its paths");
|
||||
s.execute("livePaint.release", &json!({"ids": [g.0]})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
for id in [text, text2] {
|
||||
assert_eq!(d.parent_of(id), d.default_layer(), "Release keeps {id}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Art drawn in an isolated Live Paint group and named like one of the group's parts is not taken
|
||||
/// for one: type named "Live Paint Sources" stays in the group through Gap Options, and a group of
|
||||
/// paths named "Face" joins the group when isolation mode ends.
|
||||
#[test]
|
||||
fn live_paint_isolation_keeps_art_named_like_its_parts() {
|
||||
use vectorcraft_tools::builder::{SOURCES_NAME, faces, sources};
|
||||
let mut s = session();
|
||||
let g = live(&mut s);
|
||||
s.execute("object.isolate", &json!({"id": g.0})).unwrap();
|
||||
let text = NodeId(s.execute("text.create", &json!({"x": 20, "y": 20, "text": "Hi"})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("object.setProps", &json!({"id": text.0, "name": SOURCES_NAME})).unwrap();
|
||||
let (a, b) = (line_across(&mut s, 30.0), line_across(&mut s, 70.0));
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
let paths = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("object.setProps", &json!({"id": paths.0, "name": "Face"})).unwrap();
|
||||
s.execute("object.exitIsolation", &json!({})).unwrap();
|
||||
let n = node(&s, g);
|
||||
assert_eq!(faces(&n).len(), 9, "the group named Face joined");
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(paths), Some(sources(&n).unwrap().id));
|
||||
s.execute("livePaint.gapOptions", &json!({"ids": [g.0], "detect": true})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(text), Some(g), "Gap Options keeps the type named like the sources");
|
||||
}
|
||||
|
||||
/// Type drawn in an isolated Live Paint group under the name of a face, an edge or the sources
|
||||
/// group is not one of the group's parts: Gap Options, Info and Make count only the faces and edges
|
||||
/// Live Paint made, and Expand keeps the type.
|
||||
#[test]
|
||||
fn live_paint_does_not_count_art_named_like_its_parts() {
|
||||
use vectorcraft_tools::builder::{EDGE_NAME, FACE_NAME, SOURCES_NAME};
|
||||
let mut s = session();
|
||||
let g = live(&mut s);
|
||||
let edges = s.execute("livePaint.info", &json!({"group": g.0})).unwrap()["edges"].as_array().unwrap().len();
|
||||
s.execute("object.isolate", &json!({"id": g.0})).unwrap();
|
||||
let mut texts = vec![];
|
||||
for (i, name) in [FACE_NAME, EDGE_NAME, SOURCES_NAME].into_iter().enumerate() {
|
||||
let r = s.execute("text.create", &json!({"x": 20 + 20 * i, "y": 20, "text": "Hi"})).unwrap();
|
||||
let t = NodeId(r["id"].as_u64().unwrap());
|
||||
s.execute("object.setProps", &json!({"id": t.0, "name": name})).unwrap();
|
||||
texts.push(t);
|
||||
}
|
||||
s.execute("object.exitIsolation", &json!({})).unwrap();
|
||||
let r = s.execute("livePaint.gapOptions", &json!({"ids": [g.0], "detect": true})).unwrap();
|
||||
assert_eq!(r["faces"], 3, "Gap Options counts the faces Live Paint made");
|
||||
let info = s.execute("livePaint.info", &json!({"group": g.0})).unwrap();
|
||||
assert_eq!(info["faces"].as_array().unwrap().len(), 3);
|
||||
assert_eq!(info["edges"].as_array().unwrap().len(), edges);
|
||||
let r = s.execute("livePaint.make", &json!({"ids": [g.0]})).unwrap();
|
||||
assert_eq!((r["faces"].as_u64(), r["edges"].as_u64()), (Some(3), Some(edges as u64)));
|
||||
s.execute("livePaint.expand", &json!({"ids": [g.0]})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
for t in texts {
|
||||
assert_eq!(d.parent_of(t), Some(g), "Expand keeps {t}");
|
||||
}
|
||||
}
|
||||
|
||||
/// With Real-time Drawing and Editing off, a rectangle still being drawn in a Live Paint group
|
||||
/// isolated in a pattern tile is drawn first when Exit Isolation Mode leaves pattern editing, and
|
||||
/// joins the group with the tile saved.
|
||||
#[test]
|
||||
fn live_paint_in_a_pattern_tile_adds_a_shape_still_being_drawn_on_exit() {
|
||||
use vectorcraft_tools::builder::{is_live_paint, sources};
|
||||
let mut s = session();
|
||||
two(&mut s);
|
||||
s.execute("object.pattern.make", &json!({"name": "P"})).unwrap();
|
||||
let g = NodeId(s.execute("livePaint.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("object.isolate", &json!({"id": g.0})).unwrap();
|
||||
s.execute("prefs.set", &json!({"key": "realTimeDrawing", "value": false})).unwrap();
|
||||
let v = ViewInfo::default();
|
||||
s.select_tool("rectangle", v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 10.0, 10.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, 40.0, 40.0), v).unwrap();
|
||||
assert!(s.interaction_unapplied());
|
||||
s.execute("object.exitIsolation", &json!({})).unwrap();
|
||||
let st = s.doc().unwrap();
|
||||
assert!(st.doc.pattern_edit.is_none());
|
||||
let art = &st.doc.pattern("P").unwrap().art;
|
||||
let n = art.iter().find(|n| is_live_paint(n)).expect("the tile holds the Live Paint group");
|
||||
assert_eq!(sources(n).unwrap().children().unwrap().len(), 3, "the rectangle joined the sources");
|
||||
}
|
||||
|
||||
/// Isolating a level outside an isolated Live Paint group, as the isolation bar's back arrow does,
|
||||
/// leaves the group and adds the paths drawn in it; isolating a path drawn in it does not.
|
||||
#[test]
|
||||
fn live_paint_isolation_adds_drawn_paths_when_isolating_a_level_outside() {
|
||||
use vectorcraft_tools::builder::{faces, sources};
|
||||
let mut s = session();
|
||||
let g = live(&mut s);
|
||||
s.execute("object.isolate", &json!({"id": g.0})).unwrap();
|
||||
let a = line_across(&mut s, 50.0);
|
||||
s.execute("object.isolate", &json!({"id": a.0})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(a), Some(g), "the path is still being drawn in the group");
|
||||
assert_eq!(faces(&node(&s, g)).len(), 3);
|
||||
let layer = s.doc().unwrap().doc.parent_of(g).unwrap();
|
||||
s.execute("object.isolate", &json!({"id": layer.0})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().isolation, Some(layer));
|
||||
let n = node(&s, g);
|
||||
assert_eq!(faces(&n).len(), 6);
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(a), Some(sources(&n).unwrap().id));
|
||||
}
|
||||
|
||||
/// A group of paths drawn in an isolated Live Paint group and then isolated itself joins the Live
|
||||
/// Paint group when isolation mode ends, or when a level outside the Live Paint group is isolated.
|
||||
#[test]
|
||||
fn live_paint_isolation_adds_a_drawn_group_isolated_inside_it() {
|
||||
use vectorcraft_tools::builder::{faces, sources};
|
||||
for to_layer in [false, true] {
|
||||
let mut s = session();
|
||||
let g = live(&mut s);
|
||||
s.execute("object.isolate", &json!({"id": g.0})).unwrap();
|
||||
let (a, b) = (line_across(&mut s, 30.0), line_across(&mut s, 70.0));
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
let paths = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("object.isolate", &json!({"id": paths.0})).unwrap();
|
||||
assert_eq!(faces(&node(&s, g)).len(), 3, "isolating the drawn group stays in the Live Paint group");
|
||||
if to_layer {
|
||||
let layer = s.doc().unwrap().doc.parent_of(g).unwrap();
|
||||
s.execute("object.isolate", &json!({"id": layer.0})).unwrap();
|
||||
} else {
|
||||
s.execute("object.exitIsolation", &json!({})).unwrap();
|
||||
}
|
||||
let n = node(&s, g);
|
||||
assert_eq!(faces(&n).len(), 9, "the drawn group joined (to the layer: {to_layer})");
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(paths), Some(sources(&n).unwrap().id));
|
||||
}
|
||||
}
|
||||
|
||||
/// Give Live Paint group `g` a lock, hidden state, appearance, knockout, opacity mask and
|
||||
/// graphic style link, and return it as it then is.
|
||||
fn dress_live_group(s: &mut Session, g: NodeId) -> Node {
|
||||
|
||||
@@ -95,3 +95,50 @@ fn new_swatch_saves_several_colours_in_one_step() {
|
||||
assert!(s.execute("swatch.new", &json!({"colors": []})).is_err());
|
||||
assert!(s.execute("swatch.new", &json!({"colors": ["nope"]})).is_err());
|
||||
}
|
||||
|
||||
/// The tint swatch a swatch named `name` is: (base, tint 0..1); none for any other swatch.
|
||||
fn tint_of(s: &Session, name: &str) -> Option<(String, f32)> {
|
||||
s.doc().unwrap().doc.swatch(name)?.tint_of().map(|(b, t)| (b.to_string(), t))
|
||||
}
|
||||
|
||||
/// `{swatch, tint}` entries of `swatch.new {colors}` and `swatch.newGroup {colors}` make tint
|
||||
/// swatches linked to their spot color, beside plain colors, in one undo step; the tints follow an
|
||||
/// edit of the spot color; a bad entry saves nothing.
|
||||
#[test]
|
||||
fn colors_entries_naming_a_spot_color_save_tint_swatches() {
|
||||
let mut s = session();
|
||||
s.execute("swatch.new", &json!({"name": "Ink", "color": "#0066cc", "spot": true})).unwrap();
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
let r = s.execute("swatch.new", &json!({"colors": [{"swatch": "Ink", "tint": 60}, "#112233", {"swatch": "Ink", "tint": 30}]})).unwrap();
|
||||
let names = hexes(&r["names"]);
|
||||
assert_eq!(names, ["Ink 60%", "R=17 G=34 B=51", "Ink 30%"]);
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "one undo step");
|
||||
let (base, tint) = tint_of(&s, "Ink 60%").expect("a tint swatch");
|
||||
assert_eq!(base, "Ink");
|
||||
assert!((tint - 0.6).abs() < 1e-6, "{tint}");
|
||||
assert!(tint_of(&s, "R=17 G=34 B=51").is_none());
|
||||
let r = s.execute("swatch.newGroup", &json!({"name": "Guide", "colors": [{"swatch": "Ink", "tint": 45}, "#445566", {"swatch": "Ink"}]})).unwrap();
|
||||
let members = hexes(&r["swatches"]);
|
||||
assert_eq!(members[0], "Ink 45%");
|
||||
assert_eq!(tint_of(&s, "Ink 45%").map(|(b, _)| b).as_deref(), Some("Ink"));
|
||||
assert!(members[1..].iter().all(|m| tint_of(&s, m).is_none()), "a color and the full spot color are process copies: {members:?}");
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let full = d.swatch(&members[2]).unwrap();
|
||||
assert!(!full.spot && !full.global, "{full:?}");
|
||||
// The tint swatches follow an edit of the spot color.
|
||||
s.execute("swatch.edit", &json!({"name": "Ink", "color": "#cc0000"})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let ink = d.global_color("Ink").unwrap();
|
||||
for name in ["Ink 60%", "Ink 45%"] {
|
||||
let w = d.swatch(name).unwrap();
|
||||
let t = w.tint_of().unwrap().1;
|
||||
assert_eq!(w.paint.color().map(|c| c.to_hex()), Some(ink.tinted(t).to_hex()), "{name}");
|
||||
}
|
||||
// A missing swatch, a tint of a process color or a tint that is not a number saves nothing.
|
||||
let count = s.doc().unwrap().doc.swatches_iter().count();
|
||||
for bad in [json!({"swatch": "Nope", "tint": 50}), json!({"swatch": "R=17 G=34 B=51", "tint": 50}), json!({"swatch": "Ink", "tint": "half"})] {
|
||||
assert!(s.execute("swatch.new", &json!({"colors": ["#010203", bad]})).is_err(), "{bad}");
|
||||
assert!(s.execute("swatch.newGroup", &json!({"colors": ["#010203", bad]})).is_err(), "{bad}");
|
||||
}
|
||||
assert_eq!(s.doc().unwrap().doc.swatches_iter().count(), count);
|
||||
}
|
||||
|
||||
@@ -506,3 +506,92 @@ fn arc_rotation_turns_it_and_must_be_a_number() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The outer end of the spiral `id`.
|
||||
fn spiral_outer_end(s: &Session, id: NodeId) -> Point {
|
||||
*path_points(s, id).last().unwrap()
|
||||
}
|
||||
|
||||
/// A spiral dragged out turns about its center so that its outer end is at the pointer, in every
|
||||
/// direction and with a turned Constrain Angle too; its bounding box stays on the page, except
|
||||
/// along the turned x axis, where it is the click dialog's spiral with its turned box.
|
||||
#[test]
|
||||
fn a_dragged_spiral_turns_its_outer_end_to_the_pointer() {
|
||||
let mut s = new_doc();
|
||||
for deg in [0.0, 30.0] {
|
||||
set_angle(&mut s, deg);
|
||||
s.select_tool("spiral", ViewInfo::default()).unwrap();
|
||||
for (x, y) in [(260.0, 200.0), (200.0, 260.0), (140.0, 200.0), (200.0, 140.0), (240.0, 170.0)] {
|
||||
gesture(&mut s, Mods::default(), &[(Down, 200.0, 200.0), (Drag, 230.0, 230.0), (Drag, x, y), (Up, x, y)]);
|
||||
let id = last_id(&s);
|
||||
let end = spiral_outer_end(&s, id);
|
||||
assert!(near(end, x, y), "{deg}°, to ({x}, {y}): {end:?}");
|
||||
assert_eq!(bbox_angle(&s, id).to_bits(), 0.0f64.to_bits(), "{deg}°, to ({x}, {y})");
|
||||
}
|
||||
}
|
||||
let mut s = new_doc();
|
||||
set_angle(&mut s, 90.0);
|
||||
s.select_tool("spiral", ViewInfo::default()).unwrap();
|
||||
gesture(&mut s, Mods::default(), &[(Down, 200.0, 200.0), (Drag, 230.0, 230.0), (Drag, 200.0, 150.0), (Up, 200.0, 150.0)]);
|
||||
let id = last_id(&s);
|
||||
assert_eq!(spiral_outer_end(&s, id), Point::new(200.0, 150.0));
|
||||
assert_eq!(bbox_angle(&s, id), 90.0, "along the turned x axis");
|
||||
}
|
||||
|
||||
/// A spiral placed by the click dialog starts along the turned x axis, about the click: at 90° its
|
||||
/// outer end is straight above the center, exactly, and its bounding box turns with it; at 0°, a
|
||||
/// whole turn and with a `rotation` given the dialog's params are unchanged.
|
||||
#[test]
|
||||
fn constrain_angle_turns_a_click_made_spiral() {
|
||||
let mut s = new_doc();
|
||||
let click = Point::new(200.0, 200.0);
|
||||
let p = json!({"cx": 200.0, "cy": 200.0, "radius": 50.0, "decay": 80.0, "segments": 10, "clockwise": true});
|
||||
assert_eq!(constrain_click(&s, "shape.spiral", p.clone(), click), p, "0°");
|
||||
set_angle(&mut s, 360.0);
|
||||
assert_eq!(constrain_click(&s, "shape.spiral", p.clone(), click), p, "a whole turn");
|
||||
set_angle(&mut s, 90.0);
|
||||
let mut given = p.clone();
|
||||
given["rotation"] = json!(10.0);
|
||||
assert_eq!(constrain_click(&s, "shape.spiral", given.clone(), click), given, "a given rotation");
|
||||
let turned = constrain_click(&s, "shape.spiral", p.clone(), click);
|
||||
assert_eq!(turned["rotation"], json!(-90.0));
|
||||
let id = NodeId(s.execute("shape.spiral", &turned).unwrap()["id"].as_u64().unwrap());
|
||||
assert_eq!(spiral_outer_end(&s, id), Point::new(200.0, 150.0));
|
||||
assert_eq!(bbox_angle(&s, id), 90.0);
|
||||
set_angle(&mut s, 30.0);
|
||||
let id = NodeId(s.execute("shape.spiral", &constrain_click(&s, "shape.spiral", p, click)).unwrap()["id"].as_u64().unwrap());
|
||||
let r = 30f64.to_radians();
|
||||
let end = spiral_outer_end(&s, id);
|
||||
assert!(near(end, 200.0 + 50.0 * r.cos(), 200.0 - 50.0 * r.sin()), "{end:?}");
|
||||
assert!(close(bbox_angle(&s, id), 30.0), "{}", bbox_angle(&s, id));
|
||||
}
|
||||
|
||||
/// `shape.spiral` turns by an explicit `rotation` (clockwise) about its center; 0 and a whole
|
||||
/// turn draw it exactly as without one; a `rotation` that is not a number is refused and adds
|
||||
/// nothing.
|
||||
#[test]
|
||||
fn spiral_rotation_turns_it_and_must_be_a_number() {
|
||||
let mut s = new_doc();
|
||||
let base = json!({"cx": 100, "cy": 100, "radius": 40, "segments": 6});
|
||||
let with = |r: Value| {
|
||||
let mut p = base.clone();
|
||||
p["rotation"] = r;
|
||||
p
|
||||
};
|
||||
let plain = NodeId(s.execute("shape.spiral", &base).unwrap()["id"].as_u64().unwrap());
|
||||
let plain = path_points(&s, plain);
|
||||
assert_eq!(*plain.last().unwrap(), Point::new(140.0, 100.0), "upright: the outer end to the right");
|
||||
for r in [json!(0), json!(360)] {
|
||||
let id = NodeId(s.execute("shape.spiral", &with(r.clone())).unwrap()["id"].as_u64().unwrap());
|
||||
assert_eq!(path_points(&s, id), plain, "{r}");
|
||||
assert_eq!(bbox_angle(&s, id).to_bits(), 0.0f64.to_bits(), "{r}");
|
||||
}
|
||||
let id = NodeId(s.execute("shape.spiral", &with(json!(90))).unwrap()["id"].as_u64().unwrap());
|
||||
assert_eq!(spiral_outer_end(&s, id), Point::new(100.0, 140.0), "a quarter turn clockwise");
|
||||
assert_eq!(bbox_angle(&s, id).to_bits(), 0.0f64.to_bits(), "not the Constrain Angle's turn");
|
||||
for bad in [json!("x"), Value::Null, json!(true)] {
|
||||
let p = with(bad);
|
||||
assert!(s.execute("shape.spiral", &p).is_err(), "{p}");
|
||||
assert_eq!(last_id(&s), id, "nothing added for {p}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -86,8 +86,57 @@ fn blob_tip_zero_and_invalid_values_are_safe() {
|
||||
p[key] = value;
|
||||
assert!(s.execute("path.blob", &p).is_err(), "{key}: {p}");
|
||||
}
|
||||
s.execute("path.blob", &json!({"points": [[100, 200], [300, 200]], "angle": 1e300, "roundness": -1e300, "merge": false})).unwrap();
|
||||
assert!(paths(&s)[1].1.control_bounds().unwrap().height().is_finite());
|
||||
let stroke = json!({"points": [[100, 200], [300, 200]], "merge": false});
|
||||
refuses_with(&mut s, "path.blob", &with(&stroke, json!({"angle": 1e300})), "`angle` must be from -180 to 180 degrees");
|
||||
refuses_with(&mut s, "path.blob", &with(&stroke, json!({"roundness": -1e300})), "`roundness` must be from 0 to 100%");
|
||||
assert_eq!(paths(&s).len(), 1);
|
||||
}
|
||||
|
||||
/// `path.blob` refuses an `angle`, `roundness` or `fidelity` outside its range and changes nothing;
|
||||
/// each end of a range paints, and a key left out or null takes its default (0°, 100% and no fitting).
|
||||
#[test]
|
||||
fn blob_brush_rejects_out_of_range_tip_and_fidelity_without_edit() {
|
||||
let mut s = session();
|
||||
let stroke = json!({"points": [[100, 100], [300, 100]], "size": 20, "merge": false});
|
||||
let angle = "`angle` must be from -180 to 180 degrees";
|
||||
let roundness = "`roundness` must be from 0 to 100%";
|
||||
let fidelity = "`fidelity` must be from 0.01 to 100 pt";
|
||||
for (extra, want) in [
|
||||
(json!({"angle": -180.5}), angle),
|
||||
(json!({"angle": 181}), angle),
|
||||
(json!({"angle": 1e300}), angle),
|
||||
(json!({"roundness": -0.5}), roundness),
|
||||
(json!({"roundness": 101}), roundness),
|
||||
(json!({"fidelity": 0.005}), fidelity),
|
||||
(json!({"fidelity": 0}), fidelity),
|
||||
(json!({"fidelity": -1}), fidelity),
|
||||
(json!({"fidelity": 101}), fidelity),
|
||||
(json!({"fidelity": 1e300}), fidelity),
|
||||
(json!({"angle": 45, "roundness": 50, "fidelity": 100.5}), fidelity),
|
||||
] {
|
||||
refuses_with(&mut s, "path.blob", &with(&stroke, extra), want);
|
||||
}
|
||||
assert!(paths(&s).is_empty());
|
||||
let painted = |s: &mut Session, extra: serde_json::Value| {
|
||||
let id = NodeId(s.execute("path.blob", &with(&stroke, extra)).unwrap()["id"].as_u64().unwrap());
|
||||
path(s, id)
|
||||
};
|
||||
for extra in [
|
||||
json!({"angle": -180}),
|
||||
json!({"angle": 180}),
|
||||
json!({"roundness": 0}),
|
||||
json!({"roundness": 100}),
|
||||
json!({"fidelity": 0.01}),
|
||||
json!({"fidelity": 100}),
|
||||
] {
|
||||
let pd = painted(&mut s, extra.clone());
|
||||
assert!(pd.control_bounds().is_some_and(|b| b.height().is_finite() && b.height() > 0.0), "{extra}: {pd:?}");
|
||||
}
|
||||
let defaults = painted(&mut s, json!({}));
|
||||
let nulls = painted(&mut s, json!({"angle": null, "roundness": null, "fidelity": null}));
|
||||
let given = painted(&mut s, json!({"angle": 0, "roundness": 100}));
|
||||
assert_eq!(nulls, defaults);
|
||||
assert_eq!(given, defaults);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -330,6 +379,41 @@ fn pencil_connect_keeps_the_rest_of_a_compound_path_and_refuses_the_extended_pat
|
||||
assert!(s.execute("path.freehand", &json!({"points": points, "extend": {"id": a.0}, "connect": {"id": a.0}})).is_err());
|
||||
}
|
||||
|
||||
/// `path.freehand` refuses a `style` other than "pencil" or "brush" and an `extend` end other than
|
||||
/// "start" or "end" and changes nothing; left out or null, the style is "pencil" and the stroke
|
||||
/// continues the path from its end.
|
||||
#[test]
|
||||
fn pencil_refuses_an_unknown_style_or_extend_end() {
|
||||
let mut s = session();
|
||||
let a = line(&mut s, 100.0, 100.0, 200.0, 100.0);
|
||||
let stroke = json!({"points": [[100, 300], [200, 320], [300, 300]]});
|
||||
for style in [json!("calligraphic"), json!("Brush"), json!(""), json!(1), json!(true)] {
|
||||
refuses_with(&mut s, "path.freehand", &with(&stroke, json!({ "style": style })), "style must be \"pencil\" or \"brush\"");
|
||||
}
|
||||
let from_end = json!({"points": [[200, 100], [250, 150], [300, 100]]});
|
||||
for end in [json!("middle"), json!("START"), json!(""), json!(0), json!(false)] {
|
||||
let p = with(&from_end, json!({"extend": {"id": a.0, "end": end}}));
|
||||
refuses_with(&mut s, "path.freehand", &p, "extend end must be \"start\" or \"end\"");
|
||||
}
|
||||
assert_eq!((paths(&s).len(), path(&s, a).anchor_count()), (1, 2), "refused: nothing changed");
|
||||
for style in [json!("pencil"), json!("brush"), json!(null)] {
|
||||
s.execute("path.freehand", &with(&stroke, json!({ "style": style }))).unwrap();
|
||||
}
|
||||
assert_eq!(paths(&s).len(), 4);
|
||||
for end in [json!(null), json!("end")] {
|
||||
let mut s = session();
|
||||
let a = line(&mut s, 100.0, 100.0, 200.0, 100.0);
|
||||
s.execute("path.freehand", &with(&from_end, json!({"extend": {"id": a.0, "end": end}}))).unwrap();
|
||||
let sp = &path(&s, a).subpaths[0];
|
||||
assert_eq!((sp.anchors[0].p, sp.anchors[sp.anchors.len() - 1].p), (Point::new(100.0, 100.0), Point::new(300.0, 100.0)), "{end}");
|
||||
}
|
||||
let mut s = session();
|
||||
let a = line(&mut s, 100.0, 100.0, 200.0, 100.0);
|
||||
s.execute("path.freehand", &json!({"points": [[100, 100], [50, 150], [0, 100]], "extend": {"id": a.0, "end": "start"}})).unwrap();
|
||||
let ends: Vec<Point> = path(&s, a).subpaths[0].anchors.iter().map(|x| x.p).collect();
|
||||
assert!(ends.contains(&Point::new(0.0, 100.0)) && ends.contains(&Point::new(200.0, 100.0)), "continued from its start: {ends:?}");
|
||||
}
|
||||
|
||||
/// With Keep selected off, a compound path whose direct-selected anchors all lie on the subpath
|
||||
/// that connect joins on is no longer selected, and Delete then has nothing to delete.
|
||||
#[test]
|
||||
|
||||
@@ -615,6 +615,141 @@ fn clicking_an_image_samples_its_pixel() {
|
||||
assert_eq!(node(&s, dst).appearance.fill_paint().color(), Some(Color::rgb8(128, 128, 64)), "5 x 5 average of both pixels");
|
||||
}
|
||||
|
||||
/// Gradient mesh points picked with Direct Selection or the Mesh tool take the color the
|
||||
/// Eyedropper then samples from an image or from other art, each sample one undo step, and only
|
||||
/// they change: the mesh's other points and its appearance stay as they were (#8090).
|
||||
#[test]
|
||||
fn picked_mesh_points_take_the_eyedropper_sample() {
|
||||
let mut s = session();
|
||||
// Two pixels, orange and teal, 100 pt each, at (300, 0).
|
||||
let rgba = [[255u8, 128, 0, 255], [0, 128, 128, 255]].concat();
|
||||
let img = craft_image_codecs::Image::from_raw(2, 1, craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, rgba).unwrap();
|
||||
let png = craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap();
|
||||
s.edit("Place", |d, _| {
|
||||
d.images.insert("px".into(), ImageBlob::png(png.to_vec()));
|
||||
let l = d.layers[0].id;
|
||||
let id = d.alloc_id();
|
||||
let xf = vectorcraft_geom::Affine::translate((300.0, 0.0)) * vectorcraft_geom::Affine::scale(100.0);
|
||||
let im = ImageObject { key: "px".into(), width: 2, height: 1, xf, link: None, placement: Default::default(), pixels: None };
|
||||
d.insert(Some(l), 0, Node::new(id, NodeKind::Image(Box::new(im)))).map_err(|e| crate::EngineError::Other(e.to_string()))
|
||||
})
|
||||
.unwrap();
|
||||
let m = rect(&mut s, 10.0);
|
||||
s.execute("object.mesh.create", &json!({"ids": [m.0], "rows": 1, "cols": 1})).unwrap();
|
||||
let red = rect(&mut s, 100.0);
|
||||
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
|
||||
let colors = |s: &Session| match node(s, m).kind {
|
||||
NodeKind::Mesh(g) => g.points.iter().map(|p| p.color).collect::<Vec<_>>(),
|
||||
k => panic!("not a mesh: {k:?}"),
|
||||
};
|
||||
let white = colors(&s)[0];
|
||||
assert!(colors(&s).iter().all(|c| *c == white && *c != Color::rgb8(255, 0, 0)));
|
||||
let appearance = node(&s, m).appearance;
|
||||
let v = ViewInfo::default();
|
||||
let pick = |s: &mut Session, tool: &str, i: usize, shift: bool| {
|
||||
s.select_tool(tool, v).unwrap();
|
||||
let q = match node(s, m).kind {
|
||||
NodeKind::Mesh(g) => g.points[i].p,
|
||||
k => panic!("not a mesh: {k:?}"),
|
||||
};
|
||||
let mods = Mods { shift, ..Default::default() };
|
||||
for kind in [PointerKind::Down, PointerKind::Up] {
|
||||
s.pointer(&PointerEvent::new(kind, q.x, q.y).with_mods(mods), v).unwrap();
|
||||
}
|
||||
};
|
||||
let (teal, orange) = (Color::rgb8(0, 128, 128), Color::rgb8(255, 128, 0));
|
||||
s.execute("select.set", &json!({"ids": [m.0]})).unwrap();
|
||||
pick(&mut s, "directSelection", 0, false);
|
||||
let undo = undo_len(&s);
|
||||
click(&mut s, 450.0, 50.0, Mods::default());
|
||||
assert_eq!(colors(&s), [teal, white, white, white], "the picked point takes the image's color");
|
||||
assert_eq!(node(&s, m).appearance, appearance, "the mesh's appearance stays");
|
||||
assert_eq!(undo_len(&s), undo + 1, "one undo step");
|
||||
// The Eyedropper keeps the picks: a Shift-click samples into the point again.
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 350.0, 50.0).with_mods(Mods { shift: true, ..Default::default() }), v).unwrap();
|
||||
assert_eq!(colors(&s), [orange, white, white, white]);
|
||||
assert_eq!(undo_len(&s), undo + 2);
|
||||
// A sample of the color the point already has changes nothing and adds no step.
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 350.0, 50.0), v).unwrap();
|
||||
assert_eq!(undo_len(&s), undo + 2, "no step when nothing changes");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(colors(&s), [teal, white, white, white]);
|
||||
// Two points picked with the Mesh tool both take a plain click's sample of other art, and the
|
||||
// art keeps its fill.
|
||||
pick(&mut s, "mesh", 1, false);
|
||||
pick(&mut s, "mesh", 3, true);
|
||||
let undo = undo_len(&s);
|
||||
click(&mut s, 125.0, 35.0, Mods::default());
|
||||
let r = Color::rgb8(255, 0, 0);
|
||||
assert_eq!(colors(&s), [teal, r, white, r]);
|
||||
assert_eq!(undo_len(&s), undo + 1, "one undo step for every picked point");
|
||||
assert_eq!(node(&s, m).appearance, appearance);
|
||||
assert_eq!(node(&s, red).appearance.fill_paint().color(), Some(r));
|
||||
// Back in the Mesh tool the two points are still picked: a fill color recolors just them.
|
||||
s.select_tool("mesh", v).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap();
|
||||
let b = Color::rgb8(0, 0, 255);
|
||||
assert_eq!(colors(&s), [teal, b, white, b], "the picks go back to the Mesh tool");
|
||||
// Without picked points a click on an image samples into the whole selected mesh as before.
|
||||
s.select_tool("selection", v).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [m.0]})).unwrap();
|
||||
click(&mut s, 450.0, 50.0, Mods::default());
|
||||
assert_eq!(colors(&s), [teal, b, white, b], "the points keep their colors");
|
||||
assert_ne!(node(&s, m).appearance, appearance);
|
||||
}
|
||||
|
||||
/// A Cmd-click with the Direct Selection tool the Eyedropper lends picks gradient mesh points for
|
||||
/// the Eyedropper: the lent tool starts from the Eyedropper's picks, so a Shift-click adds to
|
||||
/// them, and the Eyedropper samples into what the lent tool left picked (#8090).
|
||||
#[test]
|
||||
fn mesh_points_picked_through_the_lent_tool_take_the_eyedropper_sample() {
|
||||
let mut s = session();
|
||||
// Two pixels, orange and teal, 100 pt each, at (300, 0).
|
||||
let rgba = [[255u8, 128, 0, 255], [0, 128, 128, 255]].concat();
|
||||
let img = craft_image_codecs::Image::from_raw(2, 1, craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, rgba).unwrap();
|
||||
let png = craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap();
|
||||
s.edit("Place", |d, _| {
|
||||
d.images.insert("px".into(), ImageBlob::png(png.to_vec()));
|
||||
let l = d.layers[0].id;
|
||||
let id = d.alloc_id();
|
||||
let xf = vectorcraft_geom::Affine::translate((300.0, 0.0)) * vectorcraft_geom::Affine::scale(100.0);
|
||||
let im = ImageObject { key: "px".into(), width: 2, height: 1, xf, link: None, placement: Default::default(), pixels: None };
|
||||
d.insert(Some(l), 0, Node::new(id, NodeKind::Image(Box::new(im)))).map_err(|e| crate::EngineError::Other(e.to_string()))
|
||||
})
|
||||
.unwrap();
|
||||
let m = rect(&mut s, 10.0);
|
||||
s.execute("object.mesh.create", &json!({"ids": [m.0], "rows": 1, "cols": 1})).unwrap();
|
||||
let colors = |s: &Session| match node(s, m).kind {
|
||||
NodeKind::Mesh(g) => g.points.iter().map(|p| p.color).collect::<Vec<_>>(),
|
||||
k => panic!("not a mesh: {k:?}"),
|
||||
};
|
||||
let white = colors(&s)[0];
|
||||
let v = ViewInfo::default();
|
||||
let press = |s: &mut Session, i: usize, mods: Mods| {
|
||||
let q = match node(s, m).kind {
|
||||
NodeKind::Mesh(g) => g.points[i].p,
|
||||
k => panic!("not a mesh: {k:?}"),
|
||||
};
|
||||
for kind in [PointerKind::Down, PointerKind::Up] {
|
||||
s.pointer(&PointerEvent::new(kind, q.x, q.y).with_mods(mods), v).unwrap();
|
||||
}
|
||||
};
|
||||
let (teal, orange) = (Color::rgb8(0, 128, 128), Color::rgb8(255, 128, 0));
|
||||
s.execute("select.set", &json!({"ids": [m.0]})).unwrap();
|
||||
s.select_tool("directSelection", v).unwrap();
|
||||
press(&mut s, 0, Mods::default());
|
||||
s.select_tool("eyedropper", v).unwrap();
|
||||
// Cmd-click point 3: Direct Selection, lent, picks it in place of point 0.
|
||||
press(&mut s, 3, Mods { cmd: true, ..Default::default() });
|
||||
assert_eq!(s.tool_id(), "eyedropper");
|
||||
click(&mut s, 450.0, 50.0, Mods::default());
|
||||
assert_eq!(colors(&s), [white, white, white, teal], "the point the lent tool picked takes the sample");
|
||||
// Cmd+Shift-click point 0 adds it to the Eyedropper's pick.
|
||||
press(&mut s, 0, Mods { cmd: true, shift: true, ..Default::default() });
|
||||
click(&mut s, 350.0, 50.0, Mods::default());
|
||||
assert_eq!(colors(&s), [orange, white, white, orange], "both picked points take the sample");
|
||||
}
|
||||
|
||||
/// A CMYK document with one image of `px` (one row, 100 pt a pixel) at (300, 0).
|
||||
fn cmyk_doc_with_image(px: &[[u8; 4]]) -> Session {
|
||||
let mut s = Session::new();
|
||||
|
||||
@@ -641,7 +641,7 @@ fn export_selection_reports_the_encoders_warnings() {
|
||||
assert_eq!(plain["format"], "svg");
|
||||
assert!(warnings(&plain).is_empty(), "{plain}");
|
||||
for (format, options, says) in [
|
||||
("webp", json!({"lossless": false}), "lossless"),
|
||||
("webp", json!({"interlaced": true}), "interlaced"),
|
||||
("svg", json!({"profile": "tiny12"}), "blend"),
|
||||
("pdf", json!({"createLayers": true, "compatibility": "1.4"}), "layers"),
|
||||
] {
|
||||
|
||||
@@ -4109,6 +4109,17 @@ fn area_to_point_turns_wraps_into_breaks() {
|
||||
assert_eq!(txt.replace('\n', " "), "one two three four five six");
|
||||
}
|
||||
|
||||
/// Convert To Point Type keeps the lines that a paragraph return or a forced line break (U+2028)
|
||||
/// starts as they are: neither gets a paragraph return added after it.
|
||||
#[test]
|
||||
fn area_to_point_keeps_forced_line_breaks() {
|
||||
let mut s = session();
|
||||
let a = id_of(&s.execute("text.create", &json!({"x": 0, "y": 0, "text": "ab\u{2028}c\nd", "area": {"width": 300, "height": 200}})).unwrap());
|
||||
sel(&mut s, &[a]);
|
||||
s.execute("type.convertToPointType", &json!({})).unwrap();
|
||||
assert_eq!(plain(&s, a), "ab\u{2028}c\nd");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn placeholder_and_insert_characters() {
|
||||
let mut s = session();
|
||||
@@ -4124,6 +4135,76 @@ fn placeholder_and_insert_characters() {
|
||||
assert!(s.execute("type.insert", &json!({"char": "nope"})).is_err());
|
||||
}
|
||||
|
||||
/// Type › Insert Break Character › Forced Line Break (`type.insert {char: "forcedLineBreak"}`)
|
||||
/// starts a new line in the same paragraph (U+2028, as Shift+Enter types it), so the paragraph's
|
||||
/// space before does not come between the two lines; `paragraphReturn` starts a new paragraph.
|
||||
/// Each insert is one undo step.
|
||||
#[test]
|
||||
fn insert_forced_line_break_differs_from_paragraph_return() {
|
||||
fn second_line_gap(s: &Session, id: NodeId) -> f64 {
|
||||
let NodeKind::Text(t) = &node(s, id).kind else { panic!("not text") };
|
||||
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t);
|
||||
assert_eq!(lay.lines.len(), 2, "{:?}", t.plain_text());
|
||||
lay.lines[1].baseline - lay.lines[0].baseline
|
||||
}
|
||||
let mut s = session();
|
||||
let mut gaps = Vec::new();
|
||||
for (c, want) in [("forcedLineBreak", "ab\u{2028}c"), ("paragraphReturn", "ab\nc")] {
|
||||
let t = text(&mut s, "ab");
|
||||
sel(&mut s, &[t]);
|
||||
s.execute("text.setFormat", &json!({"ids": [t.0], "spaceBefore": 30})).unwrap();
|
||||
let steps = undo_len(&s);
|
||||
s.execute("type.insert", &json!({"char": c})).unwrap();
|
||||
assert_eq!(undo_len(&s), steps + 1, "{c}");
|
||||
s.execute("type.insert", &json!({"text": "c"})).unwrap();
|
||||
assert_eq!(plain(&s, t), want, "{c}");
|
||||
gaps.push(second_line_gap(&s, t));
|
||||
}
|
||||
assert!(gaps[1] - gaps[0] > 29.0, "space before only at the paragraph return: {gaps:?}");
|
||||
// The same character by `unicode` and by `text`.
|
||||
let t = text(&mut s, "");
|
||||
sel(&mut s, &[t]);
|
||||
s.execute("type.insert", &json!({"unicode": "2028"})).unwrap();
|
||||
s.execute("type.insert", &json!({"text": "\u{2028}"})).unwrap();
|
||||
assert_eq!(plain(&s, t), "\u{2028}\u{2028}");
|
||||
}
|
||||
|
||||
/// While the Type tool edits text, the Insert Special, Whitespace and Break menu items
|
||||
/// (`type.insert` without `ids`) insert at its caret or replace its selection, as one undo step,
|
||||
/// and the caret goes after the insertion; `ids` still appends to those objects.
|
||||
#[test]
|
||||
fn insert_character_goes_to_the_type_tool_caret() {
|
||||
use vectorcraft_tools::{Mods, PointerEvent, PointerKind, ToolKey};
|
||||
let mut s = session();
|
||||
let v = ViewInfo::default();
|
||||
s.select_tool("type", v).unwrap();
|
||||
for k in [PointerKind::Down, PointerKind::Up] {
|
||||
s.pointer(&PointerEvent::new(k, 50.0, 300.0), v).unwrap();
|
||||
}
|
||||
let t = s.doc().unwrap().selection.objects[0];
|
||||
s.tool_text("abcd", v).unwrap();
|
||||
for _ in 0..2 {
|
||||
s.tool_key(ToolKey::Left, Mods::default(), v).unwrap();
|
||||
}
|
||||
let steps = undo_len(&s);
|
||||
s.execute("type.insert", &json!({"text": ""})).unwrap();
|
||||
assert_eq!(undo_len(&s), steps, "an empty insert changes nothing");
|
||||
s.execute("type.insert", &json!({"char": "forcedLineBreak"})).unwrap();
|
||||
assert_eq!(plain(&s, t), "ab\u{2028}cd");
|
||||
assert_eq!(s.tool_options()["caret"], json!(5));
|
||||
s.tool_text("X", v).unwrap();
|
||||
assert_eq!(plain(&s, t), "ab\u{2028}Xcd");
|
||||
s.tool_key(ToolKey::Left, Mods { shift: true, ..Mods::default() }, v).unwrap();
|
||||
s.execute("type.insert", &json!({"char": "paragraphReturn"})).unwrap();
|
||||
assert_eq!(plain(&s, t), "ab\u{2028}\ncd");
|
||||
s.execute("type.insert", &json!({"ids": [t.0], "text": "!"})).unwrap();
|
||||
assert_eq!(plain(&s, t), "ab\u{2028}\ncd!");
|
||||
s.tool_key(ToolKey::Escape, Mods::default(), v).unwrap();
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(plain(&s, t), "ab\u{2028}Xcd", "the replacement is one undo step");
|
||||
}
|
||||
|
||||
/// `type.insert` by code (#5108): `code` as a Windows Alt+0 code types (Windows-1252 for
|
||||
/// 128–159, the code point otherwise), `unicode` as a hex code point.
|
||||
#[test]
|
||||
|
||||
@@ -391,3 +391,21 @@ fn for_a_printer_a_landscape_page_is_written_upright() {
|
||||
assert_eq!(size(&spooled), [(612.0, 792.0)]);
|
||||
assert_eq!(v["pages"], 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_spot_ink_converted_to_process_is_saved_and_listed_without_a_plate() {
|
||||
let (mut s, _) = session();
|
||||
s.execute("swatch.new", &json!({"name": "Gold", "color": {"model": "cmyk", "c": 0, "m": 0.2, "y": 0.8, "k": 0.1}, "spot": true})).unwrap();
|
||||
let ink = json!({"name": "Gold", "convertToProcess": true});
|
||||
let v = s.execute("print.setup", &json!({"settings": {"output": {"mode": "separations", "inks": [ink]}}})).unwrap();
|
||||
assert_eq!(v["settings"]["output"]["inks"], json!([{"name": "Gold", "print": true, "convertToProcess": true}]));
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let back = vectorcraft_format::load(&vectorcraft_format::save(doc, false)).unwrap();
|
||||
assert_eq!(back.print_setup.as_ref().map(|p| p["output"]["inks"][0]["convertToProcess"].clone()), Some(json!(true)), "kept in the file");
|
||||
let pv = s.execute("print.preview", &json!({})).unwrap();
|
||||
let names = |list: &Value| list.as_array().unwrap().iter().map(|i| i["name"].as_str().unwrap().to_string()).collect::<Vec<_>>();
|
||||
assert_eq!(names(&pv["inks"]), ["Cyan", "Magenta", "Yellow", "Black"], "no Gold plate");
|
||||
assert_eq!(names(&pv["documentInks"]), ["Cyan", "Magenta", "Yellow", "Black", "Gold"]);
|
||||
assert_eq!(pv["documentInks"][4]["convertToProcess"], json!(true));
|
||||
assert_eq!(pv["documentInks"][0].get("convertToProcess"), None, "written only when on");
|
||||
}
|
||||
|
||||
@@ -393,10 +393,10 @@ fn a_group_selection_marquee_leaves_out_a_drop_shadow() {
|
||||
run(&mut s, "select.none", json!({}));
|
||||
let sel = marquee(&mut s, "groupSelection", (85.0, 40.0), (95.0, 60.0));
|
||||
assert!(sel.objects.is_empty() && sel.anchors.is_empty(), "{sel:?}");
|
||||
// Over the shadow and B's upper left corner: that anchor of B.
|
||||
// Over the shadow and B's upper left corner: B whole, and not A (#8047).
|
||||
let sel = marquee(&mut s, "groupSelection", (90.0, 5.0), (105.0, 30.0));
|
||||
assert_eq!(sel.objects, [b]);
|
||||
assert_eq!(picked_points(&s, b), [Point::new(100.0, 20.0)]);
|
||||
assert!(sel.partial(b).is_none(), "{sel:?}");
|
||||
// With E, a marquee around B that crosses A's shadow selects B whole, and not A.
|
||||
run(&mut s, "select.none", json!({}));
|
||||
let v = ViewInfo::default();
|
||||
|
||||
@@ -2289,6 +2289,41 @@ fn threaded_list_edited_in_its_second_frame() -> (Session, NodeId, NodeId, Strin
|
||||
(s, a, b, story)
|
||||
}
|
||||
|
||||
/// Type › Insert Break Character › Forced Line Break (`type.insert`) after Select All in threaded
|
||||
/// text replaces the whole story, every frame's text, as one undo step.
|
||||
#[test]
|
||||
fn insert_character_replaces_the_whole_story_that_select_all_selected() {
|
||||
let (mut s, a, b, story) = threaded_story_edited_in_its_second_frame();
|
||||
s.execute("select.all", &json!({})).unwrap();
|
||||
let steps = undo_labels(&s).len();
|
||||
s.execute("type.insert", &json!({"char": "forcedLineBreak"})).unwrap();
|
||||
assert_eq!(undo_labels(&s).len(), steps + 1, "one undo step");
|
||||
assert_eq!(format!("{}{}", obj(&s, a).plain_text(), obj(&s, b).plain_text()), "\u{2028}");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(format!("{}{}", obj(&s, a).plain_text(), obj(&s, b).plain_text()), story);
|
||||
}
|
||||
|
||||
/// When `type.insert` at the caret in the first frame of threaded text pushes the caret's place on
|
||||
/// into the next frame, the Type tool's caret goes there with it, and typing goes after the
|
||||
/// insertion.
|
||||
#[test]
|
||||
fn insert_character_moves_the_caret_with_the_text_it_flows_on() {
|
||||
let (mut s, a, b, story) = threaded_story_edited_in_its_second_frame();
|
||||
let first = obj(&s, a).plain_text();
|
||||
// Before the last word of the first frame: two line breaks there push the line after the
|
||||
// first one on into the second frame.
|
||||
let at = first.trim_end().rfind(' ').map_or(0, |k| k + 1);
|
||||
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
|
||||
s.set_tool_option("textSelection", &json!({"editing": a.0, "anchor": at, "caret": at}));
|
||||
for _ in 0..2 {
|
||||
s.execute("type.insert", &json!({"char": "forcedLineBreak"})).unwrap();
|
||||
}
|
||||
assert!(obj(&s, a).plain_text().len() < at + 6, "the second break flows on into the second frame");
|
||||
s.tool_text("X", ViewInfo::default()).unwrap();
|
||||
let want = format!("{}\u{2028}\u{2028}X{}", &story[..at], &story[at..]);
|
||||
assert_eq!(format!("{}{}", obj(&s, a).plain_text(), obj(&s, b).plain_text()), want);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remove_breaks_takes_the_whole_story_that_select_all_selected() {
|
||||
let (mut s, a, b, story) = threaded_list_edited_in_its_second_frame();
|
||||
|
||||
@@ -369,3 +369,129 @@ fn scale_text_attributes_keeps_tracked_type_where_it_was() {
|
||||
assert!((*a - *b).hypot() < 1e-6, "{before:?} {after:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// What Scale Text Attributes must leave as it was: the document-space bounds of an area's frame
|
||||
/// or a path type's path, each line's text, whether the text overflows, and where each glyph
|
||||
/// starts on the page.
|
||||
struct Placed {
|
||||
outline: Option<vectorcraft_geom::Rect>,
|
||||
lines: Vec<(usize, usize)>,
|
||||
overflow: bool,
|
||||
pens: Vec<Point>,
|
||||
}
|
||||
|
||||
fn placed(s: &Session, id: NodeId) -> Placed {
|
||||
let t = text(s, id);
|
||||
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t);
|
||||
let outline = match &t.kind {
|
||||
vectorcraft_doc::TextKind::Area { frame } => Some(frame),
|
||||
vectorcraft_doc::TextKind::OnPath { path, .. } => Some(path),
|
||||
vectorcraft_doc::TextKind::Point => None,
|
||||
};
|
||||
Placed {
|
||||
outline: outline.and_then(|p| p.transformed(t.xf).bounds()),
|
||||
lines: lay.lines.iter().map(|l| (l.start, l.end)).collect(),
|
||||
overflow: lay.overflow,
|
||||
pens: lay.glyphs.iter().map(|g| t.xf * (g.xf * Point::ZERO)).collect(),
|
||||
}
|
||||
}
|
||||
|
||||
fn same_place(before: &Placed, after: &Placed) {
|
||||
let (Some(b), Some(a)) = (before.outline, after.outline) else { panic!("no frame or path: {:?} {:?}", before.outline, after.outline) };
|
||||
for (x, y) in [(b.x0, a.x0), (b.y0, a.y0), (b.x1, a.x1), (b.y1, a.y1)] {
|
||||
assert!((x - y).abs() < 1e-6, "frame {b:?} became {a:?}");
|
||||
}
|
||||
assert_eq!(after.lines, before.lines, "line breaks");
|
||||
assert_eq!(after.overflow, before.overflow, "overflow");
|
||||
assert_eq!(before.pens.len(), after.pens.len());
|
||||
for (b, a) in before.pens.iter().zip(&after.pens) {
|
||||
assert!((*a - *b).hypot() < 1e-6, "{:?} {:?}", before.pens, after.pens);
|
||||
}
|
||||
}
|
||||
|
||||
/// #8297: Scale Text Attributes on scaled area type keeps the frame the scale gave it, so the
|
||||
/// lines break where they did and no text becomes overset. It used to leave the frame at its
|
||||
/// unscaled size, which then held two lines of the larger type and hid the rest.
|
||||
#[test]
|
||||
fn scale_text_attributes_keeps_an_area_frame_and_its_lines() {
|
||||
for (sx, sy, size) in [(200, 200, 24.0), (200, 100, 12.0), (50, 50, 6.0)] {
|
||||
let mut s = session();
|
||||
let id = NodeId(
|
||||
s.execute(
|
||||
"text.create",
|
||||
&json!({"x": 40, "y": 60, "size": 12, "area": {"width": 120, "height": 80}, "text": "Bright river stones mark a gentle path past old trees."}),
|
||||
)
|
||||
.unwrap()["id"]
|
||||
.as_u64()
|
||||
.unwrap(),
|
||||
);
|
||||
s.execute("object.scale", &json!({"sx": sx, "sy": sy, "origin": [0, 0]})).unwrap();
|
||||
let before = placed(&s, id);
|
||||
assert!(before.lines.len() >= 3 && !before.overflow, "{sx}x{sy}: {:?}", before.lines);
|
||||
s.execute("type.scaleTextAttributes", &json!({})).unwrap();
|
||||
near(text(&s, id).runs[0].style.size, size);
|
||||
same_place(&before, &placed(&s, id));
|
||||
if (sx, sy) == (200, 200) {
|
||||
let f = before.outline.unwrap();
|
||||
assert_eq!((f.x0.round(), f.y0.round(), f.x1.round(), f.y1.round()), (80.0, 120.0, 320.0, 280.0));
|
||||
}
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
near(text(&s, id).runs[0].style.size, 12.0);
|
||||
same_place(&before, &placed(&s, id));
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
same_place(&before, &placed(&s, id));
|
||||
}
|
||||
}
|
||||
|
||||
/// Type on a path keeps its path: it used to shrink with the scale removed, so the type ran past
|
||||
/// its end.
|
||||
#[test]
|
||||
fn scale_text_attributes_keeps_a_path_types_path() {
|
||||
let mut s = session();
|
||||
let pid = s.execute("path.create", &json!({ "d": "M100 300 L300 300" })).unwrap()["id"].as_u64().unwrap();
|
||||
let id = NodeId(
|
||||
s.execute("text.createInPath", &json!({"path": pid, "mode": "onPath", "text": "Along the way", "size": 12, "at": [100, 300]})).unwrap()["id"]
|
||||
.as_u64()
|
||||
.unwrap(),
|
||||
);
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("object.scale", &json!({"sx": 200, "origin": [0, 0]})).unwrap();
|
||||
let before = placed(&s, id);
|
||||
assert!(!before.overflow);
|
||||
s.execute("type.scaleTextAttributes", &json!({})).unwrap();
|
||||
near(text(&s, id).runs[0].style.size, 24.0);
|
||||
same_place(&before, &placed(&s, id));
|
||||
}
|
||||
|
||||
/// A non-uniform scale on type on a path: only the uniform part is baked and the stretch stays in
|
||||
/// the transform, so the brackets, which sit at fractions of the path's length, stay where they
|
||||
/// were. Baking the stretch into the path would move them: on this path, scaled 3 × 2, the length
|
||||
/// grows from 200 to 500 and not in proportion, so the same fraction lands elsewhere.
|
||||
#[test]
|
||||
fn scale_text_attributes_keeps_path_type_on_a_stretched_path_where_it_was() {
|
||||
let mut s = session();
|
||||
let pid = s.execute("path.create", &json!({ "d": "M0 0 L100 0 L100 100" })).unwrap()["id"].as_u64().unwrap();
|
||||
let id = NodeId(
|
||||
s.execute("text.createInPath", &json!({"path": pid, "mode": "onPath", "text": "Corner", "size": 12, "at": [60, 0]})).unwrap()["id"]
|
||||
.as_u64()
|
||||
.unwrap(),
|
||||
);
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("object.scale", &json!({"sx": 300, "sy": 200, "origin": [0, 0]})).unwrap();
|
||||
let before = placed(&s, id);
|
||||
let brackets = |s: &Session| match text(s, id).kind {
|
||||
vectorcraft_doc::TextKind::OnPath { start, end, .. } => (start, end),
|
||||
k => panic!("not path type: {k:?}"),
|
||||
};
|
||||
let before_brackets = brackets(&s);
|
||||
s.execute("type.scaleTextAttributes", &json!({})).unwrap();
|
||||
near(text(&s, id).runs[0].style.size, 24.0);
|
||||
near(text(&s, id).runs[0].style.h_scale, 100.0);
|
||||
let left = text(&s, id).style_scale().unwrap();
|
||||
near(left.points, 1.0);
|
||||
near(left.horizontal, 1.5);
|
||||
assert_eq!(brackets(&s), before_brackets);
|
||||
same_place(&before, &placed(&s, id));
|
||||
// Only the stretch is left: there is nothing more to bake.
|
||||
assert!(s.execute("type.scaleTextAttributes", &json!({})).is_err());
|
||||
}
|
||||
|
||||
@@ -523,3 +523,215 @@ fn setting_keys_are_their_json_values() {
|
||||
.unwrap();
|
||||
assert_eq!(serde_json::from_value::<cmd::webexport::WebSettings>(custom.to_json()).unwrap(), custom);
|
||||
}
|
||||
|
||||
fn optimize_to(s: &mut Session, p: Value) -> Value {
|
||||
run(s, "webExport.optimizeToFileSize", p)
|
||||
}
|
||||
|
||||
/// The size of the file the settings `p` write (the whole image, or slice `slice`).
|
||||
fn written(s: &mut Session, p: &Value) -> usize {
|
||||
run(s, "document.exportForWeb.preview", p.clone())["bytes"].as_u64().unwrap() as usize
|
||||
}
|
||||
|
||||
/// 20×20: 400 one-point squares of different colors (more than a palette holds).
|
||||
fn photo_like() -> Session {
|
||||
let mut s = session(20.0, 20.0);
|
||||
for i in 0..400 {
|
||||
let (x, y) = ((i % 20) as f64, (i / 20) as f64);
|
||||
rect(&mut s, [x, y, 1.0, 1.0], &format!("#{:02x}{:02x}{:02x}", (i % 20) * 12, (i / 20) * 12, (i * 7) % 256));
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn optimize_to_file_size_takes_the_highest_jpeg_quality_that_fits() {
|
||||
let mut s = many_colours();
|
||||
let start = json!({"format": "jpg", "quality": 90});
|
||||
let full = written(&mut s, &start);
|
||||
let k = (full * 3 / 4) as f64 / 1024.0;
|
||||
let r = optimize_to(&mut s, merge(&start, json!({"desiredK": k})));
|
||||
let target = r["targetBytes"].as_u64().unwrap() as usize;
|
||||
assert_eq!(target, (k * 1024.0).floor() as usize);
|
||||
assert_eq!((r["achieved"].as_bool(), r["format"].as_str(), r["images"].as_u64()), (Some(true), Some("jpg"), Some(1)), "{r}");
|
||||
let q = r["settings"]["quality"].as_u64().unwrap();
|
||||
assert!(q < 90, "{r}");
|
||||
let bytes = r["bytes"].as_u64().unwrap() as usize;
|
||||
assert!(bytes <= target, "{r}");
|
||||
// The size is the size of the file Save writes with the settings.
|
||||
assert_eq!(written(&mut s, &r["settings"]), bytes);
|
||||
assert_eq!(one(&mut s, r["settings"].clone()).len(), bytes);
|
||||
// One quality step up is over the size.
|
||||
assert!(written(&mut s, &merge(&r["settings"], json!({"quality": q + 1}))) > target);
|
||||
assert!(r["trials"].as_u64().unwrap() as usize <= cmd::webexport::OPTIMIZE_TRIALS);
|
||||
// The other settings stay.
|
||||
assert_eq!(r["settings"]["matte"], json!("white"));
|
||||
assert_eq!(r["settings"]["metadata"], json!("copyright"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn optimize_to_file_size_lowers_palette_colors() {
|
||||
let mut s = many_colours();
|
||||
for format in ["gif", "png8"] {
|
||||
let start = json!({"format": format, "dither": "none", "colors": 128});
|
||||
let full = written(&mut s, &start);
|
||||
let r = optimize_to(&mut s, merge(&start, json!({"desiredK": (full * 3 / 4) as f64 / 1024.0})));
|
||||
let target = r["targetBytes"].as_u64().unwrap() as usize;
|
||||
assert_eq!((r["achieved"].as_bool(), r["format"].as_str()), (Some(true), Some(format)), "{r}");
|
||||
let colors = r["settings"]["colors"].as_u64().unwrap();
|
||||
assert!(colors < 64, "{format}: {r}");
|
||||
assert_eq!((r["settings"]["lossy"].as_u64(), r["settings"]["dither"].as_str()), (Some(0), Some("none")), "{format}: {r}");
|
||||
let bytes = r["bytes"].as_u64().unwrap() as usize;
|
||||
assert!(bytes <= target && written(&mut s, &r["settings"]) == bytes, "{format}: {r}");
|
||||
assert!(written(&mut s, &merge(&r["settings"], json!({"colors": colors + 1}))) > target, "{format}: {r}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn optimize_to_file_size_auto_selects_gif_or_jpeg_by_content() {
|
||||
// Flat, opaque art: GIF, from a JPEG start.
|
||||
let mut flat = two_colours();
|
||||
let r = optimize_to(&mut flat, json!({"format": "jpg", "desiredK": 100, "startWith": "auto"}));
|
||||
assert_eq!((r["format"].as_str(), r["achieved"].as_bool()), (Some("gif"), Some(true)), "{r}");
|
||||
// More colors than a palette holds: JPEG, from a GIF start.
|
||||
let mut photo = photo_like();
|
||||
let r = optimize_to(&mut photo, json!({"format": "gif", "desiredK": 100, "startWith": "auto"}));
|
||||
assert_eq!((r["format"].as_str(), r["achieved"].as_bool()), (Some("jpg"), Some(true)), "{r}");
|
||||
// Transparent pixels: GIF, which keeps them.
|
||||
let mut clear = session(40.0, 30.0);
|
||||
rect(&mut clear, [0.0, 0.0, 10.0, 10.0], "#000000");
|
||||
for (k, transparency, format) in [(100.0, true, "gif"), (100.0, false, "gif"), (0.01, true, "gif")] {
|
||||
let r = optimize_to(&mut clear, json!({"format": "jpg", "desiredK": k, "startWith": "auto", "transparency": transparency}));
|
||||
assert_eq!(r["format"].as_str(), Some(format), "{k} {transparency}: {r}");
|
||||
}
|
||||
// The current format stays without auto.
|
||||
let r = optimize_to(&mut photo, json!({"format": "png8", "desiredK": 100}));
|
||||
assert_eq!(r["format"].as_str(), Some("png8"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn optimize_to_file_size_auto_counts_the_colors_blended_over_the_matte() {
|
||||
// Three colors at 100 opacities: without transparency, 300 colors once blended over the matte.
|
||||
let mut s = session(20.0, 15.0);
|
||||
for i in 0..300 {
|
||||
let (x, y) = ((i % 20) as f64, (i / 20) as f64);
|
||||
let id = rect(&mut s, [x, y, 1.0, 1.0], ["#000000", "#ff0000", "#0000ff"][i % 3]);
|
||||
run(&mut s, "transparency.set", json!({"ids": [id], "opacity": i / 3 + 1}));
|
||||
}
|
||||
let r = optimize_to(&mut s, json!({"format": "gif", "desiredK": 100, "startWith": "auto", "transparency": false, "antiAlias": "none"}));
|
||||
assert_eq!((r["format"].as_str(), r["achieved"].as_bool()), (Some("jpg"), Some(true)), "{r}");
|
||||
// With transparency the pixels stay transparent: GIF.
|
||||
let r = optimize_to(&mut s, json!({"format": "jpg", "desiredK": 100, "startWith": "auto", "antiAlias": "none"}));
|
||||
assert_eq!(r["format"].as_str(), Some("gif"), "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn optimize_to_file_size_says_when_no_setting_fits() {
|
||||
let mut s = many_colours();
|
||||
for format in ["jpg", "gif", "png8"] {
|
||||
let start = json!({"format": format});
|
||||
let r = optimize_to(&mut s, merge(&start, json!({"desiredK": 0.01})));
|
||||
assert_eq!((r["targetBytes"].as_u64(), r["achieved"].as_bool(), r["format"].as_str()), (Some(10), Some(false), Some(format)), "{r}");
|
||||
let bytes = r["bytes"].as_u64().unwrap() as usize;
|
||||
assert!(bytes > 10 && bytes <= written(&mut s, &start), "{format}: the smallest setting tried: {r}");
|
||||
assert_eq!(written(&mut s, &r["settings"]), bytes);
|
||||
assert!(r["trials"].as_u64().unwrap() as usize <= cmd::webexport::OPTIMIZE_TRIALS);
|
||||
}
|
||||
// GIF tries lossy when 2 colors are over.
|
||||
let r = optimize_to(&mut s, json!({"format": "gif", "desiredK": 0.01}));
|
||||
assert_eq!(r["settings"]["lossy"], json!(100), "{r}");
|
||||
// PNG-24 has nothing to lower.
|
||||
let r = optimize_to(&mut s, json!({"format": "png24", "desiredK": 0.01}));
|
||||
assert_eq!((r["achieved"].as_bool(), r["trials"].as_u64()), (Some(false), Some(1)), "{r}");
|
||||
assert_eq!(r["settings"], s.web_settings(&json!({"format": "png24"})).unwrap().to_json());
|
||||
// Settings that fit stay as they are.
|
||||
let p = json!({"format": "jpg", "quality": 80, "desiredK": 1000});
|
||||
let r = optimize_to(&mut s, p.clone());
|
||||
assert_eq!((r["achieved"].as_bool(), r["trials"].as_u64()), (Some(true), Some(1)), "{r}");
|
||||
assert_eq!(r["settings"], s.web_settings(&p).unwrap().to_json());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn optimize_to_file_size_refuses_bad_params_and_changes_nothing() {
|
||||
let mut s = many_colours();
|
||||
run(&mut s, "webExport.settings", json!({"format": "jpg", "quality": 77}));
|
||||
let remembered = s.last_web_settings();
|
||||
for p in [
|
||||
json!({}),
|
||||
json!({"desiredK": 0}),
|
||||
json!({"desiredK": -5}),
|
||||
json!({"desiredK": "10"}),
|
||||
json!({"desiredK": null}),
|
||||
json!({"desiredK": 2_000_000}),
|
||||
json!({"desiredK": 10, "startWith": "gif"}),
|
||||
json!({"desiredK": 10, "startWith": 1}),
|
||||
json!({"desiredK": 10, "use": "all"}),
|
||||
json!({"desiredK": 10, "slice": 0}),
|
||||
json!({"desiredK": 10, "slice": "1"}),
|
||||
json!({"desiredK": 10, "slice": 1, "use": "eachSlice"}),
|
||||
json!({"desiredK": 10, "slice": 99}),
|
||||
json!({"desiredK": 10, "percent": 0}),
|
||||
] {
|
||||
assert!(s.execute("webExport.optimizeToFileSize", &p).is_err(), "{p}");
|
||||
}
|
||||
optimize_to(&mut s, json!({"desiredK": 0.5, "format": "jpg"}));
|
||||
assert_eq!(s.last_web_settings(), remembered, "the search changes no remembered setting");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn optimize_to_file_size_measures_the_slices_as_use_says() {
|
||||
let mut s = session(300.0, 200.0);
|
||||
rect(&mut s, [0.0, 0.0, 300.0, 200.0], "#336699");
|
||||
for i in 0..40 {
|
||||
rect(&mut s, [f64::from(i) * 7.0, f64::from(i) * 4.0, 30.0, 20.0], &format!("#{:02x}{:02x}40", i * 6, 255 - i * 6));
|
||||
}
|
||||
let a = rect(&mut s, [20.0, 20.0, 100.0, 60.0], "#ff8800");
|
||||
run(&mut s, "object.slice.make", json!({"ids": [a]}));
|
||||
let layout = run(&mut s, "slice.list", json!({}))["slices"].as_array().unwrap().clone();
|
||||
let start = json!({"format": "jpg", "quality": 95});
|
||||
let sizes = |s: &mut Session, p: &Value| files(&run(s, "document.exportForWeb", p.clone())).iter().map(|(_, b)| b.len()).collect::<Vec<_>>();
|
||||
let all = sizes(&mut s, &start);
|
||||
assert_eq!(all.len(), layout.len());
|
||||
let total: usize = all.iter().sum();
|
||||
let r = optimize_to(&mut s, merge(&start, json!({"desiredK": (total * 3 / 4) as f64 / 1024.0})));
|
||||
assert_eq!((r["achieved"].as_bool(), r["images"].as_u64()), (Some(true), Some(layout.len() as u64)), "{r}");
|
||||
let after = sizes(&mut s, &r["settings"]);
|
||||
assert_eq!(after.iter().sum::<usize>(), r["bytes"].as_u64().unwrap() as usize, "the slice files together");
|
||||
let largest = *all.iter().max().unwrap();
|
||||
let r = optimize_to(&mut s, merge(&start, json!({"desiredK": (largest * 3 / 4) as f64 / 1024.0, "use": "eachSlice"})));
|
||||
let after = sizes(&mut s, &r["settings"]);
|
||||
assert_eq!(*after.iter().max().unwrap(), r["bytes"].as_u64().unwrap() as usize, "the largest slice file");
|
||||
assert!(r["achieved"].as_bool().unwrap() && after.iter().all(|n| *n <= r["targetBytes"].as_u64().unwrap() as usize), "{r}");
|
||||
let n = layout[0]["number"].as_u64().unwrap();
|
||||
let one_slice = written(&mut s, &merge(&start, json!({"slice": n})));
|
||||
let r = optimize_to(&mut s, merge(&start, json!({"desiredK": (one_slice / 2) as f64 / 1024.0, "slice": n})));
|
||||
assert_eq!(r["images"].as_u64(), Some(1));
|
||||
assert_eq!(written(&mut s, &merge(&r["settings"], json!({"slice": n}))), r["bytes"].as_u64().unwrap() as usize, "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn optimize_to_file_size_finds_a_fit_when_a_lower_setting_gives_a_larger_file() {
|
||||
use cmd::webexport::{OPTIMIZE_SAMPLES, WebSettings, highest_within, set_quality};
|
||||
// Sizes that do not fall with the quality: 1 to 20 give 900 bytes, 21 to 70 give 400 to 449,
|
||||
// and 71 and up give over 1000.
|
||||
let size_of = |q: u8| match q {
|
||||
..=20 => 900,
|
||||
21..=70 => 400 + usize::from(q - 21),
|
||||
_ => 1000 + usize::from(q),
|
||||
};
|
||||
let start = WebSettings { quality: 90, ..WebSettings::default() };
|
||||
let mut measured = Vec::new();
|
||||
let mut smallest = None;
|
||||
let mut size = |s: &WebSettings| {
|
||||
measured.push(s.quality);
|
||||
Ok(Some(size_of(s.quality)))
|
||||
};
|
||||
let found = highest_within(&mut size, &start, (1, 90), set_quality, 500, &mut smallest).unwrap();
|
||||
let (settings, bytes) = found.expect("a quality within 500 bytes");
|
||||
assert_eq!((settings.quality, bytes), (70, 449), "measured {measured:?}");
|
||||
assert!(measured.len() <= usize::from(OPTIMIZE_SAMPLES) + 7, "measured {measured:?}");
|
||||
// Nothing fits: the smallest size measured is kept.
|
||||
let mut smallest = None;
|
||||
let mut size = |s: &WebSettings| Ok(Some(size_of(s.quality)));
|
||||
assert!(highest_within(&mut size, &start, (1, 90), set_quality, 100, &mut smallest).unwrap().is_none());
|
||||
assert_eq!(smallest.map(|(s, n)| (s.quality, n)), Some((36, 415)));
|
||||
}
|
||||
|
||||
@@ -1255,9 +1255,11 @@ fn direct_selection_shift_marquee_toggles_anchors() {
|
||||
let st = s.doc().unwrap();
|
||||
assert_eq!(st.selection.objects, vec![a]);
|
||||
assert_eq!(st.selection.partial(a), None);
|
||||
// Group Selection's marquee toggles the same way.
|
||||
// Group Selection's marquee toggles the paths it touches whole: a leaves, b joins (#8047).
|
||||
gesture(&mut s, "groupSelection", &top, shift);
|
||||
assert_eq!(s.doc().unwrap().selection.partial(a).map(|p| p.len()), Some(2));
|
||||
let st = s.doc().unwrap();
|
||||
assert_eq!(st.selection.objects, vec![b]);
|
||||
assert_eq!(st.selection.partial(b), None);
|
||||
}
|
||||
|
||||
/// The Lasso: Shift adds anchors, Alt takes them away, and neither drops the rest of the
|
||||
|
||||
@@ -173,6 +173,12 @@ impl Session {
|
||||
let text_selection = ((id == "eyedropper" && is_type(self.tool.id())) || (self.tool.id() == "eyedropper" && is_type(id)))
|
||||
.then(|| self.tool.options())
|
||||
.filter(|o| o.get("editing").is_some_and(|v| !v.is_null()) && o.get("start") != o.get("end"));
|
||||
// The gradient mesh points the Mesh tool, Direct Selection or the Lasso picked stay picked
|
||||
// for the Eyedropper, which samples into them (#8090), and for the tool after it.
|
||||
let mesh_points = (id == "eyedropper" || self.tool.id() == "eyedropper")
|
||||
.then(|| self.tool.options().get("meshPoints").cloned())
|
||||
.flatten()
|
||||
.filter(|v| v.as_array().is_some_and(|a| !a.is_empty()));
|
||||
let acts = self.with_tool_cx(view, |t, cx| t.deactivate(cx));
|
||||
self.apply_actions(acts)?;
|
||||
self.keep_tool_settings();
|
||||
@@ -180,6 +186,9 @@ impl Session {
|
||||
if let Some(selection) = text_selection {
|
||||
self.tool.set_option("textSelection", &selection);
|
||||
}
|
||||
if let Some(points) = mesh_points {
|
||||
self.tool.set_option("meshPoints", &points);
|
||||
}
|
||||
if vectorcraft_tools::catalog::is_selection_tool(id) {
|
||||
self.last_selection_tool = Some(self.tool.id());
|
||||
self.select_whole_instance(id);
|
||||
@@ -258,7 +267,13 @@ impl Session {
|
||||
// The lending tool does not see the press: it counts as a press elsewhere for the clicks a
|
||||
// double-click or triple-click compares.
|
||||
self.tool.press_elsewhere();
|
||||
let lent = self.make_tool(id);
|
||||
let mut lent = self.make_tool(id);
|
||||
// The gradient mesh points the Eyedropper holds are the lent tool's picks, which a Shift
|
||||
// click adds to (#8090).
|
||||
if self.tool.id() == "eyedropper" {
|
||||
let points = self.tool.options().get("meshPoints").cloned().unwrap_or_else(|| Value::Array(vec![]));
|
||||
lent.set_option("meshPoints", &points);
|
||||
}
|
||||
self.selection_at_lend = self.active().map(|d| (d.uid, d.selection.clone()));
|
||||
self.lender = Some(std::mem::replace(&mut self.tool, lent));
|
||||
Ok((PointerEvent { mods: Mods { cmd: false, ..ev.mods }, ..*ev }, settled))
|
||||
@@ -269,10 +284,17 @@ impl Session {
|
||||
/// Cmd+click that takes the type being edited out of the selection ends its edit (#3779).
|
||||
pub(crate) fn give_back_tool(&mut self, view: ViewInfo) -> Result<()> {
|
||||
let Some(lender) = self.lender.take() else { return Ok(()) };
|
||||
// The points the lent tool left picked go back to the Eyedropper, none when it unpicked
|
||||
// them all (#8090). Group Selection picks no mesh points, so the Eyedropper keeps its own.
|
||||
let mesh_points =
|
||||
(lender.id() == "eyedropper" && self.tool.id() != "groupSelection").then(|| self.tool.options().get("meshPoints").cloned()).flatten();
|
||||
let acts = self.with_tool_cx(view, |t, cx| t.deactivate(cx));
|
||||
let r = self.apply_actions(acts);
|
||||
self.keep_tool_settings();
|
||||
self.tool = lender;
|
||||
if let Some(points) = mesh_points {
|
||||
self.tool.set_option("meshPoints", &points);
|
||||
}
|
||||
// A gesture that left the selection as it found it (a Shift marquee over nothing) picked
|
||||
// nothing: the selection keeps what it was, the Pen's last anchor or an earlier pick.
|
||||
let left = self.active().map(|d| (d.uid, d.selection.clone()));
|
||||
|
||||
@@ -3827,6 +3827,83 @@ fn editing_text() -> String {
|
||||
)
|
||||
}
|
||||
|
||||
/// The range of [`ai_written_meshes_never_panic`]'s cuts and edits: past the end of [`meshes_text`].
|
||||
const MESHES_FUZZ_CHARS: usize = 24_000;
|
||||
|
||||
/// The editing data VectorCraft writes for a document with two gradient meshes: 2 × 3 patches whose
|
||||
/// rows of points are RGB, CMYK and gray, at half opacity and named; a 1 × 1 mesh with a point at
|
||||
/// 40% opacity; and an instance of a symbol whose art is a 2 × 1 mesh.
|
||||
fn meshes_text() -> &'static str {
|
||||
static TEXT: std::sync::OnceLock<String> = std::sync::OnceLock::new();
|
||||
TEXT.get_or_init(|| {
|
||||
use vectorcraft_color::Color;
|
||||
use vectorcraft_doc::live::{GradientMesh, MeshPoint, grid_points, smooth_handles};
|
||||
use vectorcraft_doc::{Node, NodeKind};
|
||||
use vectorcraft_geom::Rect;
|
||||
let mesh = |r: Rect, rows: u32, cols: u32, color: &dyn Fn(usize) -> Color| {
|
||||
let pts = grid_points(r, rows, cols);
|
||||
let handles = smooth_handles(rows, cols, &pts);
|
||||
let width = cols as usize + 1;
|
||||
let points = pts
|
||||
.iter()
|
||||
.zip(handles)
|
||||
.enumerate()
|
||||
.map(|(i, (p, h))| MeshPoint { p: *p, color: color(i / width), opacity: 1.0, handles: h })
|
||||
.collect();
|
||||
GradientMesh { rows, cols, points }
|
||||
};
|
||||
let mut doc = Document::new(300.0, 200.0);
|
||||
let layer = doc.layers[0].id;
|
||||
let sheet = mesh(Rect::new(20.0, 20.0, 200.0, 120.0), 2, 3, &|row| match row {
|
||||
0 => Color::rgb(1.0, 0.5, 0.0),
|
||||
1 => Color::cmyk(0.1, 0.6, 0.2, 0.05),
|
||||
_ => Color::gray(0.4),
|
||||
});
|
||||
let mut sheet = Node::new(doc.alloc_id(), NodeKind::Mesh(sheet));
|
||||
(sheet.name, sheet.opacity) = (Some("Sheet".into()), 0.5);
|
||||
doc.insert(Some(layer), usize::MAX, sheet).unwrap();
|
||||
let mut small = mesh(Rect::new(220.0, 20.0, 280.0, 80.0), 1, 1, &|row| Color::rgb(0.0, 0.3, 0.3 + 0.5 * row as f32));
|
||||
small.points[1].opacity = 0.4;
|
||||
let small = Node::new(doc.alloc_id(), NodeKind::Mesh(small));
|
||||
doc.insert(Some(layer), usize::MAX, small).unwrap();
|
||||
let patch = mesh(Rect::new(0.0, 0.0, 40.0, 30.0), 2, 1, &|row| Color::rgb(0.2 * row as f32, 0.6, 0.1));
|
||||
let patch = Node::new(doc.alloc_id(), NodeKind::Mesh(patch));
|
||||
doc.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Patch".into(), art: std::sync::Arc::new(patch) });
|
||||
let instance =
|
||||
Node::new(doc.alloc_id(), NodeKind::SymbolInstance { symbol: "Patch".into(), xf: vectorcraft_geom::Affine::translate((20.0, 140.0)) });
|
||||
doc.insert(Some(layer), usize::MAX, instance).unwrap();
|
||||
let out = vectorcraft_eps::export_ai_editing(&doc, &vectorcraft_eps::AiEditingOptions::default()).unwrap();
|
||||
String::from_utf8(out.program).unwrap()
|
||||
})
|
||||
}
|
||||
|
||||
/// The data [`ai_written_meshes_never_panic`] damages, as it is, opens with both meshes, the symbol
|
||||
/// with its mesh and its instance, and the property's cuts and edits reach all of it.
|
||||
#[test]
|
||||
fn the_written_meshes_fuzz_data_opens_as_meshes() {
|
||||
use vectorcraft_doc::NodeKind;
|
||||
let text = meshes_text();
|
||||
assert!(text.chars().count() < MESHES_FUZZ_CHARS, "{}", text.chars().count());
|
||||
for mark in ["%AI14_BeginSymbol", "%AI5_BeginLayer", "/Mesh X!", "%_[2 3] /Size X#", "%_/DeviceCMYK /CS X#", "/End X!", "/SymbolInstance :"] {
|
||||
assert!(text.replace("\r\n", "\n").contains(mark), "{mark}");
|
||||
}
|
||||
let private = [b"%AI24_ZStandard_Data".as_slice(), &zstd(text)].concat();
|
||||
let (d, warnings, layered) = vectorcraft_eps::layered_ai(&private, Document::new(300.0, 200.0), vec![], false, true, 1.0);
|
||||
assert!(layered, "{warnings:?}");
|
||||
let art = d.layers[0].children().unwrap();
|
||||
let kinds: Vec<&str> = art
|
||||
.iter()
|
||||
.map(|n| match n.kind {
|
||||
NodeKind::Mesh(_) => "mesh",
|
||||
NodeKind::SymbolInstance { .. } => "instance",
|
||||
_ => "other",
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(kinds, ["mesh", "mesh", "instance"], "{warnings:?}");
|
||||
let patch = d.symbols.iter().find(|s| s.name == "Patch").map(|s| &s.art.kind);
|
||||
assert!(matches!(patch, Some(NodeKind::Mesh(_))), "{patch:?}");
|
||||
}
|
||||
|
||||
fn zstd(text: &str) -> Vec<u8> {
|
||||
ruzstd::encoding::compress_to_vec(text.as_bytes(), ruzstd::encoding::CompressionLevel::Fastest)
|
||||
}
|
||||
@@ -4482,6 +4559,17 @@ proptest! {
|
||||
survive("mutated .ai editing data", || Some(vectorcraft_eps::layered_ai(&private, Document::new(100.0, 100.0), vec![], false, false, 1.0).0))?;
|
||||
}
|
||||
|
||||
/// A `.ai` whose gradient meshes, as the writer writes them, are damaged: the record's type,
|
||||
/// size, places, color spaces and corners on `%_` lines, its `/Mesh X!` and `/End X!`, and the
|
||||
/// mesh's transparency and name, cut short or edited.
|
||||
#[test]
|
||||
fn ai_written_meshes_never_panic(cut in 0usize..MESHES_FUZZ_CHARS, edits in prop::collection::vec((0usize..MESHES_FUZZ_CHARS, prop::sample::select(vec!['0', '1', '2', '9', '-', '.', 'e', ' ', '\n', '[', ']', '(', ')', '/', '%', '_', 'X', '!', '#', 'N', 'P', 'E'])), 0..12)) {
|
||||
let text = mutate_text(meshes_text(), cut, &edits);
|
||||
let private = [b"%AI24_ZStandard_Data".as_slice(), &zstd(&text)].concat();
|
||||
survive("mutated .ai meshes", || Some(vectorcraft_eps::layered_ai(&private, Document::new(300.0, 200.0), vec![], false, false, 1.0).0))?;
|
||||
survive("mutated .ai meshes, trusted", || Some(vectorcraft_eps::layered_ai(&private, Document::new(300.0, 200.0), vec![], false, true, 1.0).0))?;
|
||||
}
|
||||
|
||||
/// The active artboard that a restored `.ai` opens on, read from damaged or hostile editing data.
|
||||
#[test]
|
||||
fn ai_active_artboard_never_panics(cut in 0usize..600, edits in prop::collection::vec((0usize..600, prop::sample::select(vec!['0', '9', '-', ' ', '\n', '/', ':', ';', ',', '%', '_'])), 0..12)) {
|
||||
@@ -5066,6 +5154,81 @@ proptest! {
|
||||
survive("mutated .ai brushes", || Some(vectorcraft_eps::layered_ai(&private, Document::new(200.0, 100.0), vec![], false, false, 1.0).0))?;
|
||||
survive("mutated .ai brushes, trusted", || Some(vectorcraft_eps::layered_ai(&private, Document::new(200.0, 100.0), vec![], false, true, 1.0).0))?;
|
||||
}
|
||||
|
||||
/// A `.ai` whose blends, as the writer writes them, are damaged: the keys and spine on `%_`
|
||||
/// lines with their dictionaries, the drawn steps, the record's `XP` and its hex, and the
|
||||
/// blend's transparency, cut short or edited.
|
||||
#[test]
|
||||
fn ai_written_blends_never_panic(cut in 0usize..BLENDS_FUZZ_CHARS, edits in prop::collection::vec((0usize..BLENDS_FUZZ_CHARS, prop::sample::select(vec!['0', '1', '2', '8', '9', 'A', 'F', '-', '.', ' ', '\n', '(', ')', '/', ',', ';', '%', '_', 'u', 'U', 'K', 'S', 'X', 'P'])), 0..12)) {
|
||||
let text = mutate_text(blends_text(), cut, &edits);
|
||||
let private = [b"%AI24_ZStandard_Data".as_slice(), &zstd(&text)].concat();
|
||||
survive("mutated .ai blends", || Some(vectorcraft_eps::layered_ai(&private, Document::new(300.0, 200.0), vec![], false, false, 1.0).0))?;
|
||||
survive("mutated .ai blends, trusted", || Some(vectorcraft_eps::layered_ai(&private, Document::new(300.0, 200.0), vec![], false, true, 1.0).0))?;
|
||||
}
|
||||
}
|
||||
|
||||
/// The range of [`ai_written_blends_never_panic`]'s cuts and edits: past the end of [`blends_text`].
|
||||
const BLENDS_FUZZ_CHARS: usize = 24_000;
|
||||
|
||||
/// The editing data VectorCraft writes for a document with two blends: red to blue squares with
|
||||
/// three steps and no spine of its own, at half opacity; and three squares 25 pt apart on a spine
|
||||
/// edited on the canvas, aligned to the path.
|
||||
fn blends_text() -> &'static str {
|
||||
static TEXT: std::sync::OnceLock<String> = std::sync::OnceLock::new();
|
||||
TEXT.get_or_init(|| {
|
||||
use std::sync::Arc;
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::live::{BlendOrientation, BlendSpacing, BlendSpec};
|
||||
use vectorcraft_doc::{Appearance, Node, NodeKind};
|
||||
use vectorcraft_geom::{PathData, Point, Rect, SubPath, shapes};
|
||||
let mut doc = Document::new(300.0, 200.0);
|
||||
let layer = doc.layers[0].id;
|
||||
let square = |doc: &mut Document, x: f64, y: f64, c: Color| {
|
||||
Arc::new(Node::path(
|
||||
doc.alloc_id(),
|
||||
shapes::rectangle(Rect::new(x, y, x + 20.0, y + 20.0)),
|
||||
Appearance::basic(Paint::solid(c), Paint::None, 0.0),
|
||||
))
|
||||
};
|
||||
let (red, blue, green) = (Color::rgb(1.0, 0.0, 0.0), Color::rgb(0.0, 0.0, 1.0), Color::rgb(0.0, 1.0, 0.0));
|
||||
let keys = vec![square(&mut doc, 20.0, 20.0, red), square(&mut doc, 120.0, 20.0, blue)];
|
||||
let mut fade = Node::new(
|
||||
doc.alloc_id(),
|
||||
NodeKind::Blend { children: keys, spec: Box::new(BlendSpec { spacing: BlendSpacing::Steps(3), ..BlendSpec::default() }) },
|
||||
);
|
||||
fade.opacity = 0.5;
|
||||
doc.insert(Some(layer), usize::MAX, fade).unwrap();
|
||||
let keys = vec![square(&mut doc, 20.0, 80.0, red), square(&mut doc, 120.0, 80.0, blue), square(&mut doc, 170.0, 80.0, green)];
|
||||
let centers: Vec<Point> = [30.0, 130.0, 180.0].iter().map(|x| Point::new(*x, 90.0)).collect();
|
||||
let spec = BlendSpec {
|
||||
spacing: BlendSpacing::Distance(25.0),
|
||||
orientation: BlendOrientation::AlignToPath,
|
||||
spine: Some(PathData::single(SubPath::polyline(¢ers, false))),
|
||||
key_anchors: vec![0, 1, 2],
|
||||
..BlendSpec::default()
|
||||
};
|
||||
let path = Node::new(doc.alloc_id(), NodeKind::Blend { children: keys, spec: Box::new(spec) });
|
||||
doc.insert(Some(layer), usize::MAX, path).unwrap();
|
||||
let out = vectorcraft_eps::export_ai_editing(&doc, &vectorcraft_eps::AiEditingOptions::default()).unwrap();
|
||||
String::from_utf8(out.program).unwrap()
|
||||
})
|
||||
}
|
||||
|
||||
/// The data [`ai_written_blends_never_panic`] damages, as it is, opens with both blends live, and
|
||||
/// the property's cuts and edits reach all of it.
|
||||
#[test]
|
||||
fn the_written_blends_fuzz_data_opens_live() {
|
||||
use vectorcraft_doc::NodeKind;
|
||||
let text = blends_text();
|
||||
assert!(text.chars().count() < BLENDS_FUZZ_CHARS, "{}", text.chars().count());
|
||||
for mark in ["%AI5_BeginLayer", "%_(K) /String (ShapeBlendPathType) ,", "%_(S) /String (ShapeBlendPathType) ,", "1 0 92 XP", "1 0 116 XP"] {
|
||||
assert!(text.replace("\r\n", "\n").contains(mark), "{mark}");
|
||||
}
|
||||
let private = [b"%AI24_ZStandard_Data".as_slice(), &zstd(text)].concat();
|
||||
let (d, warnings, layered) = vectorcraft_eps::layered_ai(&private, Document::new(300.0, 200.0), vec![], false, true, 1.0);
|
||||
assert!(layered, "{warnings:?}");
|
||||
let art = d.layers[0].children().unwrap();
|
||||
assert_eq!(art.iter().map(|n| matches!(n.kind, NodeKind::Blend { .. })).collect::<Vec<_>>(), [true, true], "{warnings:?}");
|
||||
}
|
||||
|
||||
/// The range of [`ai_written_styles_never_panic`]'s cuts and edits: past the end of [`styles_text`].
|
||||
|
||||
@@ -61,6 +61,20 @@ fn selection_commands_report_the_resulting_selection() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn toggle_and_add_handle_each_listed_id_in_order() {
|
||||
let (mut s, a, b) = session();
|
||||
let c = NodeId(s.execute("shape.rectangle", &json!({"x": 40, "y": 0, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
// `a` goes off and back on at the end, `b` goes off, and `c` comes on.
|
||||
assert_eq!(s.execute("select.toggle", &json!({"ids": [a.0, b.0, c.0, a.0]})).unwrap(), json!({"count": 2, "ids": [c.0, a.0]}));
|
||||
assert_eq!(s.execute("select.add", &json!({"ids": [b.0, a.0, b.0]})).unwrap(), json!({"count": 3, "ids": [c.0, a.0, b.0]}));
|
||||
// Inverse selects the objects that were not selected, in document order.
|
||||
s.execute("select.set", &json!({"ids": [b.0]})).unwrap();
|
||||
s.execute("select.inverse", &json!({})).unwrap();
|
||||
assert_eq!(s.active().unwrap().selection.objects, [a, c]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn single_id_toggle_validates_before_mutating() {
|
||||
let (mut s, a, _) = session();
|
||||
|
||||
@@ -120,7 +120,9 @@
|
||||
//! and opacity mask and a state block as a group's with its opacity and blending mode (an
|
||||
//! instance with isolation, knockout or knockout shape of its own is written as its art). The
|
||||
//! definitions are at most the reader's 4,096. In a symbol's art, an instance's matrix and
|
||||
//! a gradient's take the art to the canvas's space turned y up about art space's origin there.
|
||||
//! a gradient's take the art to the canvas's space turned y up about art space's origin there,
|
||||
//! and a gradient mesh's corners are in that space; an envelope's contents in its dictionary are
|
||||
//! in the canvas's space with y down.
|
||||
//! - Art styles, as the reader reads them (`style.rs`, `read/ops.rs`): a path, compound path or
|
||||
//! group with live effects or linked to a graphic style is written as its drawn look (`u`, its
|
||||
//! vector art as its geometry effects leave it, without shadows, glows or feathers, `U`, its
|
||||
@@ -147,6 +149,19 @@
|
||||
//! reader reads back as the same graph ([`crate::ai_graph`]) is written as its group between
|
||||
//! `%_Gs`, its functional records and `%_GS`, each series' group tagged `Go` right after its end;
|
||||
//! any other graph, and a graph with art left out, as its art, with a warning.
|
||||
//! - Gradient meshes, as the reader reads them (`mesh.rs`): `/Mesh X!`, `2 /Version`, the grid's type
|
||||
//! and size, `/Data` (the reader passes over the version and `/Data`), and each patch's place, color
|
||||
//! space and four corners (color, opacity, point and handles) as `X#` entries on `%_` lines,
|
||||
//! `/End X!`; the mesh's transparency before it, its name and opacity mask after it
|
||||
//! (`writer::meshes`). A mesh is written as it is only when the reader reads it back so, when every
|
||||
//! patch turns the same way (a reflected mesh's columns are written in reverse order), and outside
|
||||
//! pattern tiles, art cut to a clipping object and a large canvas.
|
||||
//! - Blends, as the reader reads them (`blend.rs`): the blend's key objects and spine as a group on
|
||||
//! `%_` lines, each key's `/ArtDictionary` naming it a key and its id and the spine's naming it the
|
||||
//! spine (written when the blend has a spine of its own); its steps drawn, a group;
|
||||
//! the blend plugin's `1 0 n XP` line and the blend's record of its spacing, orientation and keys as hex
|
||||
//! on `%` lines; its name and transparency as a group's after its end (`writer::blends`). A blend is
|
||||
//! written live only when the reader reads it back with its settings.
|
||||
//!
|
||||
//! Lines end in CR LF. Strings are written in UTF-8. Art space is ruler space: y up, its origin at
|
||||
//! the first artboard's top-left corner. On the canvas ([`CANVAS_SIZE`] points square, y down) the
|
||||
@@ -176,7 +191,10 @@
|
||||
//! and instances of
|
||||
//! symbols past 4,096 as their art (symbol art past [`vectorcraft_doc::MAX_SYMBOL_NODES`] objects
|
||||
//! in all left out), instances of symbols the document doesn't have as empty groups, symbols' 9-slice
|
||||
//! guides, export types and dynamic type left out, live objects (placed documents included) as their art,
|
||||
//! guides, export types and dynamic type left out, gradient meshes the reader wouldn't read back as
|
||||
//! they are, folded meshes, meshes in pattern tiles and in art cut to a clipping object and every mesh
|
||||
//! on a large canvas as their drawn look, blends the reader wouldn't read back live as
|
||||
//! their steps, other live objects (placed documents included) as their art,
|
||||
//! strokes a plain line can't draw and the object's art style doesn't hold
|
||||
//! as their filled outlines, several fills or strokes as a group of a path for each, freeform
|
||||
//! gradient swatches, gradient swatches of more than 256 stops, swatches of patterns written as
|
||||
@@ -289,6 +307,8 @@ fn export_held(source: &Document, o: &AiEditingOptions, max_objects: usize, keep
|
||||
let links = writer::style_links(doc);
|
||||
// Before baking, which leaves the wrap objects that may be written as they are unchanged.
|
||||
let wraps_held = if keep_wraps { writer::wraps_held(doc, &styled) } else { HashSet::new() };
|
||||
// The blends baking leaves as they are, which may be written live.
|
||||
let unbaked_blends = writer::unbaked_blends(doc);
|
||||
// Live geometry effects as their result, as the PDF part draws them.
|
||||
let baked = baked(doc);
|
||||
let doc = baked.as_ref().unwrap_or(doc);
|
||||
@@ -319,6 +339,9 @@ fn export_held(source: &Document, o: &AiEditingOptions, max_objects: usize, keep
|
||||
// On a large canvas the layers' symbol instances are written as their art.
|
||||
w.symbols_live = scale == 1.0;
|
||||
w.brushes_live = scale == 1.0;
|
||||
w.meshes_live = scale == 1.0;
|
||||
w.blends_live = scale == 1.0;
|
||||
w.unbaked_blends = unbaked_blends;
|
||||
w.symbol_doc = symbol_doc;
|
||||
w.max_objects = max_objects;
|
||||
w.wraps_held = wraps_held;
|
||||
|
||||
+2153
-27
File diff suppressed because it is too large
Load Diff
@@ -15,19 +15,26 @@ use vectorcraft_pathops::BoolOp;
|
||||
use crate::ai_ops::{self, unit};
|
||||
use crate::ps;
|
||||
|
||||
mod blends;
|
||||
mod brushes;
|
||||
mod envelopes;
|
||||
mod images;
|
||||
mod meshes;
|
||||
mod paints;
|
||||
mod styles;
|
||||
mod symbols;
|
||||
mod texts;
|
||||
mod variables;
|
||||
|
||||
#[cfg(test)]
|
||||
pub(super) use blends::BLENDS;
|
||||
pub(super) use blends::unbaked_blends;
|
||||
#[cfg(test)]
|
||||
pub(super) use brushes::BRUSHES;
|
||||
#[cfg(test)]
|
||||
pub(super) use envelopes::ENVELOPES;
|
||||
#[cfg(test)]
|
||||
pub(super) use meshes::MESHES;
|
||||
pub(super) use styles::{LARGE_CANVAS_STYLES, style_links, styled_definitions, styled_objects};
|
||||
#[cfg(test)]
|
||||
pub(super) use styles::{PANEL_EMPTY, PANEL_STYLES, STYLE_LINKS, WARPED_IMAGES, same_appearance};
|
||||
@@ -58,7 +65,7 @@ pub(super) const PATTERN_TILES: &str = "pattern fills with more tiles than a fil
|
||||
pub(super) const CLIPPING: &str = "clipping groups and clipping layers whose clipping object isn't a path, and the clipping groups inside them, are written as their art cut to that object in the editing data for other apps";
|
||||
pub(super) const CLIP_PAINT: &str = "the fills and strokes of clipping paths that a plain fill and line can't draw are written as paths of their own inside the clipping (fills under the clipped art, strokes over it) in the editing data for other apps";
|
||||
pub(super) const CLIP_PAINT_MASKS: &str = "the opacity masks of clipping paths whose fills and strokes are written as paths of their own stay on the clipping path, not on those paths, in the editing data for other apps";
|
||||
pub(super) const LIVE: &str = "blends, meshes, repeats, placed documents and intertwines are written as their art in the editing data for other apps";
|
||||
pub(super) const LIVE: &str = "repeats, placed documents and intertwines are written as their art in the editing data for other apps";
|
||||
pub(super) const GRAPHS: &str = "graphs are written as their art, without their data or settings, in the editing data for other apps";
|
||||
pub(super) const STROKES: &str = "strokes a plain line can't draw (inside or outside the path, variable width, dots, dashes fitted to corners, gradients, patterns, arrowheads) are written as filled outlines, and brushed strokes as their brush's art, in the editing data for other apps";
|
||||
pub(super) const ITEM_TRANSPARENCY: &str =
|
||||
@@ -304,6 +311,9 @@ pub(super) struct Writer<'a> {
|
||||
brush_set: brushes::Brushes,
|
||||
/// Brushes may be written; false on a large canvas, where they are left out.
|
||||
pub(super) brushes_live: bool,
|
||||
/// Gradient meshes may be written as meshes; false on a large canvas, where they are written as
|
||||
/// their drawn look.
|
||||
pub(super) meshes_live: bool,
|
||||
/// The object just written is an envelope's distorted art, which the plugin's `XP` follows
|
||||
/// ([`Self::envelope`]).
|
||||
deform: bool,
|
||||
@@ -328,6 +338,14 @@ pub(super) struct Writer<'a> {
|
||||
series_tag: Option<String>,
|
||||
/// Where the `Go` lines of the graph being written start in [`Self::body`].
|
||||
graph_tags: Vec<usize>,
|
||||
/// Blends may be written live; false on a large canvas, where they are written as their steps.
|
||||
pub(super) blends_live: bool,
|
||||
/// How many more objects the reader's blends may lay out ([`crate::import::BLEND_BUDGET`]).
|
||||
blend_budget: usize,
|
||||
/// The entries naming a blend's key object in its dictionary, and the key's id.
|
||||
blend_role: Option<(NodeId, String)>,
|
||||
/// The blends baking left as they are ([`blends::unbaked_blends`]); only these are written live.
|
||||
pub(super) unbaked_blends: HashSet<NodeId>,
|
||||
}
|
||||
|
||||
impl<'a> Writer<'a> {
|
||||
@@ -395,6 +413,7 @@ impl<'a> Writer<'a> {
|
||||
wrap_moved: false,
|
||||
brush_set: brushes::Brushes::default(),
|
||||
brushes_live: true,
|
||||
meshes_live: true,
|
||||
deform: false,
|
||||
checks_left: crate::import::ENVELOPE_CHECKS,
|
||||
objects: 0,
|
||||
@@ -410,6 +429,10 @@ impl<'a> Writer<'a> {
|
||||
in_graph: false,
|
||||
series_tag: None,
|
||||
graph_tags: vec![],
|
||||
blends_live: true,
|
||||
blend_budget: crate::import::BLEND_BUDGET,
|
||||
blend_role: None,
|
||||
unbaked_blends: HashSet::new(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -723,6 +746,11 @@ impl<'a> Writer<'a> {
|
||||
return self.styled_object(n, &orig, &name);
|
||||
}
|
||||
self.effects(n);
|
||||
// A gradient mesh the reader reads as it is; else it is written as its drawn look.
|
||||
let mut mesh = match &n.kind {
|
||||
NodeKind::Mesh(m) => self.mesh_record(m),
|
||||
_ => None,
|
||||
};
|
||||
self.state(n.locked, !n.visible);
|
||||
let mut xy = Xy::of(n);
|
||||
if masked_warp_pieces(n) {
|
||||
@@ -738,6 +766,11 @@ impl<'a> Writer<'a> {
|
||||
let charged = self.charges();
|
||||
match &n.kind {
|
||||
NodeKind::Layer { .. } => {}
|
||||
NodeKind::Mesh(_) if mesh.is_some() => {
|
||||
if let Some(record) = mesh.take() {
|
||||
self.write_mesh(&record, xy);
|
||||
}
|
||||
}
|
||||
NodeKind::Group { children, clip: true } => self.clip_group(children, xy),
|
||||
NodeKind::Group { children, clip: false } => {
|
||||
if self.open_group("u") {
|
||||
@@ -840,7 +873,10 @@ impl<'a> Writer<'a> {
|
||||
}
|
||||
NodeKind::Envelope { .. } if self.envelope(n, xy) => {}
|
||||
NodeKind::Envelope { .. } => self.drawn_art(n, xy, Some(envelopes::ENVELOPES), true),
|
||||
NodeKind::Blend { .. } | NodeKind::Mesh(_) | NodeKind::Repeat(_) | NodeKind::PlacedDocument(_) | NodeKind::Intertwine { .. } => {
|
||||
NodeKind::Mesh(_) => self.drawn_art(n, xy, Some(meshes::MESHES), true),
|
||||
NodeKind::Blend { .. } if self.blend(n, xy) => {}
|
||||
NodeKind::Blend { .. } => self.drawn_art(n, xy, Some(blends::BLENDS), true),
|
||||
NodeKind::Repeat(_) | NodeKind::PlacedDocument(_) | NodeKind::Intertwine { .. } => {
|
||||
self.drawn_art(n, xy, Some(LIVE), true);
|
||||
}
|
||||
// Ruler guides are kept in the document's native copy only.
|
||||
@@ -919,7 +955,8 @@ impl<'a> Writer<'a> {
|
||||
self.warn(w);
|
||||
}
|
||||
let moved = bounds && self.wrap_on_bounds(n, state);
|
||||
if self.nest < MAX_NEST {
|
||||
// A gradient mesh's drawn look is paths, which hold nothing: it is written at any depth.
|
||||
if self.nest < MAX_NEST || matches!(n.kind, NodeKind::Mesh(_)) {
|
||||
let g = vectorcraft_effects::expand_live_deep(Some(self.doc), n);
|
||||
self.nest += 1;
|
||||
self.drawn += 1;
|
||||
@@ -955,9 +992,10 @@ impl<'a> Writer<'a> {
|
||||
/// `n`'s `/ArtDictionary`, after it, when it has a name (`AI10_ArtUID`, see [`Self::take_id`]),
|
||||
/// is bound to variables ([`Self::bound_variables`]; without a name, it gets an XML id and an
|
||||
/// empty `AIArtName`), has text wrap options ([`Self::text_wrap`]), has an opacity mask
|
||||
/// (`AI9_Mask`, see [`Self::mask`]), or is a symbol's art (its symbol's entries first, see
|
||||
/// [`Self::define_symbol`]). False when `n` has an opacity mask that is left out: nested too
|
||||
/// deep, or its art doesn't fit.
|
||||
/// (`AI9_Mask`, see [`Self::mask`]), is a symbol's art (its symbol's entries first, see
|
||||
/// [`Self::define_symbol`]), or is a blend's key object (its part and id after the name, see
|
||||
/// [`blends`]). False when `n` has an opacity mask that is left out: nested too deep, or its art
|
||||
/// doesn't fit.
|
||||
fn dictionary(&mut self, n: &Node) -> bool {
|
||||
let name = n.name.as_deref().filter(|s| !s.is_empty());
|
||||
let moved = std::mem::take(&mut self.wrap_moved);
|
||||
@@ -977,7 +1015,11 @@ impl<'a> Writer<'a> {
|
||||
Some((id, _)) if *id == n.id => self.root_entries.take().map(|(_, e)| e),
|
||||
_ => None,
|
||||
};
|
||||
if name.is_none() && mask.is_none() && bound.is_empty() && entries.is_none() && wrap.is_none() {
|
||||
let role = match &self.blend_role {
|
||||
Some((id, _)) if *id == n.id => self.blend_role.take().map(|(_, e)| e),
|
||||
_ => None,
|
||||
};
|
||||
if name.is_none() && mask.is_none() && bound.is_empty() && entries.is_none() && wrap.is_none() && role.is_none() {
|
||||
return mask_written;
|
||||
}
|
||||
let start = self.body.len();
|
||||
@@ -998,6 +1040,10 @@ impl<'a> Writer<'a> {
|
||||
self.bound.push((n.id, id, bound));
|
||||
}
|
||||
}
|
||||
let has_role = role.is_some();
|
||||
if let Some(r) = role {
|
||||
self.body.push_str(&r);
|
||||
}
|
||||
if let Some(w) = wrap {
|
||||
self.text_wrap(w);
|
||||
}
|
||||
@@ -1005,7 +1051,7 @@ impl<'a> Writer<'a> {
|
||||
if let Some(m) = mask
|
||||
&& !self.mask(m)
|
||||
{
|
||||
if !has_id && !has_entries && wrap.is_none() {
|
||||
if !has_id && !has_entries && wrap.is_none() && !has_role {
|
||||
self.body.truncate(start);
|
||||
return false;
|
||||
}
|
||||
@@ -1701,8 +1747,8 @@ impl<'a> Writer<'a> {
|
||||
self.plain_color(*color, stroke);
|
||||
}
|
||||
|
||||
/// A color that names no swatch: `g` (gray), `k` (CMYK), else `c m y k r g b Xa` (RGB in the
|
||||
/// working RGB space, and Lab as display RGB), with its CMYK equivalent (an RGB color's from its
|
||||
/// A color that names no swatch: `g` (gray), `k` (CMYK), else `c m y k r g b Xa` (RGB, and Lab
|
||||
/// as RGB, in the working RGB space), with its CMYK equivalent (an RGB color's from its
|
||||
/// values as written, a Lab color's from its Lab values).
|
||||
fn plain_color(&mut self, color: Color, stroke: bool) {
|
||||
let s = &mut self.body;
|
||||
|
||||
@@ -0,0 +1,372 @@
|
||||
//! Blends: a live blend as the `.ai` reader reads one ([`crate::import`]'s `.ai` reader, `blend.rs`
|
||||
//! and `read/containers.rs`' `end_blend`).
|
||||
//!
|
||||
//! The blend's own art on `%_` lines: `0 Ae`, a group of its key objects, each with an
|
||||
//! `/ArtDictionary` naming it a key (`ShapeBlendPathType` `K`) and its id (`ShapeBlendPathID`, a
|
||||
//! letter or digit), and its spine as an unpainted path named the spine (`S`), written only when the
|
||||
//! blend has a spine of its own; then its steps drawn, a group on plain lines; then `0 Ae`,
|
||||
//! the `XP` line of the blend plugin ([`BLEND_PLUGIN`], `1 0 n XP`) and the blend's record, `n` bytes
|
||||
//! as hex on `%` lines; then the blend's name in an `/ArtDictionary` and its transparency, as a
|
||||
//! group's after its end. The record
|
||||
//! is `DCBA` and little-endian 32-bit words: 1, the spacing (0 Smooth Color, 1 Specified Steps, 2
|
||||
//! Specified Distance); 2, the distance as a float (Specified Steps: the spine's length shared out
|
||||
//! between the steps; Smooth Color: 4); 4, the steps between the first two keys; 5, the orientation
|
||||
//! (0 Align to Page, a float of 8 and the spine's starting angle in radians for Align to Path); 6,
|
||||
//! the next free id (0 after the 62nd); 9, 1; 10, the number of keys; then six words a key: its id,
|
||||
//! 0, the anchor of the spine it sits on as a float, two words of all ones, and the steps between
|
||||
//! it and the key before it. The reader reads words 1, 2 (for Specified Distance), 5 (0, or 8 or
|
||||
//! more), 10 and the keys' ids; the others are written as the record's form has them.
|
||||
//!
|
||||
//! Each blend is checked with the reader's own reading ([`crate::import::blend_reads`]) before it is
|
||||
//! written: one the reader would read with other settings is written as its steps.
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::fmt::Write;
|
||||
use std::sync::Arc;
|
||||
|
||||
use vectorcraft_color::{BlendMode, Color, Paint};
|
||||
use vectorcraft_doc::blend::{blend_spine, blend_steps, blend_steps_settled, pin_spine};
|
||||
use vectorcraft_doc::live::{BlendOrientation, BlendSpacing, BlendSpec};
|
||||
use vectorcraft_doc::{AppearanceItem, Document, Node, NodeId, NodeKind, StrokeLayer};
|
||||
use vectorcraft_geom::{FillRule, PathData};
|
||||
|
||||
use super::{MAX_NEST, Writer, Xy, hide};
|
||||
use crate::import::{BLEND_PLUGIN, MAX_BLEND_KEYS, MAX_BLEND_OBJECTS, blend_reads};
|
||||
|
||||
pub(in crate::ai_editing) const BLENDS: &str = "blends with easing, a color shift or start points of their own, blends with effects, an appearance or an opacity mask of their own, blends of objects other than paths, compound paths and groups, of clipping groups, of more than 62 key objects, of hidden key objects, of key objects that hold a blend, of key objects with geometry or Pathfinder effects or a group's own fills and strokes, or of key objects the editing copy would change (empty paths or subpaths, paths and compound path members of several subpaths, several fills or strokes, strokes a plain line can't draw, dashes of more than 64 lengths, hidden fills or strokes, fills or strokes other than a color, in a Lab color or with transparency or effects of their own, effects or opacity masks), blends where one key object has a fill or stroke of no paint or a stroke of no width and another has one that draws, blends inside objects with geometry or Pathfinder effects or a group's own fills and strokes, blends whose spine has more than one part, blends whose step count is close to where rounding changes it, blends that would open with other settings or not as they are drawn, blends in opacity masks, pattern tiles, symbols and art cut to a clipping object or nested eight levels deep in art written in place of other objects (symbol instances, live objects, brushed strokes), blends whose art would pass the most objects the reader reads, and every blend on a large canvas are written as their steps in the editing data for other apps";
|
||||
|
||||
/// How far (pt) the lengths a blend counts its steps from may move when written (coordinates are
|
||||
/// written to 4 decimals and read back through art space) without changing a count.
|
||||
const SETTLE_LENGTH: f64 = 0.01;
|
||||
/// How far (pt) each segment of a spine may add to [`SETTLE_LENGTH`]: rounding moves each of its
|
||||
/// points by up to 0.00005 √2 pt, which moves the segment's length by up to six times that.
|
||||
const SETTLE_SEGMENT: f64 = 5e-4;
|
||||
/// How far a key's color (each channel, 0 to 1) may move when written without changing a Smooth
|
||||
/// Color count.
|
||||
const SETTLE_COLOR: f64 = 0.001;
|
||||
|
||||
/// The most dash lengths the reader reads; a stroke with more opens solid.
|
||||
const MAX_DASH_LENGTHS: usize = 64;
|
||||
|
||||
/// The ids the keys take, in their order (letters and digits, as the reader reads them).
|
||||
const IDS: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
|
||||
|
||||
/// Hex digits on one `%` line of a record.
|
||||
const HEX_LINE: usize = 60;
|
||||
|
||||
/// A blend to write live.
|
||||
pub(super) struct LiveBlend {
|
||||
keys: Vec<Arc<Node>>,
|
||||
ids: Vec<String>,
|
||||
/// Its spine part; `None`: the blend has no spine of its own.
|
||||
spine: Option<PathData>,
|
||||
record: Vec<u8>,
|
||||
steps: Vec<Arc<Node>>,
|
||||
}
|
||||
|
||||
impl Writer<'_> {
|
||||
/// Blend `n` as the reader reads it live, or `None` when it would read other settings or none
|
||||
/// (the blend is then written as its steps).
|
||||
pub(super) fn live_blend(&mut self, n: &Node) -> Option<LiveBlend> {
|
||||
let NodeKind::Blend { children: keys, spec } = &n.kind else { return None };
|
||||
// Hidden lines (pattern tiles, opacity masks), symbols' definitions and art cut to a
|
||||
// clipping object aren't read as live blends. (No blend is drawn in a look: styled objects
|
||||
// hold only paths, compound paths and groups of them.)
|
||||
if !self.blends_live || self.hidden > 0 || self.in_symbol || self.clip.is_some() || self.nest >= MAX_NEST {
|
||||
return None;
|
||||
}
|
||||
// Baking changes its keys, or the art it sits in ([`unbaked_blends`]).
|
||||
if !self.unbaked_blends.contains(&n.id) {
|
||||
return None;
|
||||
}
|
||||
if !spec.ease.is_default() || spec.color_shift != 0.0 || !spec.starts.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let own = &n.appearance;
|
||||
if !own.items.is_empty() || !own.effects.is_empty() || n.extras().mask.is_some() {
|
||||
return None;
|
||||
}
|
||||
// The reader shows every key object it reads.
|
||||
if keys.len() < 2 || keys.len() > IDS.len().min(MAX_BLEND_KEYS) || !keys.iter().all(|k| k.visible && plain_key(k)) {
|
||||
return None;
|
||||
}
|
||||
// A fill or stroke the editing copy leaves out is read back as none at all, and the steps
|
||||
// blend from it to another key's otherwise.
|
||||
if left_out_against_drawn(keys) {
|
||||
return None;
|
||||
}
|
||||
// The spine written: a replaced spine (no key anchors) with an anchor where each key sits, a
|
||||
// spine edited on the canvas with its keys' anchors moved onto them.
|
||||
let spec: &BlendSpec = spec;
|
||||
// The blend lays out along the spine's first subpath, and only that part is written: a
|
||||
// spine of more parts would open without the others.
|
||||
if spec.spine.as_ref().is_some_and(|s| s.subpaths.len() > 1) {
|
||||
return None;
|
||||
}
|
||||
let written = match &spec.spine {
|
||||
None => BlendSpec { key_anchors: vec![], ..spec.clone() },
|
||||
Some(_) if spec.key_anchors.is_empty() => {
|
||||
let (path, anchors) = pin_spine(keys, spec)?;
|
||||
let anchors = anchors.into_iter().map(u32::try_from).collect::<Result<Vec<u32>, _>>().ok()?;
|
||||
BlendSpec { spine: Some(path), key_anchors: anchors, ..spec.clone() }
|
||||
}
|
||||
Some(_) => BlendSpec { spine: Some(blend_spine(keys, spec)?.0), ..spec.clone() },
|
||||
};
|
||||
// The record holds Specified Distance as a 32-bit float, which the reader reads back as its
|
||||
// shortest decimal (10 mm comes back as 28.346457 pt): the blend is compared with that
|
||||
// distance, and kept live only when it lays out as many steps with it.
|
||||
let written = match written.spacing {
|
||||
BlendSpacing::Distance(d) => {
|
||||
let read: f64 = (d as f32).to_string().parse().ok().filter(|r: &f64| r.is_finite() && *r > 0.0)?;
|
||||
let stored = BlendSpec { spacing: BlendSpacing::Distance(read), ..written.clone() };
|
||||
if blend_steps(keys, &stored) != blend_steps(keys, &written) {
|
||||
return None;
|
||||
}
|
||||
stored
|
||||
}
|
||||
_ => written,
|
||||
};
|
||||
// As many objects as the reader lays out for one blend, twice within what its budget has left,
|
||||
// counted before the steps are drawn.
|
||||
let objects = blend_steps(keys, &written).into_iter().fold(keys.len(), usize::saturating_add);
|
||||
if objects > MAX_BLEND_OBJECTS || objects.saturating_mul(2) > self.blend_budget {
|
||||
return None;
|
||||
}
|
||||
// The reader counts the steps from the keys as written, rounded: a count that rounding can
|
||||
// change may come back other than drawn. Specified Distance counts from the spine's length,
|
||||
// and every segment of the spine adds to how far that may move.
|
||||
let segments = written.spine.as_ref().and_then(|s| s.subpaths.first()).map_or(0, |s| s.segment_count());
|
||||
let settle = match written.spacing {
|
||||
BlendSpacing::Distance(_) => SETTLE_LENGTH + segments as f64 * SETTLE_SEGMENT,
|
||||
_ => SETTLE_LENGTH,
|
||||
};
|
||||
if !blend_steps_settled(keys, &written, settle, SETTLE_COLOR) {
|
||||
return None;
|
||||
}
|
||||
let ids: Vec<String> = IDS.iter().take(keys.len()).map(|c| char::from(*c).to_string()).collect();
|
||||
let record = self.record(keys, &written)?;
|
||||
let steps: Vec<Arc<Node>> = vectorcraft_effects::expand_live_deep(Some(self.doc), n).children().cloned().unwrap_or_default();
|
||||
let drawn: Vec<Node> = steps.iter().map(|s| (**s).clone()).collect();
|
||||
// The spine part as written: the first subpath of the spine laid out.
|
||||
let part = written.spine.as_ref().and_then(|s| s.subpaths.first()).map(|sp| PathData::single(sp.clone()));
|
||||
let mut budget = self.blend_budget;
|
||||
let read = blend_reads(keys, &ids, part.as_ref(), &record, &drawn, &mut budget)?;
|
||||
if read != written {
|
||||
return None;
|
||||
}
|
||||
self.blend_budget = budget;
|
||||
Some(LiveBlend { keys: keys.clone(), ids, spine: part, record, steps })
|
||||
}
|
||||
|
||||
/// The record of a blend of `keys` with the settings `spec` (its spine as written).
|
||||
fn record(&self, keys: &[Arc<Node>], spec: &BlendSpec) -> Option<Vec<u8>> {
|
||||
let (spine, anchors) = blend_spine(keys, spec)?;
|
||||
let steps = blend_steps(keys, spec);
|
||||
let first = u32::try_from(*steps.first()?).ok()?;
|
||||
let (spacing, value) = match spec.spacing {
|
||||
BlendSpacing::SmoothColor => (0, 4.0),
|
||||
BlendSpacing::Steps(n) => (1, spine.length() / (f64::from(n) + 1.0)),
|
||||
BlendSpacing::Distance(d) => (2, d),
|
||||
};
|
||||
let orientation = match spec.orientation {
|
||||
BlendOrientation::AlignToPage => 0.0,
|
||||
BlendOrientation::AlignToPath => 8.0 + self.starting_angle(&spine)?,
|
||||
};
|
||||
let count = u32::try_from(keys.len()).ok()?;
|
||||
let next = IDS.get(keys.len()).copied().map_or(0, u32::from);
|
||||
let mut words: Vec<u32> = vec![u32::from_le_bytes(*b"DCBA"), spacing, (value as f32).to_bits(), 0, first, (orientation as f32).to_bits()];
|
||||
words.extend([next, 0, 0, 1, count]);
|
||||
for (i, id) in IDS.iter().take(keys.len()).enumerate() {
|
||||
let anchor = anchors.as_ref().and_then(|a| a.get(i)).copied().unwrap_or(i);
|
||||
let before = i.checked_sub(1).and_then(|j| steps.get(j)).copied().unwrap_or(0);
|
||||
words.extend([u32::from(*id), 0, (anchor as f32).to_bits(), u32::MAX, u32::MAX, u32::try_from(before).ok()?]);
|
||||
}
|
||||
Some(words.iter().flat_map(|w| w.to_le_bytes()).collect())
|
||||
}
|
||||
|
||||
/// The angle in art space (radians, from 0 to 2π) at which `spine` starts.
|
||||
fn starting_angle(&self, spine: &PathData) -> Option<f64> {
|
||||
let sp = spine.subpaths.first()?;
|
||||
let first = sp.anchors.first()?;
|
||||
let towards = if (first.h_out - first.p).hypot() > 1e-9 { first.h_out } else { sp.anchors.get(1)?.p };
|
||||
let (a, b) = (self.to_art * first.p, self.to_art * towards);
|
||||
let angle = (b.y - a.y).atan2(b.x - a.x);
|
||||
Some(if angle < 0.0 { angle + std::f64::consts::TAU } else { angle })
|
||||
}
|
||||
|
||||
/// Blend `n`, of transparency `xy`, written live ([`Self::live_blend`]): its own art on `%_`
|
||||
/// lines, its steps and its record, then the state block of its transparency, before which the
|
||||
/// object's dictionary (its name, text wrap options and variables) goes. False, writing
|
||||
/// nothing, when it is written as its steps: the reader would read it otherwise, or art in it
|
||||
/// would be left out at the object limit ([`Self::take_objects`]).
|
||||
pub(super) fn blend(&mut self, n: &Node, xy: Xy) -> bool {
|
||||
let budget = self.blend_budget;
|
||||
let Some(b) = self.live_blend(n) else { return false };
|
||||
let start = self.body.len();
|
||||
let (state, gs, charges, bound, warnings) = (self.state, self.gs, self.charges(), self.bound.len(), self.warnings.len());
|
||||
let outer = std::mem::take(&mut self.body);
|
||||
self.hidden += 1;
|
||||
self.line("0 Ae");
|
||||
let opened = self.open_group("u");
|
||||
if opened {
|
||||
for (k, id) in b.keys.iter().zip(&b.ids) {
|
||||
self.blend_role = Some((k.id, format!("%_(K) /String (ShapeBlendPathType) ,\n%_({id}) /String (ShapeBlendPathID) ,\n")));
|
||||
self.node(k);
|
||||
self.blend_role = None;
|
||||
}
|
||||
if let Some(spine) = &b.spine {
|
||||
self.plain_object(spine, FillRule::NonZero, None, None, Xy::OPAQUE);
|
||||
self.body.push_str("%_/ArtDictionary :\n%_(S) /String (ShapeBlendPathType) ,\n%_;\n%_\n");
|
||||
}
|
||||
self.line("U");
|
||||
self.line("9 () XW");
|
||||
}
|
||||
self.hidden -= 1;
|
||||
let part = std::mem::replace(&mut self.body, outer);
|
||||
hide(&part, &mut self.body);
|
||||
// Readers of the printed form skip the hidden lines: the steps set their own state.
|
||||
(self.state, self.gs) = (None, None);
|
||||
self.state(n.locked, !n.visible);
|
||||
let steps = self.open_group("u");
|
||||
if steps {
|
||||
// The steps are drawn art: copies of the keys carry no text wrap options of their own.
|
||||
self.nest += 1;
|
||||
self.drawn += 1;
|
||||
for s in &b.steps {
|
||||
self.node(s);
|
||||
}
|
||||
self.drawn -= 1;
|
||||
self.nest -= 1;
|
||||
self.state(n.locked, !n.visible);
|
||||
self.line("U");
|
||||
self.line("9 () XW");
|
||||
}
|
||||
if !opened || !steps || self.left_out_since(charges) {
|
||||
let lines = self.body.split_off(start);
|
||||
self.give_back(charges, &lines);
|
||||
self.bound.truncate(bound);
|
||||
// The warnings of art written as its steps again are those steps'.
|
||||
if !self.left_out_since(charges) {
|
||||
self.warnings.truncate(warnings);
|
||||
}
|
||||
(self.state, self.gs, self.block_end, self.blend_budget) = (state, gs, usize::MAX, budget);
|
||||
return false;
|
||||
}
|
||||
self.line("0 Ae");
|
||||
let hex: String = b.record.iter().map(|x| format!("{x:02X}")).collect();
|
||||
let _ = writeln!(self.body, "({BLEND_PLUGIN}) 1 0 {} XP", b.record.len());
|
||||
for chunk in hex.as_bytes().chunks(HEX_LINE) {
|
||||
self.body.push('%');
|
||||
self.body.push_str(&String::from_utf8_lossy(chunk));
|
||||
self.body.push('\n');
|
||||
}
|
||||
// The blend's dictionary goes after the record and before this block ([`Self::node`]).
|
||||
self.state_block(xy);
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
/// The blends on `doc`'s layers that baking leaves as they are: blends with nothing in them that
|
||||
/// [`vectorcraft_effects::needs_bake`] evaluates (geometry and Pathfinder effects, a group's own
|
||||
/// fills and strokes), inside no object that has such things of its own. Baking changes the keys
|
||||
/// of the others, so they are written as their steps.
|
||||
pub(in crate::ai_editing) fn unbaked_blends(doc: &Document) -> HashSet<NodeId> {
|
||||
fn walk(nodes: &[Arc<Node>], out: &mut HashSet<NodeId>) {
|
||||
for n in nodes {
|
||||
if matches!(n.kind, NodeKind::Blend { .. }) {
|
||||
if !vectorcraft_effects::needs_bake(n) {
|
||||
out.insert(n.id);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let Some(children) = n.children() else { continue };
|
||||
let mut own = (**n).clone();
|
||||
if let Some(c) = own.children_mut() {
|
||||
c.clear();
|
||||
}
|
||||
if !vectorcraft_effects::needs_bake(&own) {
|
||||
walk(children, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut out = HashSet::new();
|
||||
walk(&doc.layers, &mut out);
|
||||
out
|
||||
}
|
||||
|
||||
/// Does the reader read stroke `s`'s dashes back as they are (`read/ops.rs`' `d`): at most 64
|
||||
/// lengths, each finite and not negative, and a finite offset? It reads other dashes as a solid
|
||||
/// line.
|
||||
fn dash_read_back(s: &StrokeLayer) -> bool {
|
||||
s.dash
|
||||
.as_ref()
|
||||
.is_none_or(|d| d.pattern.len() <= MAX_DASH_LENGTHS && d.pattern.iter().all(|v| v.is_finite() && *v >= 0.0) && d.offset.is_finite())
|
||||
}
|
||||
|
||||
/// Do the keys hold a fill or stroke that the editing copy leaves out (a fill of no paint; a stroke
|
||||
/// of no paint or of no width, as `visible_items` leaves them out) where another holds one of the
|
||||
/// same kind that it writes? The steps blend the width, paint and settings of the one left out, and
|
||||
/// the keys read back blend from no fill or stroke, so the steps would open otherwise.
|
||||
fn left_out_against_drawn(keys: &[Arc<Node>]) -> bool {
|
||||
// [fill, stroke]: is one left out somewhere, is one written somewhere.
|
||||
let mut left_out = [false; 2];
|
||||
let mut drawn = [false; 2];
|
||||
for k in keys {
|
||||
k.walk(&mut |n| {
|
||||
for i in &n.appearance.items {
|
||||
let (kind, out) = match i {
|
||||
AppearanceItem::Fill(f) => (0, f.paint.is_none()),
|
||||
AppearanceItem::Stroke(s) => (1, s.paint.is_none() || !(s.width > 0.0 && s.width.is_finite())),
|
||||
};
|
||||
if out {
|
||||
left_out[kind] = true;
|
||||
} else {
|
||||
drawn[kind] = true;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
(left_out[0] && drawn[0]) || (left_out[1] && drawn[1])
|
||||
}
|
||||
|
||||
/// Can `k` be a key object written live, as the reader reads it back: paths, compound paths and
|
||||
/// groups other than clipping groups (holding no blend), without effects or opacity masks, each with
|
||||
/// at most one fill and one plain stroke over it (a line the data draws as it is), each fill and
|
||||
/// stroke shown, in a color other than Lab or none, opaque in the normal blending mode? (A group's own fills and
|
||||
/// strokes are baked into art of their own, and such blends aren't [`unbaked_blends`].)
|
||||
fn plain_key(k: &Node) -> bool {
|
||||
let mut plain = true;
|
||||
k.walk(&mut |n| {
|
||||
// A clipping group may be written as its art cut to the clipping object.
|
||||
let kind = match &n.kind {
|
||||
// The writer leaves out a path with nothing to draw and subpaths without anchors, and
|
||||
// writes a path of several subpaths as a compound path.
|
||||
NodeKind::Path { path, guide: false, .. } => matches!(path.subpaths.as_slice(), [one] if !one.anchors.is_empty()),
|
||||
// A compound path is written as one path, and read back with a member for each
|
||||
// subpath.
|
||||
NodeKind::Compound { children, .. } => {
|
||||
!children.is_empty()
|
||||
&& children.iter().all(|c| matches!(&c.kind, NodeKind::Path { path, guide: false, .. } if path.subpaths.len() == 1))
|
||||
}
|
||||
NodeKind::Group { clip: false, .. } => true,
|
||||
_ => false,
|
||||
};
|
||||
let items = &n.appearance.items;
|
||||
let fills = items.iter().filter(|i| matches!(i, AppearanceItem::Fill(_))).count();
|
||||
let strokes = items.iter().filter(|i| matches!(i, AppearanceItem::Stroke(_))).count();
|
||||
let order = !matches!(items.as_slice(), [AppearanceItem::Stroke(_), AppearanceItem::Fill(_)]);
|
||||
let quiet = items.iter().all(|i| {
|
||||
i.visible()
|
||||
&& matches!(i.paint(), Paint::Solid { .. } | Paint::None)
|
||||
// A color that names no global or spot swatch is written in RGB, so a Lab color
|
||||
// would come back as another.
|
||||
&& !matches!(i.paint(), Paint::Solid { color: Color::Lab { .. }, .. })
|
||||
&& i.effects().is_empty()
|
||||
&& i.opacity() >= 1.0
|
||||
&& i.blend() == BlendMode::Normal
|
||||
&& !matches!(i, AppearanceItem::Stroke(s) if !vectorcraft_effects::stroke::is_plain(s) || !dash_read_back(s))
|
||||
});
|
||||
plain &= kind && fills <= 1 && strokes <= 1 && order && quiet && n.appearance.effects.is_empty() && n.extras().mask.is_none();
|
||||
});
|
||||
plain
|
||||
}
|
||||
@@ -23,7 +23,7 @@ use super::{Writer, Xy};
|
||||
use crate::ai_ops;
|
||||
use crate::ps;
|
||||
|
||||
pub(in crate::ai_editing) const BRUSHES: &str = "Pattern and Bristle brushes, Art brushes that don't run their art from left to right, that overlap or whose width follows the pen, Scatter and Art brushes in Tints and Shades or Hue Shift, brushes whose art holds an empty path or group or more than paths, compound paths and groups with one solid fill and one plain stroke each, brushes whose names hold a slash or repeat an earlier brush's name, brushes that would open with other settings, brushes past the number or the amount of art one file's brushes can hold, and every brush on a large canvas are left out of the Brushes panel in the editing data for other apps";
|
||||
pub(in crate::ai_editing) const BRUSHES: &str = "Pattern and Bristle brushes, Art brushes that don't run their art from left to right, that overlap or whose width follows the pen, Scatter and Art brushes in Tints and Shades or Hue Shift, brushes whose art or its opacity masks' art holds an empty path or group or more than paths, compound paths and groups with one solid fill and one plain stroke each, or opacity masks on a compound path's members or more than seven deep in one another's art, brushes whose names hold a slash or repeat an earlier brush's name, brushes that would open with other settings, brushes past the number or the amount of art one file's brushes can hold, and every brush on a large canvas are left out of the Brushes panel in the editing data for other apps";
|
||||
|
||||
/// Most brushes written (the reader's limit).
|
||||
const MAX_BRUSHES: usize = 4096;
|
||||
@@ -213,17 +213,38 @@ fn art_params(a: &ArtBrush, art: &str) -> Option<String> {
|
||||
Some(format!("2 / {art}/ / / / / 0 0/ 5 0 0 0 / {}", nums6(&numbers)))
|
||||
}
|
||||
|
||||
/// Most opacity masks in one another's art in a brush's art: a brush's art section writes its art
|
||||
/// one level inside, and masks at [`super::MAX_NEST`] levels are left out ([`super::DEEP_MASKS`]).
|
||||
const MAX_MASK_NEST: u32 = super::MAX_NEST - 1;
|
||||
|
||||
/// Is `art` written as the reader reads it back, within a brush: paths and compound paths with
|
||||
/// points and groups with members (not clipping, without paint of their own), each opaque in the
|
||||
/// normal blending mode, without effects or opacity masks, with at most one fill and one plain
|
||||
/// stroke (no brush, width profile, arrowheads, alignment off the path or dashes fitted to corners)
|
||||
/// over it, each in a color or none? A path without points isn't written ([`Writer::plain_object`]).
|
||||
/// normal blending mode, without effects, with at most one fill and one plain stroke (no brush,
|
||||
/// width profile, arrowheads, alignment off the path or dashes fitted to corners) over it, each in a
|
||||
/// color or none, and opacity masks whose art is such art too, at most [`MAX_MASK_NEST`] deep and
|
||||
/// none on a compound path's members? A path without points isn't written
|
||||
/// ([`Writer::plain_object`]).
|
||||
fn plain_art(art: &Node) -> bool {
|
||||
plain_within(art, MAX_MASK_NEST)
|
||||
}
|
||||
|
||||
/// Does no object of `art` have an opacity mask?
|
||||
fn unmasked(art: &Node) -> bool {
|
||||
let mut unmasked = true;
|
||||
art.walk(&mut |n| unmasked &= n.extras().mask.is_none());
|
||||
unmasked
|
||||
}
|
||||
|
||||
/// [`plain_art`] with at most `masks` opacity masks in one another's art.
|
||||
fn plain_within(art: &Node, masks: u32) -> bool {
|
||||
let mut plain = true;
|
||||
art.walk(&mut |n| {
|
||||
let kind = match &n.kind {
|
||||
NodeKind::Path { path, guide: false, clipping: false, .. } => path.subpaths.iter().any(|sp| !sp.anchors.is_empty()),
|
||||
NodeKind::Compound { .. } => super::compound_path(n).subpaths.iter().any(|sp| !sp.anchors.is_empty()),
|
||||
// A compound path is written as one path of its members' subpaths, without their masks.
|
||||
NodeKind::Compound { children, .. } => {
|
||||
children.iter().all(|c| unmasked(c)) && super::compound_path(n).subpaths.iter().any(|sp| !sp.anchors.is_empty())
|
||||
}
|
||||
NodeKind::Group { children, clip: false } => !children.is_empty(),
|
||||
_ => false,
|
||||
};
|
||||
@@ -247,7 +268,7 @@ fn plain_art(art: &Node) -> bool {
|
||||
&& order
|
||||
&& quiet
|
||||
&& n.appearance.effects.is_empty()
|
||||
&& n.extras().mask.is_none()
|
||||
&& n.extras().mask.as_deref().is_none_or(|m| masks > 0 && plain_within(&m.art, masks - 1))
|
||||
&& n.opacity >= 1.0
|
||||
&& n.blend == BlendMode::Normal;
|
||||
});
|
||||
@@ -258,8 +279,13 @@ fn plain_art(art: &Node) -> bool {
|
||||
/// compound path with the subpaths of all its members as one path ([`super::compound_path`]), is
|
||||
/// written as one path when it has one subpath with points and as a compound path when it has more
|
||||
/// ([`Writer::plain_object`]); the reader reads that compound path as one path for each subpath,
|
||||
/// each with the object's paint.
|
||||
/// each with the object's paint. An opacity mask's art is written shown ([`Writer::mask`]).
|
||||
fn as_read(art: &mut Node) {
|
||||
if let Some(m) = art.extras_if_any().and_then(|e| e.mask.as_mut()) {
|
||||
let mask_art = Arc::make_mut(&mut m.art);
|
||||
mask_art.visible = true;
|
||||
as_read(mask_art);
|
||||
}
|
||||
let (subpaths, rule) = match &art.kind {
|
||||
NodeKind::Path { path, rule, .. } => (path.subpaths.clone(), *rule),
|
||||
NodeKind::Compound { rule, .. } => (super::compound_path(art).subpaths, *rule),
|
||||
@@ -390,7 +416,7 @@ impl Writer<'_> {
|
||||
}
|
||||
let mut read = a.clone();
|
||||
if *to_section == Affine::IDENTITY {
|
||||
read.transform(Affine::FLIP_Y, false);
|
||||
crate::import::turn_brush_art_over(&mut read);
|
||||
}
|
||||
as_read(&mut read);
|
||||
Some(read)
|
||||
@@ -427,6 +453,9 @@ impl Writer<'_> {
|
||||
// The art is the brush's own: not on `%_` lines, in a drawn look or in a symbol that
|
||||
// first uses the brush.
|
||||
(std::mem::take(&mut self.hidden), std::mem::take(&mut self.in_look), std::mem::take(&mut self.in_symbol)),
|
||||
// The layers' objects written with art styles, by id: none of them is the brush's art,
|
||||
// which may hold objects with the same ids.
|
||||
std::mem::take(&mut self.styled),
|
||||
);
|
||||
(self.to_art, self.grad_space, self.canvas, self.block_end) = (to_section, to_section, to_section, usize::MAX);
|
||||
self.state(false, false);
|
||||
@@ -462,6 +491,7 @@ impl Writer<'_> {
|
||||
(self.clip, self.shown),
|
||||
(self.block_start, self.block_end),
|
||||
(self.hidden, self.in_look, self.in_symbol),
|
||||
self.styled,
|
||||
) = saved;
|
||||
let text = std::mem::replace(&mut self.body, body);
|
||||
if !std::mem::replace(&mut self.warnings, warnings).is_empty() {
|
||||
|
||||
@@ -5,7 +5,8 @@
|
||||
//! Contents (`AIDeformEditModeKey`), a warp's style, bend, distortions and orientation
|
||||
//! (`DeformStyle`, `DeformValue`, `DeformHoriz`, `DeformVert`, `Rotate`), with Distort Appearance
|
||||
//! the size of the box the contents map from (`AIDeformArtWidthKey`, `AIDeformArtHeightKey`), the
|
||||
//! contents in an `X=` … `X+` block (while they are edited, the grid) as `AIDeformArtKey`, and the
|
||||
//! contents in an `X=` … `X+` block (in a symbol's art, in the canvas's space with y down; while
|
||||
//! they are edited, the grid) as `AIDeformArtKey`, and the
|
||||
//! kind (`AIDeformStyle`: 1 a warp, 2 a mesh, 3 a top object); then the distorted art on plain
|
||||
//! lines, and the plugin's `XP` after it. A top object's outline is the edge of the grid written
|
||||
//! for it, one grid edge to each segment of its sides, a side with fewer segments than the side
|
||||
@@ -401,7 +402,13 @@ impl Writer<'_> {
|
||||
if *editing {
|
||||
self.grid(record.grid.as_ref());
|
||||
} else if self.open_group("u") {
|
||||
// In a symbol's art, the contents in the dictionary are in the canvas's space, y down.
|
||||
let to_art = self.to_art;
|
||||
if self.in_symbol {
|
||||
self.to_art = Affine::translate(self.canvas_origin) * to_art;
|
||||
}
|
||||
self.contents(content, true);
|
||||
self.to_art = to_art;
|
||||
self.end_group("U", Xy::PLAIN);
|
||||
}
|
||||
let block = std::mem::replace(&mut self.body, outer);
|
||||
@@ -448,15 +455,17 @@ impl Writer<'_> {
|
||||
/// An envelope's grid, when it has one, as a gray gradient mesh (`/Mesh X!` … `/End X!`): its
|
||||
/// size (`[cols rows] /Size`), then each patch's place (`[col row] /P`), its four corners
|
||||
/// (`/N`: gray, opacity, the point, the handle towards the next corner and a weight, the handle
|
||||
/// towards the previous one and a weight, in art space), from its top left one down, across and
|
||||
/// up, and `/E`. One object.
|
||||
/// towards the previous one and a weight, in art space; in a symbol's art, in the space a
|
||||
/// gradient mesh's corners are written in there), from its top left one down, across and up,
|
||||
/// and `/E`. One object.
|
||||
fn grid(&mut self, grid: Option<&(usize, usize, Vec<GridPoint>)>) {
|
||||
let Some((rows, cols, pts)) = grid else { return };
|
||||
if !self.take_objects(1) {
|
||||
return;
|
||||
}
|
||||
let (rows, cols, width) = (*rows, *cols, cols + 1);
|
||||
let to_art = self.to_art;
|
||||
// In a symbol's art, corners are written in the space a gradient mesh's are written in there.
|
||||
let to_art = if self.in_symbol { self.instance_space } else { self.to_art };
|
||||
let s = &mut self.body;
|
||||
let _ = writeln!(s, "/Mesh X!\n2 /Version X#\n/Cartesian /Type X#\n[{cols} {rows}] /Size X#\n/Data X#\n/DeviceGray /CS X#");
|
||||
let num = |s: &mut String, v: f64| {
|
||||
|
||||
@@ -0,0 +1,256 @@
|
||||
//! Gradient meshes: a mesh as the `.ai` reader reads one ([`crate::import`]'s `.ai` reader,
|
||||
//! `mesh.rs` and `read/art.rs`' `end_mesh`).
|
||||
//!
|
||||
//! `/Mesh X!`, then on `%_` lines `value /key X#` entries: `2 /Version` (corners with an opacity),
|
||||
//! `/Cartesian /Type`, `[rows cols] /Size`, `/Data` (the patches follow), and for each patch, row by
|
||||
//! row, its place `[row col] /P`, the color space (`/DeviceGray`,
|
||||
//! `/DeviceRGB` or `/DeviceCMYK`) with `/CS` where it changes, its four corners with `/N` and `/E`;
|
||||
//! then `/End X!`. A corner is `[color… opacity x y nx ny 1 px py 1]` in art space (in a symbol's
|
||||
//! art, in the canvas's space turned y up about art space's origin there, as an image's matrix in
|
||||
//! it is): its color (gray as lightness), its opacity, the point, the
|
||||
//! handle towards the next corner and the handle towards the one before it, each with a weight of 1.
|
||||
//! The corners go from the patch's top left mesh point to the one below it, then to the right, then
|
||||
//! up: the first index of `/P` runs along the first edge. The mesh's transparency is set before it
|
||||
//! (`0 XR`, `Xy`), its name and opacity mask follow `/End X!` in an `/ArtDictionary`, then `0 0 Xd`
|
||||
//! and `6 () XW`.
|
||||
//!
|
||||
//! Each record is read back with the reader's mesh reading ([`crate::import::mesh_reads`], the
|
||||
//! patches and how they join; not the rest of the `.ai` reader) before it is written: a mesh it
|
||||
//! would read otherwise is written as its drawn look, as are folded meshes (patches whose corners
|
||||
//! turn different ways, along the handles there, or a corner with no angle), meshes in pattern
|
||||
//! tiles and in art cut to a clipping object, and every mesh on a large canvas. A reflected mesh,
|
||||
//! whose patches all turn the negative way, is written with its columns in reverse order: it draws
|
||||
//! the same patches, and reads back with each row's points in reverse order.
|
||||
|
||||
use std::fmt::Write;
|
||||
|
||||
use vectorcraft_color::Color;
|
||||
use vectorcraft_doc::live::{GradientMesh, H_DOWN, H_LEFT, H_RIGHT, H_UP, MeshPoint};
|
||||
use vectorcraft_geom::{Affine, Point, Vec2};
|
||||
|
||||
use super::{Writer, Xy};
|
||||
use crate::ai_ops::unit;
|
||||
use crate::import::{MAX_MESH_SIDE, mesh_reads};
|
||||
use crate::ps;
|
||||
|
||||
pub(in crate::ai_editing) const MESHES: &str = "gradient meshes with a point in a Lab color, with more than 128 rows or columns, folded meshes, meshes that would not open as they are drawn, meshes in pattern tiles and in art cut to a clipping object, and every gradient mesh on a large canvas are written as their drawn look in the editing data for other apps";
|
||||
|
||||
/// How far (in the document's units, at a scale of 1) a written point or handle's end may move:
|
||||
/// coordinates are written to 4 decimals, which moves a point at most 0.00005 along each axis.
|
||||
const SETTLE_POINT: f64 = 1e-4;
|
||||
/// How far a written color channel or opacity may move: they are written to 4 decimals too.
|
||||
const SETTLE_COLOR: f32 = 1e-4;
|
||||
|
||||
/// The color space a corner's color is written in.
|
||||
#[derive(Clone, Copy, PartialEq)]
|
||||
enum Space {
|
||||
Gray,
|
||||
Rgb,
|
||||
Cmyk,
|
||||
}
|
||||
|
||||
impl Space {
|
||||
fn name(self) -> &'static str {
|
||||
match self {
|
||||
Space::Gray => "/DeviceGray",
|
||||
Space::Rgb => "/DeviceRGB",
|
||||
Space::Cmyk => "/DeviceCMYK",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Writer<'_> {
|
||||
/// Mesh `m`'s record as the reader reads it, or `None` when it would read it otherwise (the
|
||||
/// mesh is then written as its drawn look).
|
||||
pub(super) fn mesh_record(&self, m: &GradientMesh) -> Option<String> {
|
||||
// Art cut to a clipping object is written cut, which a mesh can't be. Meshes in pattern
|
||||
// tiles and on a large canvas are written as their drawn look too. (A mesh holds no objects,
|
||||
// so it is written as a mesh however deep it is nested.) A grid the reader doesn't read as
|
||||
// one mesh is left before its record is built.
|
||||
if !self.meshes_live
|
||||
|| self.clip.is_some()
|
||||
|| !self.defining.is_empty()
|
||||
|| !m.is_valid()
|
||||
|| m.rows as usize > MAX_MESH_SIDE
|
||||
|| m.cols as usize > MAX_MESH_SIDE
|
||||
{
|
||||
return None;
|
||||
}
|
||||
// In a symbol's art, corners are written in the space an image's matrix is written in there.
|
||||
let to_art = if self.in_symbol { self.instance_space } else { self.to_art };
|
||||
// Every patch turns the positive way where it is written: from its first corner, the second
|
||||
// (below it) then the fourth (beside it) go anticlockwise, y up. A reflected mesh, whose
|
||||
// patches all turn the other way, is written with its columns in reverse order, which turns
|
||||
// each of them the positive way and draws the same mesh; any other mesh with a patch that
|
||||
// doesn't turn the positive way is written as its drawn look.
|
||||
let reversed;
|
||||
let m = match turns(m, to_art)? {
|
||||
true => m,
|
||||
false => {
|
||||
reversed = columns_reversed(m);
|
||||
&reversed
|
||||
}
|
||||
};
|
||||
let (rows, cols) = (m.rows as usize, m.cols as usize);
|
||||
let at = |r: usize, c: usize| m.points.get(r * (cols + 1) + c);
|
||||
// Version 2: each corner has an opacity.
|
||||
let mut s = String::from("/Mesh X!\n%_2 /Version X#\n%_/Cartesian /Type X#\n");
|
||||
let _ = writeln!(s, "%_[{rows} {cols}] /Size X#\n%_/Data X#");
|
||||
let mut space = None;
|
||||
for r in 0..rows {
|
||||
for c in 0..cols {
|
||||
let _ = writeln!(s, "%_[{r} {c}] /P X#");
|
||||
// From the top left point down, right and up; each with its handles towards the
|
||||
// next corner and the one before it.
|
||||
for (p, next, prev) in
|
||||
[(at(r, c)?, H_DOWN, H_RIGHT), (at(r + 1, c)?, H_RIGHT, H_UP), (at(r + 1, c + 1)?, H_UP, H_LEFT), (at(r, c + 1)?, H_LEFT, H_DOWN)]
|
||||
{
|
||||
corner(&mut s, &mut space, to_art, p, next, prev)?;
|
||||
}
|
||||
s.push_str("%_/E X#\n");
|
||||
}
|
||||
}
|
||||
s.push_str("/End X!\n");
|
||||
let read = mesh_reads(s.as_bytes(), to_art.inverse())?;
|
||||
same_mesh(&read, m, SETTLE_POINT * to_art.inverse().determinant().abs().sqrt().max(1.0)).then_some(s)
|
||||
}
|
||||
|
||||
/// Mesh `n` written as `record`: its transparency before it (`xy`), the record, and the block
|
||||
/// its name and opacity mask go before ([`Self::node`]). The mesh is one object
|
||||
/// ([`Self::take_objects`]); nothing is written when there is no room for it.
|
||||
pub(super) fn write_mesh(&mut self, record: &str, xy: Xy) {
|
||||
if !self.take_objects(1) {
|
||||
return;
|
||||
}
|
||||
self.set_object_xy(xy.object());
|
||||
self.body.push_str(record);
|
||||
self.block_start = self.body.len();
|
||||
self.line("0 0 Xd\n6 () XW");
|
||||
self.block_end = self.body.len();
|
||||
}
|
||||
}
|
||||
|
||||
/// Which way every patch of `m` turns where `to_art` takes it, at each of its four corners, from
|
||||
/// its top left point to the one below it, then right and up, y up: `Some(true)` when all turn
|
||||
/// anticlockwise, `Some(false)` when all turn clockwise, and `None` when they differ (a patch
|
||||
/// folded across itself, or patches folded over each other) or a corner has no angle. Each corner
|
||||
/// is measured twice: along the straight lines to the next corners, and along its handles (towards
|
||||
/// the next corners where a handle is zero), where the patch's edges leave it.
|
||||
fn turns(m: &GradientMesh, to_art: Affine) -> Option<bool> {
|
||||
let (rows, cols) = (m.rows as usize, m.cols as usize);
|
||||
let at = |r: usize, c: usize| m.points.get(r * (cols + 1) + c);
|
||||
let mut way = None;
|
||||
for r in 0..rows {
|
||||
for c in 0..cols {
|
||||
// Each corner with the slots of its handles towards the next corner and the one before it.
|
||||
let corners =
|
||||
[(at(r, c)?, H_DOWN, H_RIGHT), (at(r + 1, c)?, H_RIGHT, H_UP), (at(r + 1, c + 1)?, H_UP, H_LEFT), (at(r, c + 1)?, H_LEFT, H_DOWN)];
|
||||
for i in 0..4 {
|
||||
let (before, (here, next, prev), after) = (corners[(i + 3) % 4].0, corners[i], corners[(i + 1) % 4].0);
|
||||
let line = |to: &MeshPoint| to_art * to.p - to_art * here.p;
|
||||
let along = |h: usize, to: &MeshPoint| -> Option<Vec2> {
|
||||
let h = *here.handles.get(h)?;
|
||||
Some(if h == Vec2::ZERO { line(to) } else { to_art * (here.p + h) - to_art * here.p })
|
||||
};
|
||||
for cross in [line(after).cross(line(before)), along(next, after)?.cross(along(prev, before)?)] {
|
||||
let positive = match cross {
|
||||
x if x > 0.0 => true,
|
||||
x if x < 0.0 => false,
|
||||
_ => return None,
|
||||
};
|
||||
if *way.get_or_insert(positive) != positive {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
way
|
||||
}
|
||||
|
||||
/// `m` with its columns in reverse order: each row's points from the last to the first, each
|
||||
/// point's handles to the right and left swapped. It draws the same mesh.
|
||||
fn columns_reversed(m: &GradientMesh) -> GradientMesh {
|
||||
let width = m.cols as usize + 1;
|
||||
let points = m
|
||||
.points
|
||||
.chunks(width)
|
||||
.flat_map(|row| {
|
||||
row.iter().rev().map(|p| {
|
||||
let mut p = p.clone();
|
||||
p.handles.swap(H_RIGHT, H_LEFT);
|
||||
p
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
GradientMesh { rows: m.rows, cols: m.cols, points }
|
||||
}
|
||||
|
||||
/// A corner `p` of a patch: its color space when it changes (in `space`), then `[color… opacity x y
|
||||
/// nx ny 1 px py 1] /N X#` with its handles `next` and `prev`, `to_art` taking the document to the
|
||||
/// space the corners are written in.
|
||||
fn corner(s: &mut String, space: &mut Option<Space>, to_art: Affine, p: &MeshPoint, next: usize, prev: usize) -> Option<()> {
|
||||
let (sp, values): (Space, Vec<f32>) = match p.color {
|
||||
// The format's gray is lightness.
|
||||
Color::Gray { k } => (Space::Gray, vec![1.0 - unit(k)]),
|
||||
Color::Rgb { r, g, b } => (Space::Rgb, vec![unit(r), unit(g), unit(b)]),
|
||||
Color::Cmyk { c, m, y, k } => (Space::Cmyk, vec![unit(c), unit(m), unit(y), unit(k)]),
|
||||
// The reader reads no Lab mesh colors.
|
||||
Color::Lab { .. } => return None,
|
||||
};
|
||||
if *space != Some(sp) {
|
||||
let _ = writeln!(s, "%_{} /CS X#", sp.name());
|
||||
*space = Some(sp);
|
||||
}
|
||||
let art = |q: Point| to_art * q;
|
||||
let (at, n, b) = (art(p.p), art(p.p + *p.handles.get(next)?), art(p.p + *p.handles.get(prev)?));
|
||||
s.push_str("%_[");
|
||||
for v in values {
|
||||
ps::push_num(s, f64::from(v));
|
||||
s.push(' ');
|
||||
}
|
||||
ps::push_num(s, f64::from(unit(p.opacity)));
|
||||
for v in [at.x, at.y, n.x, n.y] {
|
||||
s.push(' ');
|
||||
ps::push_num(s, v);
|
||||
}
|
||||
s.push_str(" 1");
|
||||
for v in [b.x, b.y] {
|
||||
s.push(' ');
|
||||
ps::push_num(s, v);
|
||||
}
|
||||
s.push_str(" 1] /N X#\n");
|
||||
Some(())
|
||||
}
|
||||
|
||||
/// Whether `read` is `m` as written: the same grid, each point within `tol` of its place, each
|
||||
/// handle that points into the grid within `tol` (the reader gives the others none, and they draw
|
||||
/// nothing), each color in the same model and within [`SETTLE_COLOR`] a channel, and each opacity
|
||||
/// within it.
|
||||
fn same_mesh(read: &GradientMesh, m: &GradientMesh, tol: f64) -> bool {
|
||||
if (read.rows, read.cols) != (m.rows, m.cols) || read.points.len() != m.points.len() {
|
||||
return false;
|
||||
}
|
||||
let (rows, cols) = (m.rows as usize, m.cols as usize);
|
||||
let near = |a: Point, b: Point| (a - b).hypot() <= tol * (1.0 + 1e-9 * a.to_vec2().hypot());
|
||||
read.points.iter().zip(&m.points).enumerate().all(|(i, (a, b))| {
|
||||
let (r, c) = (i / (cols + 1), i % (cols + 1));
|
||||
let inside = [c < cols, c > 0, r < rows, r > 0];
|
||||
let handles = [H_RIGHT, H_LEFT, H_DOWN, H_UP].iter().zip(inside).all(|(&h, inside)| {
|
||||
!inside || near(a.p + a.handles.get(h).copied().unwrap_or(Vec2::ZERO), b.p + b.handles.get(h).copied().unwrap_or(Vec2::ZERO))
|
||||
});
|
||||
near(a.p, b.p) && handles && same_color(&a.color, &b.color) && (a.opacity - unit(b.opacity)).abs() <= SETTLE_COLOR
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether `a` is `b` as written: the same model, each channel within [`SETTLE_COLOR`] of `b`'s
|
||||
/// clamped to 0 to 1.
|
||||
fn same_color(a: &Color, b: &Color) -> bool {
|
||||
let close = |x: &[f32], y: &[f32]| x.iter().zip(y).all(|(x, y)| (x - unit(*y)).abs() <= SETTLE_COLOR);
|
||||
match (a, b) {
|
||||
(Color::Gray { k }, Color::Gray { k: k2 }) => close(&[*k], &[*k2]),
|
||||
(Color::Rgb { r, g, b }, Color::Rgb { r: r2, g: g2, b: b2 }) => close(&[*r, *g, *b], &[*r2, *g2, *b2]),
|
||||
(Color::Cmyk { c, m, y, k }, Color::Cmyk { c: c2, m: m2, y: y2, k: k2 }) => close(&[*c, *m, *y, *k], &[*c2, *m2, *y2, *k2]),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
@@ -417,8 +417,8 @@ impl Writer<'_> {
|
||||
/// A stop's color and its style: gray `lightness 0`, CMYK `c m y k 1`, RGB (and Lab, as RGB)
|
||||
/// `c m y k r g b 2` with its CMYK equivalent; a spot color its full color's CMYK equivalent,
|
||||
/// then its RGB values when it isn't CMYK, its name and how much lighter than the full color,
|
||||
/// then `3` (CMYK), or `1 4` (RGB, and Lab as RGB). RGB values are an RGB color's own (in the
|
||||
/// working RGB space) and a Lab color's display RGB ([`ai_ops::rgb_values`]). An RGB color's CMYK
|
||||
/// then `3` (CMYK), or `1 4` (RGB, and Lab as RGB). RGB values are in the working RGB space: an
|
||||
/// RGB color's own and a Lab color's converted ([`ai_ops::rgb_values`]). An RGB color's CMYK
|
||||
/// equivalent is converted from its values as written ([`ai_ops::as_written`]), a Lab color's
|
||||
/// from its Lab values, and a spot color's CMYK equivalent and RGB values both come from its full
|
||||
/// color as the palette writes it.
|
||||
|
||||
@@ -28,7 +28,7 @@ use vectorcraft_doc::{
|
||||
};
|
||||
use vectorcraft_geom::{Affine, PathData, Point};
|
||||
|
||||
use crate::ps;
|
||||
use crate::{ai_ops, ps};
|
||||
|
||||
/// What the text document holds of type, and what it leaves out.
|
||||
pub(in crate::ai_editing) const TYPE_ATTRIBUTES: &str = "attributes of type other than its font, size, leading, tracking, baseline shift, horizontal and vertical scale, solid fill, solid stroke and its weight, cap, join and miter limit, capitals, small capitals at the document's size, Tate-chu-yoko, Standard Vertical Roman Alignment, Insert Aki, paragraph alignment, indents, space before and after, hyphenation on or off, right-to-left direction, Kinsoku set, Kinsoku Shori Type, Burasagari and Bunri-Kinshi (for example underline, kerning, OpenType features, swatch links of its colors, character and paragraph styles, tabs, lists, optical margin alignment, area type's inset spacing, vertical alignment and flow, a minimum first baseline with the Ascent first baseline, and type on a path's effect, alignment and spacing and an end bracket at the very end of an open path) are left out of the editing data for other apps";
|
||||
@@ -176,11 +176,13 @@ fn set(resources: Vec<V>, display: bool) -> V {
|
||||
}
|
||||
|
||||
/// A paint: kind 0 gray (`[alpha, lightness]`), 1 RGB, 2 CMYK, as the reader's `paint` reads them.
|
||||
/// RGB values are an RGB color's own (in the working RGB space) and a Lab color's converted into
|
||||
/// the working RGB space ([`ai_ops::rgb_values`]).
|
||||
fn paint(c: &Color) -> V {
|
||||
let (kind, values) = match *c {
|
||||
Color::Gray { k } => (0, vec![1.0 - f64::from(k.clamp(0.0, 1.0))]),
|
||||
Color::Cmyk { c, m, y, k } => (2, [c, m, y, k].iter().map(|v| f64::from(v.clamp(0.0, 1.0))).collect()),
|
||||
Color::Rgb { .. } | Color::Lab { .. } => (1, c.to_rgb().iter().map(|v| f64::from(v.clamp(0.0, 1.0))).collect()),
|
||||
Color::Rgb { .. } | Color::Lab { .. } => (1, ai_ops::rgb_values(*c).iter().map(|v| f64::from(*v)).collect()),
|
||||
};
|
||||
let values: Vec<f64> = std::iter::once(1.0).chain(values).collect();
|
||||
dict(vec![(99, V::Name("SimplePaint")), (0, dict(vec![(0, V::Int(kind)), (1, reals(&values))]))])
|
||||
|
||||
@@ -113,20 +113,23 @@ pub(crate) fn as_written(color: Color) -> Color {
|
||||
}
|
||||
}
|
||||
|
||||
/// The RGB values written for `color`, clamped to 0..1: an RGB color's own values (in the working
|
||||
/// RGB space, as a reader reads them back), any other color's display RGB.
|
||||
/// The RGB values written for `color`, clamped to 0..1, in the working RGB space, as a reader
|
||||
/// reads them back: an RGB color's own values, any other color's display RGB converted into the
|
||||
/// working RGB space.
|
||||
pub(crate) fn rgb_values(color: Color) -> [f32; 3] {
|
||||
match color {
|
||||
Color::Rgb { r, g, b } => [r, g, b].map(unit),
|
||||
c => c.to_rgb().map(unit),
|
||||
c => vectorcraft_color::cms::active().srgb_to_rgb(c.to_rgb()).map(unit),
|
||||
}
|
||||
}
|
||||
|
||||
/// The average colour of a gradient's stops (in RGB).
|
||||
/// The average color of a gradient's stops: the average of their display RGB, as an RGB color in
|
||||
/// the working RGB space.
|
||||
pub(crate) fn average(g: &Gradient) -> Color {
|
||||
let n = g.stops.len().max(1) as f32;
|
||||
let sum = g.stops.iter().map(|s| s.color.to_rgb()).fold([0.0f32; 3], |a, c| [a[0] + c[0], a[1] + c[1], a[2] + c[2]]);
|
||||
Color::rgb(unit(sum[0] / n), unit(sum[1] / n), unit(sum[2] / n))
|
||||
let [r, green, b] = vectorcraft_color::cms::active().srgb_to_rgb(sum.map(|v| v / n)).map(unit);
|
||||
Color::rgb(r, green, b)
|
||||
}
|
||||
|
||||
/// The pixels an image's part keeps past the edge of the region that shows it, on each side: as
|
||||
|
||||
@@ -90,9 +90,10 @@ pub use ai::NameEncoding;
|
||||
#[cfg(test)]
|
||||
pub(crate) use ai::objects_read;
|
||||
pub(crate) use ai::{
|
||||
BRUSH_MANAGER, BrushesRead, DEFORM_PLUGIN, EnvelopeGridPoint, MAX_CHECKED as ENVELOPE_CHECKS, MAX_EDITING_OBJECTS, MAX_GRADIENT_STOPS,
|
||||
MAX_LISTED, MAX_LISTED_NAME, MAX_SYMBOLS, brush_plugin_name, brushes_kept, envelope_outline, envelope_upright, read_art_style, read_brush_object,
|
||||
read_style_list, style_moves_with, symbol_art_member, warp_number,
|
||||
BLEND_BUDGET, BLEND_PLUGIN, BRUSH_MANAGER, BrushesRead, DEFORM_PLUGIN, EnvelopeGridPoint, MAX_BLEND_KEYS, MAX_BLEND_OBJECTS,
|
||||
MAX_CHECKED as ENVELOPE_CHECKS, MAX_EDITING_OBJECTS, MAX_GRADIENT_STOPS, MAX_LISTED, MAX_LISTED_NAME, MAX_MESH_SIDE, MAX_SYMBOLS, blend_reads,
|
||||
brush_plugin_name, brushes_kept, envelope_outline, envelope_upright, mesh_reads, read_art_style, read_brush_object, read_style_list,
|
||||
style_moves_with, symbol_art_member, turn_brush_art_over, warp_number,
|
||||
};
|
||||
#[cfg(test)]
|
||||
pub(crate) use ai::{ENVELOPE_DRAWN, ENVELOPE_TYPE_DRAWN};
|
||||
|
||||
@@ -34,14 +34,20 @@ use std::io::Read as _;
|
||||
use super::lex::find;
|
||||
use crate::ps;
|
||||
|
||||
pub(crate) use brush::{BrushesRead, MANAGER_NAME as BRUSH_MANAGER, brushes_kept, plugin_name as brush_plugin_name, read_brush_object};
|
||||
pub(crate) use blend::{MAX_BLEND_OBJECTS, MAX_KEYS as MAX_BLEND_KEYS, PLUGIN as BLEND_PLUGIN, blend_reads};
|
||||
pub(crate) use brush::{
|
||||
BrushesRead, MANAGER_NAME as BRUSH_MANAGER, brushes_kept, plugin_name as brush_plugin_name, read_brush_object, turn_over as turn_brush_art_over,
|
||||
};
|
||||
pub(crate) use envelope::DRAWN as ENVELOPE_DRAWN;
|
||||
pub(crate) use envelope::MAX_CHECKED;
|
||||
pub(crate) use envelope::TYPE_DRAWN as ENVELOPE_TYPE_DRAWN;
|
||||
pub(crate) use envelope::{GridPoint as EnvelopeGridPoint, PLUGIN as DEFORM_PLUGIN, outline as envelope_outline, upright as envelope_upright};
|
||||
pub(crate) use envelope::{MAX_ANY as ENVELOPE_MAX_ANY, MAX_SOLID as ENVELOPE_MAX_SOLID};
|
||||
pub(crate) use envelope::{WARPED_TYPE_DRAWN, WarpedType};
|
||||
#[cfg(test)]
|
||||
pub(crate) use frames::TEXT_FRAME_SCANS;
|
||||
pub(crate) use frames::text_frames;
|
||||
pub(crate) use mesh::{MAX_SIDE as MAX_MESH_SIDE, mesh_reads};
|
||||
pub use obj::{NameEncoding, Names};
|
||||
pub(crate) use paint::MAX_STOPS as MAX_GRADIENT_STOPS;
|
||||
#[cfg(test)]
|
||||
@@ -50,14 +56,14 @@ pub(crate) use read::objects_read;
|
||||
pub use read::read;
|
||||
#[cfg(test)]
|
||||
pub(crate) use read::with_image_limits;
|
||||
pub(crate) use read::{
|
||||
BLEND_BUDGET, MAX_NODES as MAX_EDITING_OBJECTS, MAX_SYMBOLS, join_and, read_art_style, read_over_page, read_program, read_style_list, slot_frame,
|
||||
slot_of, style_moves_with, symbol_art_member,
|
||||
};
|
||||
pub use read::{
|
||||
BindingRef, Brushes, PaletteSwatches, PlacedPage, Structure, Symbols, active_artboard, artboards, bindings_note, brushes, graphic_styles,
|
||||
palette, read_beside, read_in, symbols, variables,
|
||||
};
|
||||
pub(crate) use read::{
|
||||
MAX_NODES as MAX_EDITING_OBJECTS, MAX_SYMBOLS, join_and, read_art_style, read_over_page, read_program, read_style_list, slot_frame, slot_of,
|
||||
style_moves_with, symbol_art_member,
|
||||
};
|
||||
|
||||
pub(crate) use read::is_look_slot;
|
||||
pub(crate) use style::{MAX_LISTED, MAX_LISTED_NAME, warp_number};
|
||||
|
||||
@@ -15,11 +15,14 @@
|
||||
//!
|
||||
//! The reader reads the words after `DCBA` (little endian) this way. Word 1 is the spacing: 0 is
|
||||
//! Smooth Color, 1 is Specified Steps and 2 is Specified Distance. For Specified Distance, word 2
|
||||
//! is the distance in points, as a 32-bit float. Word 10 is the number of keys, and the words after
|
||||
//! it are a record of six words per key that starts with the key's id. For Specified Steps, the
|
||||
//! steps between two keys are counted from the steps drawn. The orientation is taken from the steps
|
||||
//! drawn: whichever one lays the blend out as they are drawn. A blend whose parts don't agree,
|
||||
//! whose spacing isn't one of these, or that doesn't come out as drawn, keeps its drawn steps.
|
||||
//! is the distance in points, as a 32-bit float. Word 5 is 0 for Align to Page and, for Align to
|
||||
//! Path, a 32-bit float of 8 or more. Word 10 is the number of keys, and the words after it are a
|
||||
//! record of six words per key that starts with the key's id. For Specified Steps, the steps
|
||||
//! between two keys are counted from the steps drawn. The orientation is the record's when it lays
|
||||
//! the blend out as the steps are drawn, else whichever one does (the closest when both do). A blend
|
||||
//! with no spine part whose record names its keys in their order has no spine of its own: it runs
|
||||
//! straight between its keys' centers. A blend whose parts don't agree, whose spacing isn't one of
|
||||
//! these, or that doesn't come out as drawn, keeps its drawn steps.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
@@ -28,19 +31,19 @@ use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::blend::{blend_expand, blend_steps};
|
||||
use vectorcraft_doc::live::{BlendOrientation, BlendSpacing, BlendSpec};
|
||||
use vectorcraft_doc::{AppearanceItem, Node, NodeId, NodeKind};
|
||||
use vectorcraft_geom::{PathData, Point, SubPath};
|
||||
use vectorcraft_geom::{ParamCurve, PathData, Point, SubPath};
|
||||
|
||||
/// The plugin that writes blends.
|
||||
pub(super) const PLUGIN: &str = "Adobe Path Blends"; // brand-ok: the plugin name the files use
|
||||
pub(crate) const PLUGIN: &str = "Adobe Path Blends"; // brand-ok: the plugin name the files use
|
||||
/// The most bytes of a blend's record read.
|
||||
pub(super) const MAX_RECORD: usize = 4096;
|
||||
/// The most keys read from one blend.
|
||||
const MAX_KEYS: usize = 64;
|
||||
pub(crate) const MAX_KEYS: usize = 64;
|
||||
/// The most steps between two keys (Blend Options' limit).
|
||||
const MAX_STEPS: usize = 1000;
|
||||
/// The most objects (keys and steps) one blend may lay out to be read live; more keep their
|
||||
/// drawn steps.
|
||||
pub(super) const MAX_BLEND_OBJECTS: usize = 5_000;
|
||||
pub(crate) const MAX_BLEND_OBJECTS: usize = 5_000;
|
||||
/// How far (pt) a step laid out here may be from where the file draws it.
|
||||
const PLACE_TOLERANCE: f64 = 0.5;
|
||||
/// How far a step's colour (each channel, 0 to 1) may be from the drawn one.
|
||||
@@ -66,6 +69,8 @@ pub(super) struct Record {
|
||||
pub(super) ids: Vec<String>,
|
||||
/// `None`: Specified Steps, whose steps the reader counts from the drawn ones.
|
||||
pub(super) spacing: Option<BlendSpacing>,
|
||||
/// The orientation word 5 names, when it names one.
|
||||
pub(super) orientation: Option<BlendOrientation>,
|
||||
}
|
||||
|
||||
/// A blend's record, or `None` for a record that isn't one or whose spacing isn't read: an
|
||||
@@ -82,7 +87,18 @@ pub(super) fn record(bytes: &[u8]) -> Option<Record> {
|
||||
_ => return None,
|
||||
};
|
||||
let ids = record_ids(&words)?;
|
||||
Some(Record { ids, spacing })
|
||||
let orientation = words.get(5).and_then(|w| orientation(*w));
|
||||
Some(Record { ids, spacing, orientation })
|
||||
}
|
||||
|
||||
/// The orientation in a record's word 5: 0 is Align to Page, a 32-bit float of 8 or more Align to
|
||||
/// Path; anything else names none.
|
||||
fn orientation(bits: u32) -> Option<BlendOrientation> {
|
||||
if bits == 0 {
|
||||
return Some(BlendOrientation::AlignToPage);
|
||||
}
|
||||
let a = f32::from_bits(bits);
|
||||
(a.is_finite() && a >= 8.0).then_some(BlendOrientation::AlignToPath)
|
||||
}
|
||||
|
||||
/// The distance in a record's word `bits` (a 32-bit float), as the shortest decimal that reads
|
||||
@@ -131,6 +147,7 @@ pub(super) fn live_blend(edit: &Node, drawn: &Node, record: &Record, roles: &Rol
|
||||
if keys.len() < 2 || named.len() != keys.len() || ids.len() != keys.len() {
|
||||
return None;
|
||||
}
|
||||
let in_order = named.iter().zip(ids).all(|(n, id)| *n == id.as_str());
|
||||
named.sort_unstable();
|
||||
let mut listed: Vec<&str> = ids.iter().map(String::as_str).collect();
|
||||
listed.sort_unstable();
|
||||
@@ -150,12 +167,20 @@ pub(super) fn live_blend(edit: &Node, drawn: &Node, record: &Record, roles: &Rol
|
||||
})
|
||||
.collect();
|
||||
// A blend whose spine was never edited has none written: its spine is the straight lines
|
||||
// between the keys' centres, in the record's order.
|
||||
let spine = match spine {
|
||||
Some(spine) => spine,
|
||||
None => straight_spine(&keys, ids, roles)?,
|
||||
// between the keys' centers, in the record's order. With the keys in that order it is the
|
||||
// spine of a blend that has none of its own.
|
||||
let (spine, key_anchors) = match spine {
|
||||
Some(spine) => {
|
||||
let anchors = on_spine(&keys, &spine)?;
|
||||
(Some(spine), anchors)
|
||||
}
|
||||
None if in_order => (None, vec![]),
|
||||
None => {
|
||||
let spine = straight_spine(&keys, ids, roles)?;
|
||||
let anchors = on_spine(&keys, &spine)?;
|
||||
(Some(spine), anchors)
|
||||
}
|
||||
};
|
||||
let key_anchors = on_spine(&keys, &spine)?;
|
||||
let spacing = match record.spacing {
|
||||
// Specified Steps: the steps between two keys are the drawn objects that aren't keys,
|
||||
// shared out.
|
||||
@@ -170,26 +195,68 @@ pub(super) fn live_blend(edit: &Node, drawn: &Node, record: &Record, roles: &Rol
|
||||
if cost > *budget {
|
||||
return None;
|
||||
}
|
||||
let spec = BlendSpec { spacing, spine: Some(spine), key_anchors, ..BlendSpec::default() };
|
||||
let spec = BlendSpec { spacing, spine, key_anchors, ..BlendSpec::default() };
|
||||
// As many objects as the spacing lays out between each pair of keys (the orientation doesn't
|
||||
// change how many), counted before anything is laid out: as many as are drawn.
|
||||
if blend_steps(&keys, &spec).into_iter().fold(keys.len(), usize::saturating_add) != drawn.len() {
|
||||
return None;
|
||||
}
|
||||
*budget -= cost;
|
||||
// The drawn steps' centres and paints, once.
|
||||
let drawn: Vec<(Point, Fill)> = drawn.iter().map(|d| Some((centre(d)?, fill(d)))).collect::<Option<_>>()?;
|
||||
// The orientation that lays the steps out as drawn, the closest when both do.
|
||||
[BlendOrientation::AlignToPage, BlendOrientation::AlignToPath]
|
||||
// The drawn steps as the check compares them, once.
|
||||
let drawn: Vec<Drawn> = drawn.iter().map(|d| drawn_as(d)).collect::<Option<_>>()?;
|
||||
// The orientations that lay the steps out as drawn (the check compares the steps' centers, which
|
||||
// turning the steps along the spine leaves in place). Of those that also lay them out at their
|
||||
// drawn sizes and turned as drawn, the record's, else the closest; when none does, the closest
|
||||
// of them all.
|
||||
let fits: Vec<(f64, BlendSpec, Vec<Node>)> = [BlendOrientation::AlignToPage, BlendOrientation::AlignToPath]
|
||||
.into_iter()
|
||||
.filter_map(|orientation| {
|
||||
let spec = BlendSpec { orientation, ..spec.clone() };
|
||||
let laid = blend_expand(&keys, &spec);
|
||||
let off = how_far(&laid, &drawn)?;
|
||||
Some((off, spec))
|
||||
let off = how_far(&laid, &drawn, false)?;
|
||||
Some((off, spec, laid))
|
||||
})
|
||||
.min_by(|a, b| a.0.total_cmp(&b.0))
|
||||
.map(|(_, spec)| NodeKind::Blend { children: keys, spec: Box::new(spec) })
|
||||
.collect();
|
||||
let as_drawn: Vec<&(f64, BlendSpec, Vec<Node>)> = fits.iter().filter(|(_, _, laid)| how_far(laid, &drawn, true).is_some()).collect();
|
||||
as_drawn
|
||||
.iter()
|
||||
.copied()
|
||||
.find(|(_, s, _)| Some(s.orientation) == record.orientation)
|
||||
.or_else(|| as_drawn.iter().copied().min_by(|a, b| a.0.total_cmp(&b.0)))
|
||||
.or_else(|| fits.iter().min_by(|a, b| a.0.total_cmp(&b.0)))
|
||||
.map(|(_, spec, _)| NodeKind::Blend { children: keys, spec: Box::new(spec.clone()) })
|
||||
}
|
||||
|
||||
/// What the reader makes of a blend written as the key objects `keys`, named by `ids` in their
|
||||
/// order, the spine `spine` (`None`: no spine part), the record `bytes` and the drawn steps `drawn`:
|
||||
/// the live blend's settings, or `None` where it keeps the drawn steps. Takes from `budget` as
|
||||
/// [`live_blend`] does.
|
||||
pub(crate) fn blend_reads(
|
||||
keys: &[Arc<Node>],
|
||||
ids: &[String],
|
||||
spine: Option<&PathData>,
|
||||
bytes: &[u8],
|
||||
drawn: &[Node],
|
||||
budget: &mut usize,
|
||||
) -> Option<BlendSpec> {
|
||||
let record = record(bytes)?;
|
||||
let mut roles = Roles::new();
|
||||
let mut parts: Vec<Arc<Node>> = Vec::with_capacity(keys.len() + 1);
|
||||
for (k, id) in keys.iter().zip(ids) {
|
||||
roles.insert(k.id, ("K".to_string(), Some(id.clone())));
|
||||
parts.push(k.clone());
|
||||
}
|
||||
if let Some(s) = spine {
|
||||
let id = NodeId(u64::MAX);
|
||||
roles.insert(id, ("S".to_string(), None));
|
||||
parts.push(Arc::new(Node::path(id, s.clone(), Default::default())));
|
||||
}
|
||||
let edit = Node::new(NodeId(u64::MAX - 1), NodeKind::Group { children: parts, clip: false });
|
||||
let drawn = Node::new(NodeId(u64::MAX - 2), NodeKind::Group { children: drawn.iter().cloned().map(Arc::new).collect(), clip: false });
|
||||
match live_blend(&edit, &drawn, &record, &roles, budget)? {
|
||||
NodeKind::Blend { spec, .. } => Some(*spec),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The anchor of `spine`'s first subpath each key's centre sits on (within a point), each a
|
||||
@@ -227,6 +294,117 @@ fn centre(n: &Node) -> Option<Point> {
|
||||
n.geometric_bounds().map(|b| b.center()).filter(|p| p.x.is_finite() && p.y.is_finite())
|
||||
}
|
||||
|
||||
/// The most anchors of an object's paths the check compares; an object with more is compared by its
|
||||
/// size alone.
|
||||
const MAX_MARK_ANCHORS: usize = 64;
|
||||
/// The most drawn objects whose outlines one check compares, spread evenly from the first to the
|
||||
/// last; the rest are compared by their sizes alone (the orientation turns every step alike).
|
||||
const MAX_OUTLINE_CHECKS: usize = 16;
|
||||
/// The most outline comparisons one check makes (a drawn object compared can have more than one
|
||||
/// laid object in its place); past them, a drawn object whose outline is to be compared matches
|
||||
/// none.
|
||||
const MAX_OUTLINE_COMPARISONS: usize = 4 * MAX_OUTLINE_CHECKS;
|
||||
|
||||
/// An object as the check compares it.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
struct Drawn<'a> {
|
||||
centre: Point,
|
||||
fill: Fill,
|
||||
/// Its width and height.
|
||||
size: Point,
|
||||
/// The object, for its paths' outline ([`outline`]), which turning it moves.
|
||||
node: &'a Node,
|
||||
}
|
||||
|
||||
/// `n` as the check compares it, or `None` when it has no finite bounds.
|
||||
fn drawn_as(n: &Node) -> Option<Drawn<'_>> {
|
||||
let size = n.geometric_bounds().map(|b| Point::new(b.width(), b.height())).filter(|p| p.x.is_finite() && p.y.is_finite())?;
|
||||
Some(Drawn { centre: centre(n)?, fill: fill(n), size, node: n })
|
||||
}
|
||||
|
||||
/// How the check compares an object's turn.
|
||||
enum Outline {
|
||||
/// By its outline: every subpath of more than one anchor of its paths, in any order, each with
|
||||
/// its path's fill, so that a turn that trades the places of paths painted differently doesn't
|
||||
/// pass.
|
||||
Paths(Vec<(Fill, SubPath)>),
|
||||
/// By its size alone: it holds art whose drawing isn't its members (a blend, an envelope, a
|
||||
/// repeat), art past eight levels down, more than [`MAX_MARK_ANCHORS`] anchors or no subpath to
|
||||
/// compare.
|
||||
Size,
|
||||
}
|
||||
|
||||
/// How the check compares `n`'s turn (the members of its groups and compound paths looked through,
|
||||
/// at most eight levels down; a compound path's members take its fill).
|
||||
fn outline(n: &Node) -> Outline {
|
||||
/// What the walk found.
|
||||
#[derive(Default)]
|
||||
struct Walk {
|
||||
subpaths: Vec<(Fill, SubPath)>,
|
||||
anchors: usize,
|
||||
/// Art compared by the size alone, or too many anchors.
|
||||
size_only: bool,
|
||||
}
|
||||
fn add(n: &Node, depth: usize, painted: Option<Fill>, w: &mut Walk) {
|
||||
if w.size_only {
|
||||
return;
|
||||
}
|
||||
match &n.kind {
|
||||
NodeKind::Path { path, .. } => {
|
||||
let f = painted.unwrap_or_else(|| fill(n));
|
||||
// A subpath of one anchor has no segment to compare with.
|
||||
for s in path.subpaths.iter().filter(|s| s.anchors.len() > 1) {
|
||||
w.anchors = w.anchors.saturating_add(s.anchors.len());
|
||||
if w.anchors > MAX_MARK_ANCHORS {
|
||||
w.size_only = true;
|
||||
return;
|
||||
}
|
||||
w.subpaths.push((f, s.clone()));
|
||||
}
|
||||
}
|
||||
NodeKind::Group { children, .. } if depth < 8 => {
|
||||
for c in children {
|
||||
add(c, depth + 1, painted, w);
|
||||
}
|
||||
}
|
||||
NodeKind::Compound { children, .. } if depth < 8 => {
|
||||
let f = painted.unwrap_or_else(|| fill(n));
|
||||
for c in children {
|
||||
add(c, depth + 1, Some(f), w);
|
||||
}
|
||||
}
|
||||
_ => w.size_only = true,
|
||||
}
|
||||
}
|
||||
let mut w = Walk::default();
|
||||
add(n, 0, None, &mut w);
|
||||
if w.size_only || w.subpaths.is_empty() { Outline::Size } else { Outline::Paths(w.subpaths) }
|
||||
}
|
||||
|
||||
/// Do two outlines ([`Outline::Paths`]) draw the same lines in the same fills: each anchor of one,
|
||||
/// and the points a quarter, half and three quarters along each of its segments (which show how a
|
||||
/// curved side bends), within `tolerance` of the other's subpaths of a fill that matches its own?
|
||||
/// Where a path starts, how many anchors it has on a straight or curved stretch, and the order of
|
||||
/// the paths don't count.
|
||||
fn same_outline(a: &[(Fill, SubPath)], b: &[(Fill, SubPath)], tolerance: f64) -> bool {
|
||||
let on = |from: &[(Fill, SubPath)], to: &[(Fill, SubPath)]| {
|
||||
from.iter().all(|(f, s)| {
|
||||
// Fills the check can't compare (gradients, patterns) are compared with each other by
|
||||
// their outline alone.
|
||||
let to = PathData::new(
|
||||
to.iter().filter(|(g, _)| same_fill(*f, *g) || (*f == Fill::Other && *g == Fill::Other)).map(|(_, t)| t.clone()).collect(),
|
||||
);
|
||||
let near = |p: Point| to.nearest(p).is_some_and(|(.., d)| d <= tolerance);
|
||||
s.anchors.iter().all(|p| near(p.p))
|
||||
&& (0..s.segment_count()).all(|i| {
|
||||
let c = s.segment(i);
|
||||
[0.25, 0.5, 0.75].into_iter().all(|t| near(c.eval(t)))
|
||||
})
|
||||
})
|
||||
};
|
||||
on(a, b) && on(b, a)
|
||||
}
|
||||
|
||||
/// An object's fill, as far as the check compares it.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
enum Fill {
|
||||
@@ -267,31 +445,76 @@ fn same_fill(a: Fill, b: Fill) -> bool {
|
||||
/// farthest, each drawn object matched to a laid one of its own within the tolerance (each laid
|
||||
/// one matches one drawn one: the nearest still free; through a grid of cells the tolerance wide,
|
||||
/// so each finds its neighbours without looking at them all), when they are as many and each
|
||||
/// matches in place and fill; else `None` (also when that matching leaves one out).
|
||||
fn how_far(laid: &[Node], drawn: &[(Point, Fill)]) -> Option<f64> {
|
||||
/// matches in place and fill, and with `turned` also in width and height and, for at most
|
||||
/// [`MAX_OUTLINE_CHECKS`] drawn objects spread from the first to the last, in the outline of its
|
||||
/// paths (each within twice the tolerance), which turning an object changes; else `None` (also when
|
||||
/// that matching leaves one out, and when it would take more than [`MAX_OUTLINE_COMPARISONS`]
|
||||
/// outline comparisons).
|
||||
fn how_far(laid: &[Node], drawn: &[Drawn], turned: bool) -> Option<f64> {
|
||||
if laid.len() != drawn.len() {
|
||||
return None;
|
||||
}
|
||||
let cell = |p: Point| ((p.x / PLACE_TOLERANCE).floor() as i64, (p.y / PLACE_TOLERANCE).floor() as i64);
|
||||
let laid: Vec<(Point, Fill)> = laid.iter().map(|l| Some((centre(l)?, fill(l)))).collect::<Option<_>>()?;
|
||||
let laid: Vec<Drawn> = laid.iter().map(drawn_as).collect::<Option<_>>()?;
|
||||
let mut grid: HashMap<(i64, i64), Vec<usize>> = HashMap::with_capacity(laid.len());
|
||||
for (i, (p, _)) in laid.iter().enumerate() {
|
||||
grid.entry(cell(*p)).or_default().push(i);
|
||||
for (i, l) in laid.iter().enumerate() {
|
||||
grid.entry(cell(l.centre)).or_default().push(i);
|
||||
}
|
||||
let close = |a: Point, b: Point| (a.x - b.x).abs() <= 2.0 * PLACE_TOLERANCE && (a.y - b.y).abs() <= 2.0 * PLACE_TOLERANCE;
|
||||
// The drawn objects whose outlines are compared: all of them, or as many as the limit allows,
|
||||
// spread evenly so that the first and the last are among them.
|
||||
let mut compare_outline = vec![drawn.len() <= MAX_OUTLINE_CHECKS; drawn.len()];
|
||||
if drawn.len() > MAX_OUTLINE_CHECKS {
|
||||
for j in 0..MAX_OUTLINE_CHECKS {
|
||||
if let Some(c) = compare_outline.get_mut(j * (drawn.len() - 1) / (MAX_OUTLINE_CHECKS - 1)) {
|
||||
*c = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
let outlines_compared = std::cell::Cell::new(0usize);
|
||||
let same_turn = |l: &Drawn, d: &Drawn, compare: bool| {
|
||||
if !turned {
|
||||
return true;
|
||||
}
|
||||
if !close(l.size, d.size) || !compare {
|
||||
return close(l.size, d.size);
|
||||
}
|
||||
// An outline that isn't compared doesn't count as the same.
|
||||
if outlines_compared.get() >= MAX_OUTLINE_COMPARISONS {
|
||||
return false;
|
||||
}
|
||||
outlines_compared.set(outlines_compared.get() + 1);
|
||||
match (outline(l.node), outline(d.node)) {
|
||||
(Outline::Paths(a), Outline::Paths(b)) => same_outline(&a, &b, 2.0 * PLACE_TOLERANCE),
|
||||
// Live art against its drawing, too many anchors, or no paths: compared by the size
|
||||
// alone.
|
||||
_ => true,
|
||||
}
|
||||
};
|
||||
let mut used = vec![false; laid.len()];
|
||||
let mut worst: f64 = 0.0;
|
||||
for &(c, f) in drawn {
|
||||
for (k, d) in drawn.iter().enumerate() {
|
||||
let (c, f) = (d.centre, d.fill);
|
||||
let compare = compare_outline.get(k).copied().unwrap_or(false);
|
||||
let (cx, cy) = cell(c);
|
||||
// Coordinates far out saturate the cells: the neighbours' keys saturate too.
|
||||
let (i, near) = (-1i64..=1)
|
||||
let candidates = (-1i64..=1)
|
||||
.flat_map(|dx| (-1i64..=1).map(move |dy| (cx.saturating_add(dx), cy.saturating_add(dy))))
|
||||
.filter_map(|k| grid.get(&k))
|
||||
.flatten()
|
||||
.filter(|&&i| !used.get(i).copied().unwrap_or(true))
|
||||
.filter_map(|&i| laid.get(i).map(|l| (i, l)))
|
||||
.filter(|(_, (p, lf))| (*p - c).hypot() <= PLACE_TOLERANCE && same_fill(*lf, f))
|
||||
.map(|(i, (p, _))| (i, (*p - c).hypot()))
|
||||
.min_by(|a, b| a.1.total_cmp(&b.1))?;
|
||||
.filter(|(_, l)| (l.centre - c).hypot() <= PLACE_TOLERANCE && same_fill(l.fill, f));
|
||||
let (i, near) = if turned && compare {
|
||||
// Outlines are tried nearest first, so that steps crowded in one place don't spend the
|
||||
// outline comparisons on candidates farther off.
|
||||
let mut nearest: Vec<(usize, f64)> =
|
||||
candidates.filter(|(_, l)| close(l.size, d.size)).map(|(i, l)| (i, (l.centre - c).hypot())).collect();
|
||||
nearest.sort_by(|a, b| a.1.total_cmp(&b.1));
|
||||
nearest.into_iter().find(|(i, _)| laid.get(*i).is_some_and(|l| same_turn(l, d, true)))?
|
||||
} else {
|
||||
candidates.filter(|(_, l)| same_turn(l, d, false)).map(|(i, l)| (i, (l.centre - c).hypot())).min_by(|a, b| a.1.total_cmp(&b.1))?
|
||||
};
|
||||
if let Some(u) = used.get_mut(i) {
|
||||
*u = true;
|
||||
}
|
||||
@@ -364,7 +587,7 @@ mod tests {
|
||||
let edit = Node::new(NodeId(1), NodeKind::Group { children: vec![], clip: false });
|
||||
let drawn = Node::new(NodeId(2), NodeKind::Group { children: vec![], clip: false });
|
||||
let mut budget = 1;
|
||||
let record = Record { ids: vec!["A".into(), "B".into()], spacing: None };
|
||||
let record = Record { ids: vec!["A".into(), "B".into()], spacing: None, orientation: None };
|
||||
assert!(live_blend(&edit, &drawn, &record, &Roles::new(), &mut budget).is_none());
|
||||
assert_eq!(budget, 1);
|
||||
}
|
||||
@@ -396,7 +619,7 @@ mod tests {
|
||||
#[test]
|
||||
fn a_blend_takes_from_the_budget_only_when_it_is_laid_out() {
|
||||
let (edit, drawn, roles) = two_keys();
|
||||
let steps = Record { ids: vec!["A".into(), "B".into()], spacing: None };
|
||||
let steps = Record { ids: vec!["A".into(), "B".into()], spacing: None, orientation: None };
|
||||
let mut budget = 10;
|
||||
assert!(matches!(live_blend(&edit, &drawn, &steps, &roles, &mut budget), Some(NodeKind::Blend { .. })));
|
||||
assert_eq!(budget, 0);
|
||||
@@ -417,7 +640,7 @@ mod tests {
|
||||
let NodeKind::Group { children, .. } = &drawn.kind else { panic!("a group") };
|
||||
let keys_alone = [children[0].clone(), children[4].clone()];
|
||||
let drawn = Node::new(NodeId(11), NodeKind::Group { children: keys_alone.to_vec(), clip: false });
|
||||
let far = Record { ids: vec!["A".into(), "B".into()], spacing: Some(BlendSpacing::Distance(150.0)) };
|
||||
let far = Record { ids: vec!["A".into(), "B".into()], spacing: Some(BlendSpacing::Distance(150.0)), orientation: None };
|
||||
let mut budget = 10;
|
||||
let Some(NodeKind::Blend { spec, .. }) = live_blend(&edit, &drawn, &far, &roles, &mut budget) else { panic!("a live blend") };
|
||||
assert_eq!(spec.spacing, BlendSpacing::Distance(150.0));
|
||||
@@ -427,6 +650,44 @@ mod tests {
|
||||
assert_eq!(budget, 6);
|
||||
}
|
||||
|
||||
/// Word 5 names the orientation: 0 Align to Page, a 32-bit float of 8 or more (8 and an angle)
|
||||
/// Align to Path; any other value names none, and a record too short to hold it names none.
|
||||
#[test]
|
||||
fn records_say_their_orientation() {
|
||||
let magic = u32::from_le_bytes(*b"DCBA");
|
||||
let words = |w5: u32| {
|
||||
[magic, 1, 50f32.to_bits(), 0, 3, w5, 'C' as u32, 0, 0, 1, 2, 'A' as u32, 0, 0, u32::MAX, u32::MAX, 0, 'B' as u32, 0, 1f32.to_bits()]
|
||||
.into_iter()
|
||||
.chain([u32::MAX, u32::MAX, 3])
|
||||
.flat_map(u32::to_le_bytes)
|
||||
.collect::<Vec<u8>>()
|
||||
};
|
||||
let orientation = |w5: u32| record(&words(w5)).map(|r| r.orientation);
|
||||
assert_eq!(orientation(0), Some(Some(BlendOrientation::AlignToPage)));
|
||||
assert_eq!(orientation(8f32.to_bits()), Some(Some(BlendOrientation::AlignToPath)));
|
||||
assert_eq!(orientation(11.141593f32.to_bits()), Some(Some(BlendOrientation::AlignToPath)));
|
||||
for other in [1f32.to_bits(), 7.9f32.to_bits(), (-9f32).to_bits(), f32::NAN.to_bits(), f32::INFINITY.to_bits()] {
|
||||
assert_eq!(orientation(other), Some(None), "{other:#x}");
|
||||
}
|
||||
}
|
||||
|
||||
/// On a level straight spine both orientations lay two squares' steps out alike: the blend takes
|
||||
/// the record's orientation, and Align to Page when the record names none.
|
||||
#[test]
|
||||
fn the_records_orientation_is_kept_where_both_lay_out_alike() {
|
||||
let (edit, drawn, roles) = two_keys();
|
||||
for (named, want) in [
|
||||
(Some(BlendOrientation::AlignToPath), BlendOrientation::AlignToPath),
|
||||
(Some(BlendOrientation::AlignToPage), BlendOrientation::AlignToPage),
|
||||
(None, BlendOrientation::AlignToPage),
|
||||
] {
|
||||
let record = Record { ids: vec!["A".into(), "B".into()], spacing: None, orientation: named };
|
||||
let mut budget = 10;
|
||||
let Some(NodeKind::Blend { spec, .. }) = live_blend(&edit, &drawn, &record, &roles, &mut budget) else { panic!("a live blend") };
|
||||
assert_eq!(spec.orientation, want, "{named:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Two drawn steps on one laid object don't both match it: each laid object matches one drawn
|
||||
/// one, so a drawing the blend doesn't lay out isn't taken for it.
|
||||
#[test]
|
||||
@@ -435,12 +696,261 @@ mod tests {
|
||||
let path = vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(x, 0.0, x + 10.0, 10.0));
|
||||
Node::path(NodeId(0), path, Default::default())
|
||||
};
|
||||
// `laid` against the objects `drawn` as the check compares them.
|
||||
let check = |laid: &[Node], drawn: &[Node], turned: bool| {
|
||||
let drawn: Vec<Drawn> = drawn.iter().map(|d| drawn_as(d).expect("bounds")).collect();
|
||||
how_far(laid, &drawn, turned)
|
||||
};
|
||||
let laid = [square(0.0), square(50.0)];
|
||||
let c = |x: f64| (Point::new(x + 5.0, 5.0), Fill::None);
|
||||
assert!(how_far(&laid, &[c(0.0), c(50.0)]).is_some());
|
||||
assert!(how_far(&laid, &[c(0.0), c(0.1)]).is_none(), "both drawn steps near the first laid one");
|
||||
assert!(check(&laid, &[square(0.0), square(50.0)], true).is_some());
|
||||
assert!(check(&laid, &[square(0.0), square(0.1)], false).is_none(), "both drawn steps near the first laid one");
|
||||
// Sizes and outlines count only when asked for: a wider rectangle with the same center, and
|
||||
// a triangle turned a half turn.
|
||||
let wide = |x: f64| {
|
||||
let path = vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(x - 5.0, 2.5, x + 15.0, 7.5));
|
||||
Node::path(NodeId(0), path, Default::default())
|
||||
};
|
||||
assert!(check(&laid, &[wide(0.0), wide(50.0)], false).is_some());
|
||||
assert!(check(&laid, &[wide(0.0), wide(50.0)], true).is_none());
|
||||
// Steps on one center match by their size, in whichever order they are drawn.
|
||||
let big = |x: f64| {
|
||||
let path = vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(x - 5.0, -5.0, x + 15.0, 15.0));
|
||||
Node::path(NodeId(0), path, Default::default())
|
||||
};
|
||||
assert!(check(&[square(0.0), big(0.0)], &[big(0.0), square(0.0)], true).is_some());
|
||||
// A group's members in close reds match in whichever order they are drawn.
|
||||
let reds = |x: f64, order: [usize; 3]| {
|
||||
let member = |k: usize| {
|
||||
let left = x + k as f64 * 10.0;
|
||||
let path = vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(left, 0.0, left + 8.0, 8.0));
|
||||
let red = [0.25, 0.265, 0.28].get(k).copied().unwrap_or(0.0);
|
||||
Arc::new(Node::path(NodeId(0), path, vectorcraft_doc::Appearance::basic(Paint::solid(Color::rgb(red, 0.0, 0.0)), Paint::None, 0.0)))
|
||||
};
|
||||
Node::group(NodeId(0), order.iter().map(|k| member(*k)).collect())
|
||||
};
|
||||
assert!(check(&[reds(0.0, [0, 1, 2]), reds(50.0, [0, 1, 2])], &[reds(0.0, [1, 0, 2]), reds(50.0, [1, 0, 2])], true).is_some());
|
||||
// A triangle turned a half turn has its anchors elsewhere.
|
||||
let polygon = |points: &[Point]| Node::path(NodeId(0), PathData::single(SubPath::polyline(points, true)), Default::default());
|
||||
let triangle = |x: f64, turn: f64| {
|
||||
let mut n = polygon(&[Point::new(x, 0.0), Point::new(x, 10.0), Point::new(x + 10.0, 5.0)]);
|
||||
n.transform(vectorcraft_geom::Affine::rotate_about(turn, Point::new(x + 5.0, 5.0)), false);
|
||||
n
|
||||
};
|
||||
let laid = [triangle(0.0, 0.0), triangle(50.0, 0.0)];
|
||||
let turned = |x: f64| triangle(x, std::f64::consts::PI);
|
||||
assert!(check(&laid, &[turned(0.0), turned(50.0)], false).is_some());
|
||||
assert!(check(&laid, &[turned(0.0), turned(50.0)], true).is_none());
|
||||
// So has one in a group, filled with a gradient, which the check compares by its outline.
|
||||
let graded = |x: f64, turn: f64| {
|
||||
let mut t = triangle(x, turn);
|
||||
let gradient = vectorcraft_color::gradient::GradientPaint::new(vectorcraft_color::gradient::Gradient::default());
|
||||
t.appearance.set_fill(Paint::Gradient(Box::new(gradient)));
|
||||
Node::group(NodeId(0), vec![Arc::new(t)])
|
||||
};
|
||||
let in_groups = [graded(0.0, 0.0), graded(50.0, 0.0)];
|
||||
assert!(check(&in_groups, &[graded(0.0, 0.0), graded(50.0, 0.0)], true).is_some());
|
||||
assert!(check(&in_groups, &[graded(0.0, std::f64::consts::PI), graded(50.0, std::f64::consts::PI)], true).is_none());
|
||||
// The same triangle drawn from another of its anchors matches.
|
||||
let shifted = |x: f64| polygon(&[Point::new(x + 10.0, 5.0), Point::new(x, 0.0), Point::new(x, 10.0)]);
|
||||
assert!(check(&laid, &[shifted(0.0), shifted(50.0)], true).is_some());
|
||||
// So does the same triangle drawn with another anchor on one of its sides.
|
||||
let split = |x: f64| polygon(&[Point::new(x, 0.0), Point::new(x, 5.0), Point::new(x, 10.0), Point::new(x + 10.0, 5.0)]);
|
||||
assert!(check(&laid, &[split(0.0), split(50.0)], true).is_some());
|
||||
// A square with its top side bent inward has the same corners as its half turn, whose bent
|
||||
// side is at the bottom: the points along its sides tell them apart.
|
||||
let bent = |x: f64, turn: f64| {
|
||||
let (tl, tr) = (Point::new(x, 0.0), Point::new(x + 10.0, 0.0));
|
||||
let anchors = vec![
|
||||
vectorcraft_geom::Anchor::with_handles(tl, tl, Point::new(x + 3.0, 4.0)),
|
||||
vectorcraft_geom::Anchor::with_handles(tr, Point::new(x + 7.0, 4.0), tr),
|
||||
vectorcraft_geom::Anchor::corner(Point::new(x + 10.0, 10.0)),
|
||||
vectorcraft_geom::Anchor::corner(Point::new(x, 10.0)),
|
||||
];
|
||||
let mut n = Node::path(NodeId(0), PathData::single(SubPath::new(anchors, true)), Default::default());
|
||||
n.transform(vectorcraft_geom::Affine::rotate_about(turn, Point::new(x + 5.0, 5.0)), false);
|
||||
n
|
||||
};
|
||||
let upright = [bent(0.0, 0.0), bent(50.0, 0.0)];
|
||||
assert!(check(&upright, &[bent(0.0, 0.0), bent(50.0, 0.0)], true).is_some());
|
||||
let half = std::f64::consts::PI;
|
||||
assert!(check(&upright, &[bent(0.0, half), bent(50.0, half)], false).is_some());
|
||||
assert!(check(&upright, &[bent(0.0, half), bent(50.0, half)], true).is_none(), "the bent side at the bottom");
|
||||
// Past the limit of outlines compared, the last object is still among them.
|
||||
let row = |last: Node| {
|
||||
let mut row: Vec<Node> = (0..MAX_OUTLINE_CHECKS).map(|i| square(20.0 * i as f64)).collect();
|
||||
row.push(last);
|
||||
row
|
||||
};
|
||||
let end = 20.0 * MAX_OUTLINE_CHECKS as f64;
|
||||
assert!(check(&row(bent(end, 0.0)), &row(bent(end, 0.0)), true).is_some());
|
||||
assert!(check(&row(bent(end, 0.0)), &row(bent(end, half)), true).is_none(), "the last one turned");
|
||||
// A hundred steps crowded within the tolerance of each other match their drawn copies:
|
||||
// each drawn one is compared with the nearest laid one first.
|
||||
let crowd = |turn: f64| (0..100u32).map(|i| triangle(0.4 * f64::from(i) / 99.0, turn)).collect::<Vec<_>>();
|
||||
assert!(check(&crowd(0.0), &crowd(0.0), true).is_some());
|
||||
assert!(check(&crowd(0.0), &crowd(half), true).is_none(), "the crowd turned");
|
||||
// A compound path matches with its contours in another order, and not turned a half turn.
|
||||
let pair = |x: f64, flip: bool, turn: f64| {
|
||||
let a = SubPath::polyline(&[Point::new(x, 0.0), Point::new(x, 4.0), Point::new(x + 10.0, 2.0)], true);
|
||||
let b = SubPath::polyline(&[Point::new(x, 6.0), Point::new(x, 10.0), Point::new(x + 4.0, 8.0)], true);
|
||||
let subpaths = if flip { vec![b, a] } else { vec![a, b] };
|
||||
let mut n = Node::path(NodeId(0), PathData::new(subpaths), Default::default());
|
||||
n.transform(vectorcraft_geom::Affine::rotate_about(turn, Point::new(x + 5.0, 5.0)), false);
|
||||
n
|
||||
};
|
||||
let laid = [pair(0.0, false, 0.0), pair(50.0, false, 0.0)];
|
||||
assert!(check(&laid, &[pair(0.0, true, 0.0), pair(50.0, true, 0.0)], true).is_some());
|
||||
assert!(check(&laid, &[pair(0.0, true, std::f64::consts::PI), pair(50.0, true, std::f64::consts::PI)], true).is_none());
|
||||
// A lone anchor in a path draws nothing: the same path with one matches itself.
|
||||
let dotted = |x: f64| {
|
||||
let triangle = SubPath::polyline(&[Point::new(x, 0.0), Point::new(x, 10.0), Point::new(x + 10.0, 5.0)], true);
|
||||
let dot = SubPath::polyline(&[Point::new(x + 3.0, 5.0)], false);
|
||||
Node::path(NodeId(0), PathData::new(vec![triangle, dot]), Default::default())
|
||||
};
|
||||
assert!(check(&[dotted(0.0), dotted(50.0)], &[dotted(0.0), dotted(50.0)], true).is_some());
|
||||
// A live blend draws more than its keys: one is compared with its drawn copy by size alone.
|
||||
let blend = |x: f64| {
|
||||
let keys = vec![Arc::new(triangle(x, 0.0)), Arc::new(triangle(x, 0.0))];
|
||||
Node::new(NodeId(0), NodeKind::Blend { children: keys, spec: Box::default() })
|
||||
};
|
||||
let expanded = |x: f64| {
|
||||
let inside = SubPath::polyline(&[Point::new(x + 3.0, 4.0), Point::new(x + 3.0, 6.0)], false);
|
||||
let inside = Node::path(NodeId(0), PathData::single(inside), Default::default());
|
||||
Node::group(NodeId(0), vec![Arc::new(triangle(x, 0.0)), Arc::new(inside)])
|
||||
};
|
||||
assert!(check(&[blend(0.0), blend(50.0)], &[expanded(0.0), expanded(50.0)], true).is_some());
|
||||
// Coordinates far out don't overflow the grid.
|
||||
let far = [square(1e300), square(-1e300)];
|
||||
let _ = how_far(&far, &[c(1e300), c(-1e300)]);
|
||||
let _ = check(&far, &[square(1e300), square(-1e300)], false);
|
||||
}
|
||||
|
||||
/// Triangles pointing right on a spine running right to left, with their steps drawn pointing
|
||||
/// right: Align to Path would turn each one (keys included) a half turn, which leaves their
|
||||
/// centers and sizes as they are but not their points. A record naming Align to Path doesn't
|
||||
/// make the blend Align to Path.
|
||||
#[test]
|
||||
fn the_records_orientation_must_lay_the_steps_out_turned_as_drawn() {
|
||||
let triangle = |id: u64, x: f64| {
|
||||
let points = [Point::new(x, 0.0), Point::new(x, 10.0), Point::new(x + 20.0, 5.0)];
|
||||
Arc::new(Node::path(NodeId(id), PathData::single(SubPath::polyline(&points, true)), Default::default()))
|
||||
};
|
||||
let spine = vectorcraft_geom::shapes::line(Point::new(110.0, 5.0), Point::new(10.0, 5.0));
|
||||
let spine = Arc::new(Node::path(NodeId(3), spine, Default::default()));
|
||||
let edit = Node::new(NodeId(10), NodeKind::Group { children: vec![triangle(1, 100.0), triangle(2, 0.0), spine], clip: false });
|
||||
let steps = (0..5u32).map(|i| triangle(20 + u64::from(i), 100.0 - f64::from(i) * 25.0)).collect();
|
||||
let drawn = Node::new(NodeId(11), NodeKind::Group { children: steps, clip: false });
|
||||
let roles = Roles::from([
|
||||
(NodeId(1), ("K".to_string(), Some("A".to_string()))),
|
||||
(NodeId(2), ("K".to_string(), Some("B".to_string()))),
|
||||
(NodeId(3), ("S".to_string(), None)),
|
||||
]);
|
||||
for named in [BlendOrientation::AlignToPath, BlendOrientation::AlignToPage] {
|
||||
let record = Record { ids: vec!["A".into(), "B".into()], spacing: None, orientation: Some(named) };
|
||||
let mut budget = 10;
|
||||
let Some(NodeKind::Blend { spec, .. }) = live_blend(&edit, &drawn, &record, &roles, &mut budget) else { panic!("a live blend") };
|
||||
assert_eq!(spec.orientation, BlendOrientation::AlignToPage, "{named:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Triangles pointing right on a spine 1 pt long running right to left, with 998 steps drawn
|
||||
/// unturned, so that every step sits within the tolerance of each one. Align to Path would turn
|
||||
/// each one to point left. A record naming Align to Path doesn't make the blend Align to Path,
|
||||
/// however many steps one step's place matches; a record naming Align to Page keeps it.
|
||||
#[test]
|
||||
fn the_records_orientation_is_checked_on_crowded_steps() {
|
||||
let triangle = |id: u64, x: f64| {
|
||||
let points = [Point::new(x, 0.0), Point::new(x, 10.0), Point::new(x + 20.0, 5.0)];
|
||||
Arc::new(Node::path(NodeId(id), PathData::single(SubPath::polyline(&points, true)), Default::default()))
|
||||
};
|
||||
let spine = vectorcraft_geom::shapes::line(Point::new(11.0, 5.0), Point::new(10.0, 5.0));
|
||||
let spine = Arc::new(Node::path(NodeId(3), spine, Default::default()));
|
||||
let edit = Node::new(NodeId(10), NodeKind::Group { children: vec![triangle(1, 1.0), triangle(2, 0.0), spine], clip: false });
|
||||
let steps = (0..1000u32).map(|i| triangle(20 + u64::from(i), 1.0 - f64::from(i) / 999.0)).collect();
|
||||
let drawn = Node::new(NodeId(11), NodeKind::Group { children: steps, clip: false });
|
||||
let roles = Roles::from([
|
||||
(NodeId(1), ("K".to_string(), Some("A".to_string()))),
|
||||
(NodeId(2), ("K".to_string(), Some("B".to_string()))),
|
||||
(NodeId(3), ("S".to_string(), None)),
|
||||
]);
|
||||
for named in [BlendOrientation::AlignToPath, BlendOrientation::AlignToPage] {
|
||||
let record = Record { ids: vec!["A".into(), "B".into()], spacing: None, orientation: Some(named) };
|
||||
let mut budget = MAX_BLEND_OBJECTS;
|
||||
let Some(NodeKind::Blend { spec, .. }) = live_blend(&edit, &drawn, &record, &roles, &mut budget) else { panic!("a live blend") };
|
||||
assert_eq!(spec.orientation, BlendOrientation::AlignToPage, "{named:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Groups of a red square on the left and a blue one on the right, on a spine running right to
|
||||
/// left, with their steps drawn unturned: Align to Path would give each a half turn, which keeps
|
||||
/// the group's outline but trades the squares' places. A record naming Align to Path doesn't make
|
||||
/// the blend Align to Path.
|
||||
#[test]
|
||||
fn the_records_orientation_must_keep_each_member_where_it_is_drawn() {
|
||||
let square = |id: u64, x: f64, color: Color| {
|
||||
let path = vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(x, 0.0, x + 10.0, 10.0));
|
||||
Arc::new(Node::path(NodeId(id), path, vectorcraft_doc::Appearance::basic(Paint::solid(color), Paint::None, 0.0)))
|
||||
};
|
||||
let pair = |id: u64, x: f64| {
|
||||
let children = vec![square(id * 10, x, Color::rgb(1.0, 0.0, 0.0)), square(id * 10 + 1, x + 10.0, Color::rgb(0.0, 0.0, 1.0))];
|
||||
Arc::new(Node::new(NodeId(id), NodeKind::Group { children, clip: false }))
|
||||
};
|
||||
let spine = vectorcraft_geom::shapes::line(Point::new(110.0, 5.0), Point::new(10.0, 5.0));
|
||||
let spine = Arc::new(Node::path(NodeId(3), spine, Default::default()));
|
||||
let edit = Node::new(NodeId(4), NodeKind::Group { children: vec![pair(1, 100.0), pair(2, 0.0), spine], clip: false });
|
||||
let steps = (0..5u32).map(|i| pair(30 + u64::from(i), 100.0 - f64::from(i) * 25.0)).collect();
|
||||
let drawn = Node::new(NodeId(5), NodeKind::Group { children: steps, clip: false });
|
||||
let roles = Roles::from([
|
||||
(NodeId(1), ("K".to_string(), Some("A".to_string()))),
|
||||
(NodeId(2), ("K".to_string(), Some("B".to_string()))),
|
||||
(NodeId(3), ("S".to_string(), None)),
|
||||
]);
|
||||
for named in [BlendOrientation::AlignToPath, BlendOrientation::AlignToPage] {
|
||||
let record = Record { ids: vec!["A".into(), "B".into()], spacing: None, orientation: Some(named) };
|
||||
let mut budget = 100;
|
||||
let Some(NodeKind::Blend { spec, .. }) = live_blend(&edit, &drawn, &record, &roles, &mut budget) else { panic!("a live blend") };
|
||||
assert_eq!(spec.orientation, BlendOrientation::AlignToPage, "{named:?}");
|
||||
}
|
||||
// Drawn turned, blue on the left: the blend is Align to Path, whichever orientation the
|
||||
// record names.
|
||||
let turned = |id: u64, x: f64| {
|
||||
let children = vec![square(id * 10, x, Color::rgb(0.0, 0.0, 1.0)), square(id * 10 + 1, x + 10.0, Color::rgb(1.0, 0.0, 0.0))];
|
||||
Arc::new(Node::new(NodeId(id), NodeKind::Group { children, clip: false }))
|
||||
};
|
||||
let steps = (0..5u32).map(|i| turned(30 + u64::from(i), 100.0 - f64::from(i) * 25.0)).collect();
|
||||
let drawn = Node::new(NodeId(5), NodeKind::Group { children: steps, clip: false });
|
||||
for named in [BlendOrientation::AlignToPath, BlendOrientation::AlignToPage] {
|
||||
let record = Record { ids: vec!["A".into(), "B".into()], spacing: None, orientation: Some(named) };
|
||||
let mut budget = 100;
|
||||
let Some(NodeKind::Blend { spec, .. }) = live_blend(&edit, &drawn, &record, &roles, &mut budget) else { panic!("a live blend") };
|
||||
assert_eq!(spec.orientation, BlendOrientation::AlignToPath, "{named:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Rectangles 20 pt wide and 10 pt high on a vertical spine, with their steps drawn upright: Align
|
||||
/// to Path would turn each one (keys included) a quarter turn, which leaves the centers in place
|
||||
/// but not the sizes. A record naming Align to Path doesn't make the blend Align to Path; a
|
||||
/// record naming Align to Page does.
|
||||
#[test]
|
||||
fn the_records_orientation_must_lay_the_steps_out_at_their_drawn_sizes() {
|
||||
let rect = |id: u64, y: f64| {
|
||||
let path = vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(0.0, y, 20.0, y + 10.0));
|
||||
Arc::new(Node::path(NodeId(id), path, Default::default()))
|
||||
};
|
||||
let spine = vectorcraft_geom::shapes::line(Point::new(10.0, 5.0), Point::new(10.0, 105.0));
|
||||
let spine = Arc::new(Node::path(NodeId(3), spine, Default::default()));
|
||||
let edit = Node::new(NodeId(10), NodeKind::Group { children: vec![rect(1, 0.0), rect(2, 100.0), spine], clip: false });
|
||||
let steps = (0..5u32).map(|i| rect(20 + u64::from(i), f64::from(i) * 25.0)).collect();
|
||||
let drawn = Node::new(NodeId(11), NodeKind::Group { children: steps, clip: false });
|
||||
let roles = Roles::from([
|
||||
(NodeId(1), ("K".to_string(), Some("A".to_string()))),
|
||||
(NodeId(2), ("K".to_string(), Some("B".to_string()))),
|
||||
(NodeId(3), ("S".to_string(), None)),
|
||||
]);
|
||||
for named in [BlendOrientation::AlignToPath, BlendOrientation::AlignToPage] {
|
||||
let record = Record { ids: vec!["A".into(), "B".into()], spacing: None, orientation: Some(named) };
|
||||
let mut budget = 10;
|
||||
let Some(NodeKind::Blend { spec, .. }) = live_blend(&edit, &drawn, &record, &roles, &mut budget) else { panic!("a live blend") };
|
||||
assert_eq!(spec.orientation, BlendOrientation::AlignToPage, "{named:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user