Merge main into the qualified Eraser group-stroke repair

This commit is contained in:
yoriswind
2026-11-17 17:40:53 -08:00
218 changed files with 8647 additions and 966 deletions
Generated
+74 -128
View File
@@ -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
View File
@@ -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" }
+1 -1
View File
@@ -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 }
+8 -7
View File
@@ -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!(
+1
View File
@@ -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()
}
+32 -5
View File
@@ -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, &note))
}
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"));
+4 -4
View File
@@ -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]
+2
View File
@@ -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 }
+3
View File
@@ -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
View File
@@ -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]
+36 -5
View File
@@ -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
View File
@@ -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;
}
+142
View File
@@ -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] {
+83 -8
View File
@@ -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
+6 -4
View File
@@ -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;
+7 -7
View File
@@ -96,13 +96,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,
+2 -2
View File
@@ -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)
}
+78 -5
View File
@@ -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();
+65
View File
@@ -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]
+1 -1
View File
@@ -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),
+21
View File
@@ -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());
+1 -1
View File
@@ -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,
+3 -1
View File
@@ -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 }
+95
View File
@@ -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)));
}
}
+1 -1
View File
@@ -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");
}
}
}
+24 -5
View File
@@ -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)")))?;
+2 -1
View File
@@ -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)
),
+72 -11
View File
@@ -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);
+1 -1
View File
@@ -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
),
+35 -15
View File
@@ -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> {
+5 -3
View File
@@ -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
+6 -11
View File
@@ -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
}
+44 -6
View File
@@ -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> {
+378 -47
View File
@@ -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;
+133 -14
View File
@@ -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");
}
+10 -6
View File
@@ -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),
})
}
+42
View File
@@ -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.
@@ -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.
+39 -1
View File
@@ -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.
+55 -9
View File
@@ -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());
}
}
+2 -2
View File
@@ -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.
+20 -2
View File
@@ -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);
+10 -2
View File
@@ -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`]).
+10 -2
View File
@@ -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
),
+11 -1
View File
@@ -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)) };
+30 -20
View File
@@ -664,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)?,
_ => {}
@@ -692,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)?;
@@ -798,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)?;
+1 -1
View File
@@ -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
),
+26 -5
View File
@@ -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",
]
);
}
}
+5 -12
View File
@@ -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)
}
+1 -1
View File
@@ -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)?;
+52 -7
View File
@@ -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 {
+20
View File
@@ -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(&center.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() {
+157
View File
@@ -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();
+69
View File
@@ -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();
+273
View File
@@ -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 {
+89
View File
@@ -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}");
}
}
+135
View File
@@ -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();
+81
View File
@@ -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]
+2 -2
View File
@@ -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();
+35
View File
@@ -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();
+4 -2
View File
@@ -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
+23 -1
View File
@@ -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()));
+88
View File
@@ -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)) {
@@ -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();
+14 -2
View File
@@ -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,13 @@
//! 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;
@@ -182,7 +191,9 @@
//! 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, blends the reader wouldn't read back live as
//! 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
@@ -328,6 +339,7 @@ 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;
File diff suppressed because it is too large Load Diff
+24 -5
View File
@@ -19,6 +19,7 @@ mod blends;
mod brushes;
mod envelopes;
mod images;
mod meshes;
mod paints;
mod styles;
mod symbols;
@@ -32,6 +33,8 @@ pub(super) use blends::unbaked_blends;
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};
@@ -62,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 = "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 =
@@ -308,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,
@@ -407,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,
@@ -739,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) {
@@ -754,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") {
@@ -856,9 +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::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::Mesh(_) | NodeKind::Repeat(_) | NodeKind::PlacedDocument(_) | NodeKind::Intertwine { .. } => {
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.
@@ -937,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;
@@ -1728,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;
+13 -4
View File
@@ -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| {
+256
View File
@@ -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,
}
}
+2 -2
View File
@@ -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.
+4 -2
View File
@@ -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))]))])
+8 -5
View File
@@ -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
+3 -3
View File
@@ -91,9 +91,9 @@ pub use ai::NameEncoding;
pub(crate) use ai::objects_read;
pub(crate) use ai::{
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_SYMBOLS, blend_reads,
brush_plugin_name, brushes_kept, envelope_outline, envelope_upright, read_art_style, read_brush_object, read_style_list, style_moves_with,
symbol_art_member, turn_brush_art_over, warp_number,
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};
+1
View File
@@ -47,6 +47,7 @@ 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)]
+99 -1
View File
@@ -25,7 +25,7 @@ const MAX_PATCHES: usize = 16_384;
const MAX_POINTS: usize = MAX_PATCHES * 16;
/// The largest grid `/Size` read as one mesh, a side.
const MAX_SIDE: usize = 128;
pub(crate) const MAX_SIDE: usize = 128;
/// The most inks of an `/NChannel` colour space read.
const MAX_INKS: usize = 32;
/// The most rows or columns a mesh stitched from its patches may have once the lines through the
@@ -556,6 +556,14 @@ impl Path {
/// `a` towards `b` by `t`, in their own colour model where they share one.
fn mix(a: &Color, b: &Color, t: f32) -> Color {
// At either end, that end's own color in its own model: a mesh point of a patch whose corners
// differ in model keeps its color.
if t <= 0.0 {
return *a;
}
if t >= 1.0 {
return *b;
}
let l = |x: f32, y: f32| x + (y - x) * t;
match (a, b) {
(Color::Rgb { r, g, b: bl }, Color::Rgb { r: r2, g: g2, b: b2 }) => Color::rgb(l(*r, *r2), l(*g, *g2), l(*bl, *b2)),
@@ -565,6 +573,51 @@ fn mix(a: &Color, b: &Color, t: f32) -> Color {
}
}
/// The most values one entry of [`mesh_reads`]' record holds (a corner of [`MAX_INKS`] inks has
/// 41).
const MAX_ENTRY: usize = 64;
/// The gradient mesh the reader reads from `record`, a mesh's lines (`/Mesh X!` … `/End X!`,
/// entries on `%_` lines or not), with `to_doc` taking art space to the document: one mesh, or
/// `None` where the reader would read none or a group of its patches.
pub(crate) fn mesh_reads(record: &[u8], to_doc: Affine) -> Option<GradientMesh> {
use super::lex::{Lexer, Tok};
let mut lex = Lexer::new(record);
let mut m: Option<MeshReader> = None;
let mut stack: Vec<V> = vec![];
let mut marks: Vec<usize> = vec![];
while let Some(t) = lex.next_token() {
match t.tok {
Tok::Num(v) => stack.push(V::Num(v)),
Tok::Name(n) => stack.push(V::Name(super::obj::text(n))),
Tok::Str(s) | Tok::Hex(s) => stack.push(V::Str(s)),
Tok::Word(b"[") => marks.push(stack.len()),
Tok::Word(b"]") => {
let at = marks.pop()?;
let items = stack.split_off(at.min(stack.len()));
stack.push(V::Arr(items));
}
Tok::Word(b"X!") => match (stack.last().and_then(V::text).as_deref(), m.take()) {
(Some("Mesh"), None) => m = Some(MeshReader::default()),
(Some("End"), Some(read)) => {
if read.unread || read.patches.is_empty() {
return None;
}
return read.one_mesh().ok();
}
_ => return None,
},
Tok::Word(b"X#") => m.as_mut()?.entry(&std::mem::take(&mut stack), to_doc),
Tok::Comment(_) => {}
_ => return None,
}
if stack.len() > MAX_ENTRY {
return None;
}
}
None
}
#[cfg(test)]
mod tests {
use super::*;
@@ -885,6 +938,51 @@ mod tests {
assert!(!reader.unread && reader.patches[0].points[0].color == Color::gray(1.0));
}
/// `/Version` and `/Data` entries, before or after the patches, are passed over: corners with
/// and without an opacity are read by their count of values either way.
#[test]
fn version_and_data_entries_are_passed_over() {
for (with_opacity, data_first) in [(true, true), (false, true), (true, false), (false, false)] {
let mut reader = MeshReader::default();
for (value, key) in [(V::Name("Cartesian".into()), "Type"), (nums(&[1.0, 1.0]), "Size")] {
reader.entry(&[value, V::Name(key.into())], Affine::IDENTITY);
}
if data_first {
reader.entry(&[V::Num(2.0), V::Name("Version".into())], Affine::IDENTITY);
reader.entry(&[V::Name("Data".into())], Affine::IDENTITY);
}
reader.entry(&[nums(&[0.0, 0.0]), V::Name("P".into())], Affine::IDENTITY);
let colors: [&[f64]; 4] =
if with_opacity { [&[0.5, 0.25], &[0.5, 0.25], &[0.5, 0.25], &[0.5, 0.25]] } else { [&[0.5], &[0.5], &[0.5], &[0.5]] };
square(&mut reader, colors, Default::default());
if !data_first {
reader.entry(&[V::Name("Data".into())], Affine::IDENTITY);
reader.entry(&[V::Num(1.0), V::Name("Version".into())], Affine::IDENTITY);
}
assert!(!reader.unread, "{with_opacity} {data_first}");
let mesh = reader.one_mesh().unwrap();
let want = if with_opacity { 0.25 } else { 1.0 };
assert!(mesh.points.iter().all(|p| p.opacity == want), "{with_opacity} {data_first}: {mesh:?}");
}
}
/// A patch whose corners differ in color space keeps each corner's color in its own model when
/// the patches are stitched into one mesh.
#[test]
fn stitched_corners_keep_their_own_color_models() {
let cs = |n: &str| (V::Name(n.into()), "CS");
let mut reader = MeshReader::default();
let first = vec![(nums(&[1.0, 1.0]), "Size"), (nums(&[0.0, 0.0]), "P"), cs("DeviceRGB")];
square(
&mut reader,
[&[1.0, 0.0, 0.0], &[0.25], &[0.0, 1.0, 0.0, 0.0], &[0.0, 0.0, 1.0]],
[first, vec![cs("DeviceGray")], vec![cs("DeviceCMYK")], vec![cs("DeviceRGB")]],
);
let mesh = reader.one_mesh().unwrap();
let colors: Vec<Color> = mesh.points.iter().map(|p| p.color).collect();
assert_eq!(colors, [Color::rgb(1.0, 0.0, 0.0), Color::rgb(0.0, 0.0, 1.0), Color::gray(0.75), Color::cmyk(0.0, 1.0, 0.0, 0.0)]);
}
/// A named colour (`[c m y k /DeviceCMYK (name) /Process]`) paints at each corner's tint, 1 its
/// full colour; `/NChannel` inks overprint at their tints. Ones that don't add up stay unread.
#[test]
+3 -1
View File
@@ -97,7 +97,9 @@
//! have is the object's own appearance, not a link.
//!
//! - Symbols: `%AI14_BeginSymbol` (or `%AI10_`), `(name)`, `0 A 0 Xw 0 Ae`, the art (in the
//! symbol's space, y down), a dictionary whose `AI13PatternRegistrationType` is the registration
//! symbol's space, y down; an image's matrix and a gradient mesh's corners in the canvas's space
//! turned y up about art space's origin there, an envelope's contents in its dictionary in the
//! canvas's space, y down), a dictionary whose `AI13PatternRegistrationType` is the registration
//! point (1 to 9, from the top left, row by row), `%AI10_EndSymbol`; each is read by a reader of
//! its own into the document's symbols. `%AI24_BeginSymbolList` (or `%AI10_`) lists their names
//! in the Symbols panel's order. An instance: `/SymbolInstance : (name) /SymbolRef , a b c d tx
+17 -1
View File
@@ -277,6 +277,18 @@ impl<'a> Reader<'a> {
Ok(())
}
/// A gradient mesh's `X#` entry `vals`. In a symbol's art, corners are in the space an image's
/// matrix is in there; a mesh there in a file that doesn't say where the canvas is is unread.
pub(super) fn mesh_entry(&mut self, vals: &[V]) {
let to_doc = self.image_space();
if let Some((m, _)) = self.mesh.as_mut() {
match to_doc {
Some(to_doc) => m.entry(vals, to_doc),
None => m.unread = true,
}
}
}
/// `/End X!`: the gradient mesh read, as one object.
pub(super) fn end_mesh(&mut self) -> Result<(), String> {
let Some((m, hidden)) = self.mesh.take() else { return Ok(()) };
@@ -351,11 +363,15 @@ impl<'a> Reader<'a> {
pub(super) fn set_instance(&mut self, i: &Instance) {
let mut to_doc = self.space();
// In a pattern's definition a gradient's `Xm` and `Bm` are written y down about the canvas point of art space's
// origin, as the file's PDF part draws them; in a symbol's, as the instances in its art are.
// origin, as the file's PDF part draws them; in a symbol's, as the instances in its art are, an envelope's
// contents' included (which `space` moves alone).
if (self.pattern.is_some() || self.symbol.is_some())
&& i.has_matrix()
&& let Some(t) = self.template
{
if self.pattern.is_none() && !self.envelope_blocks.is_empty() {
to_doc = Affine::IDENTITY;
}
let (cx, cy) = ((t[0] + t[2]) / 2.0, (t[1] + t[3]) / 2.0);
to_doc *= Affine::new([1.0, 0.0, 0.0, -1.0, CANVAS_CENTRE - cx, CANVAS_CENTRE + cy]);
}
+7 -2
View File
@@ -923,12 +923,17 @@ impl<'a> Reader<'a> {
}
/// Art space → where the art being read goes: the document, or while a pattern's definition is
/// read, the pattern's space (y down). A symbol's definition is written in the symbol's space.
/// read, the pattern's space (y down). A symbol's definition is written in the symbol's space,
/// except an envelope's contents in its dictionary (its `AIDeformArtKey` block), which are in the
/// canvas's space, y down (in the symbol's space in a file without a template box).
pub(crate) fn space(&mut self) -> Affine {
if self.pattern.is_some() {
FLIP
} else if self.symbol.is_some() {
Affine::IDENTITY
match self.canvas_origin() {
Some(o) if !self.envelope_blocks.is_empty() => Affine::translate(-o.to_vec2()),
_ => Affine::IDENTITY,
}
} else {
self.ensure_space()
}
+54 -17
View File
@@ -226,10 +226,7 @@ impl<'a> Reader<'a> {
}
("X!", Some("End")) if self.mesh.is_some() => return self.end_mesh(),
("X#", _) => {
let to_doc = self.space();
if let Some((m, _)) = self.mesh.as_mut() {
m.entry(&vals, to_doc);
}
self.mesh_entry(&vals);
return Ok(());
}
_ if self.mesh.is_some() => return Ok(()),
@@ -1129,13 +1126,47 @@ fn no_guides(n: &Node, depth: usize) -> bool {
depth <= MAX_DEPTH && !n.is_guide() && n.children().into_iter().flatten().all(|c| no_guides(c, depth + 1))
}
/// Is `n` a compound path with a guide member whose bounds reach past the bounds of its members that
/// aren't guides, or with guide members only? Any other object counts as no.
/// Is `n` a compound path or group with a guide in it whose bounds reach past the bounds of the rest
/// of its art, or with guides only? Members are looked into to [`MAX_DEPTH`]; deeper counts as yes.
/// Any other object counts as no.
fn guides_reach_past(n: &Node) -> bool {
let NodeKind::Compound { children, .. } = &n.kind else { return false };
let bounds =
|guides: bool| children.iter().filter(|c| c.is_guide() == guides).fold(None, |acc, c| vectorcraft_geom::union_opt(acc, c.geometric_bounds()));
bounds(true).is_some_and(|g| bounds(false).is_none_or(|o| o.union(g) != o))
/// Adds the bounds of the guides in `n`'s members to `guides` and of the rest to `art`; false when
/// it is deeper than [`MAX_DEPTH`].
fn split(n: &Node, depth: usize, guides: &mut Option<Rect>, art: &mut Option<Rect>) -> bool {
depth <= MAX_DEPTH
&& n.children().into_iter().flatten().all(|c| match c.children() {
_ if c.is_guide() => {
*guides = vectorcraft_geom::union_opt(*guides, c.geometric_bounds());
true
}
Some(_) => split(c, depth + 1, guides, art),
None => {
*art = vectorcraft_geom::union_opt(*art, c.geometric_bounds());
true
}
})
}
if !matches!(n.kind, NodeKind::Compound { .. } | NodeKind::Group { .. }) {
return false;
}
let (mut guides, mut art) = (None, None);
!split(n, 0, &mut guides, &mut art) || guides.is_some_and(|g| art.is_none_or(|o| o.union(g) != o))
}
/// Do Transform params `p` scale, turn or reflect, so that where the object's bounds lie changes
/// what they draw? Moving alone doesn't.
fn transform_measures(p: &serde_json::Value) -> bool {
p["scaleH"].as_f64() != Some(100.0)
|| p["scaleV"].as_f64() != Some(100.0)
|| p["rotate"].as_f64() != Some(0.0)
|| p["reflectX"].as_bool() != Some(false)
|| p["reflectY"].as_bool() != Some(false)
}
/// Do Free Distort params `p` move a corner of the box, so that where the object's bounds lie
/// changes what they draw?
fn free_distort_measures(p: &serde_json::Value) -> bool {
p["corners"] != serde_json::json!([[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]])
}
/// The largest Twist angle, in degrees either way, read as a live effect on an object that isn't a
@@ -1154,7 +1185,11 @@ const MAX_STRAIGHT_TWIST: f64 = 180.0;
/// compound path with straight segments (only at 0° when its guide members reach past its other
/// members, see [`guides_reach_past`]), or up to [`MAX_TWIST`] degrees either way on another object
/// with no guide in it. Transform that scales, turns or reflects is read only when nothing is stroked
/// (its reference point lies on the bounds without strokes).
/// (its reference point lies on the bounds without strokes) and, unless Transform Objects is off,
/// no guide reaches past the rest of the object's art ([`guides_reach_past`]). Free Distort that
/// moves a corner of a group is read only when no guide in the group reaches past the rest of its
/// art. The live effect is measured from bounds that take in the guides, so such an object keeps
/// its drawn look.
fn moves_with(object: &Node, st: &crate::import::ai::style::ArtStyle) -> bool {
use crate::import::ai::style::StyleItem;
let stroked = st.items.iter().any(|i| matches!(i, StyleItem::Stroke { paint, .. } if !paint.is_none()))
@@ -1174,12 +1209,14 @@ fn moves_with(object: &Node, st: &crate::import::ai::style::ArtStyle) -> bool {
}
"distort.transform" => {
let p = &e.params;
!stroked
|| (p["scaleH"].as_f64() == Some(100.0)
&& p["scaleV"].as_f64() == Some(100.0)
&& p["rotate"].as_f64() == Some(0.0)
&& p["reflectX"].as_bool() == Some(false)
&& p["reflectY"].as_bool() == Some(false))
// With Transform Objects off, nothing is placed from the bounds: a style read here and
// the object's members paint with no pattern for Transform Patterns to move (`simple`,
// `moves_alike`).
let placed = p["objects"].as_bool() != Some(false);
!transform_measures(p) || (!stroked && (!placed || !guides_reach_past(object)))
}
"distort.freeDistort" => {
!matches!(object.kind, NodeKind::Group { .. }) || !free_distort_measures(&e.params) || !guides_reach_past(object)
}
_ => true,
})
+142
View File
@@ -5251,6 +5251,62 @@ fn an_image_in_a_symbols_art_is_placed_from_the_canvas() {
assert_eq!(r.unread.len(), 1, "{:?}", r.warnings);
}
#[test]
fn a_mesh_in_a_symbols_art_is_placed_from_the_canvas() {
// The template box's center is (100.5, 50.5): art space's origin is at canvas (8091, 8242). A
// mesh's corners in a symbol's art are in the canvas's space turned y up about that point, as an
// image's matrix there is: (-8096, 8244.5) is (-5, -2.5) in the symbol's art.
let corners: String = [(-8096.0, 8244.5), (-8096.0, 8239.5), (-8086.0, 8239.5), (-8086.0, 8244.5)]
.iter()
.map(|(x, y)| format!("%_[0.5 1 {x} {y} {x} {y} 1 {x} {y} 1] /N X#\n"))
.collect();
let mesh = format!(
"/Mesh X!\n%_2 /Version X#\n%_/Cartesian /Type X#\n%_[1 1] /Size X#\n%_/Data X#\n%_[0 0] /P X#\n%_/DeviceGray /CS X#\n{corners}%_/E X#\n/End X!\n"
);
let doc = read_ok(&format!("%AI3_TemplateBox: 100.5 50.5 100.5 50.5\n{}{}", symbols(&symbol("Patch", &mesh, 5)), layer(""))).doc;
assert_eq!(doc.symbols.len(), 1);
let mut found = vec![];
let mut stack = vec![doc.symbols[0].art.clone()];
while let Some(n) = stack.pop() {
match &n.kind {
NodeKind::Mesh(m) => found.push(m.points.iter().map(|p| p.p).collect::<Vec<_>>()),
_ => stack.extend(n.children().into_iter().flatten().cloned()),
}
}
assert_eq!(found.len(), 1, "{:?}", doc.symbols[0].art);
let want = [Point::new(-5.0, -2.5), Point::new(5.0, -2.5), Point::new(-5.0, 2.5), Point::new(5.0, 2.5)];
assert!(want.iter().all(|w| found[0].iter().any(|p| (*p - *w).hypot() < 1e-9)), "{:?}", found[0]);
// Without a template box the mesh can't be placed, as an image there can't: the symbol isn't read
// whole and its instance comes in as the page draws it.
let group = format!("0 Ae\nu\n{}{RED}{}f\nU\n", instance("Patch", [1.0, 0.0, 0.0, -1.0, 20.0, 50.0]), rect_path(10.0, 0.0, 14.0, 4.0));
let r = read_ok(&(symbols(&symbol("Patch", &mesh, 5)) + &layer(&group)));
assert!(r.doc.symbols.is_empty(), "{:?}", r.doc.symbols.iter().map(|s| &s.name).collect::<Vec<_>>());
assert!(!r.unread.is_empty(), "{:?}", r.warnings);
}
#[test]
fn an_envelope_in_a_symbols_art_is_read_from_the_canvas() {
// An envelope's grid in a symbol's art is read in the space a gradient mesh's corners are read
// in there. A grid and contents written in the symbol's own space, as earlier VectorCraft builds
// wrote them, don't meet there: the envelope opens as the art it draws.
let drawn = format!("{RED}{}f\n", rect_path(30.0, 10.0, 170.0, 90.0));
let env = envelope_of(&straight_mesh(1, 1, (120.0, 60.0)), ENVELOPE_KEYS, &envelope_content(), 2, &drawn);
let doc = read_ok(&format!("%AI3_TemplateBox: 100.5 50.5 100.5 50.5\n{}{}", symbols(&symbol("Bent", &env, 5)), layer(""))).doc;
assert_eq!(doc.symbols.len(), 1);
let mut envelopes = 0;
doc.symbols[0].art.walk(&mut |n| envelopes += usize::from(matches!(n.kind, NodeKind::Envelope { .. })));
assert_eq!(envelopes, 0, "{:?}", doc.symbols[0].art);
let mut paths = 0;
doc.symbols[0].art.walk(&mut |n| paths += usize::from(matches!(n.kind, NodeKind::Path { .. })));
assert!(paths > 0, "{:?}", doc.symbols[0].art);
// Without a template box the grid can't be placed, as a gradient mesh there can't: the symbol
// isn't read whole and its instance comes in as the page draws it.
let group = format!("0 Ae\nu\n{}{RED}{}f\nU\n", instance("Bent", [1.0, 0.0, 0.0, -1.0, 20.0, 50.0]), rect_path(10.0, 0.0, 14.0, 4.0));
let r = read_ok(&(symbols(&symbol("Bent", &env, 5)) + &layer(&group)));
assert!(r.doc.symbols.is_empty(), "{:?}", r.doc.symbols.iter().map(|s| &s.name).collect::<Vec<_>>());
assert!(!r.unread.is_empty(), "{:?}", r.warnings);
}
#[test]
fn an_instance_keeps_its_hide_lock_transparency_and_clip() {
let m = [1.0, 0.0, 0.0, -1.0, 20.0, 50.0];
@@ -7495,6 +7551,92 @@ fn twist_is_read_on_straight_paths_and_compound_paths_up_to_half_a_turn() {
}
}
#[test]
fn transform_and_free_distort_keep_the_drawn_look_where_a_guide_reaches_past_the_rest_of_the_art() {
// GUARDS: a compound path or group whose guides reach past the rest of its art was read with a
// live Transform that scales, turns or reflects (or, on a group, a live Free Distort) measured from
// bounds that take in those guides. Such an object keeps its drawn look.
let hide = |s: String| s.replace('\n', "\n%_");
// A compound path of a square and `rest`, under its drawn look.
let compound = |rest: &str| {
format!(
"0 Ae\nu\n{RED}{}f\nU\n%_Bb\n%_{}0 BB\n1 (Bent) XW\n",
rect_path(16.0, 16.0, 64.0, 54.0),
hide(format!("*u\n{}f\n{rest}*U\n", rect_path(20.0, 20.0, 60.0, 50.0)))
)
};
// A group of a red square and `rest`, under its drawn look.
let group = |rest: &str| {
format!(
"0 Ae\nu\n{RED}{}f\nU\n%_0 Ae\n%_u\n%_{}U\n1 (Bent) XW\n",
rect_path(16.0, 16.0, 64.0, 54.0),
hide(format!("{RED}{}f\n{rest}", rect_path(20.0, 20.0, 60.0, 50.0)))
)
};
let guide = |from: (f64, f64), to: (f64, f64)| format!("{} {} m\n{} {} L\n(N) *\n", from.0, from.1, to.0, to.1);
let inside = guide((25.0, 25.0), (35.0, 35.0));
let past = guide((30.0, 30.0), (70.0, 40.0));
let nested = format!("0 Ae\nu\n{past}U\n");
let transform = |keys: &str| format!("{keys}0 /Bool (transformPatterns) ,\n");
let scale = transform("0.5 /Real (scaleH_Factor) ,\n0.5 /Real (scaleV_Factor) ,\n0 /Bool (scaleLines) ,\n");
let turn = transform("0.5 /Real (rotate_Radians) ,\n");
let reflect = transform("1 /Bool (reflectX) ,\n");
let moved = transform("5 /Real (moveH_Pts) ,\n");
let scale_in_place = transform("0.5 /Real (scaleH_Factor) ,\n0 /Bool (scaleLines) ,\n0 /Bool (transformObjects) ,\n");
// Transform Objects off and Transform Patterns on: only a pattern moves, and a solid fill has none.
let scale_patterns = "0.5 /Real (scaleH_Factor) ,\n0 /Bool (scaleLines) ,\n0 /Bool (transformObjects) ,\n1 /Bool (transformPatterns) ,\n";
let slanted = free_distort_keys([[25.0, 50.0], [65.0, 50.0], [20.0, 20.0], [60.0, 20.0]]);
let read = |name: &str, keys: &str, paint, art_: &str| read_ok(&format!("{}{}", distort_styles(name, keys, paint), layer(art_)));
let tr = "Adobe Transform";
let fd = "Adobe Free Distort";
for (what, r, id) in [
("a compound path scaled, its guide inside", read(tr, &scale, BLUE_FILL, &compound(&inside)), "distort.transform"),
("a compound path moved, its guide past", read(tr, &moved, BLUE_FILL, &compound(&past)), "distort.transform"),
("a compound path distorted, its guide past", read(fd, &slanted, BLUE_FILL, &compound(&past)), "distort.freeDistort"),
("a group scaled, its guide inside", read(tr, &scale, None, &group(&inside)), "distort.transform"),
("a group moved, its guide past", read(tr, &moved, None, &group(&past)), "distort.transform"),
("a group scaled with Transform Objects off, its guide past", read(tr, &scale_in_place, None, &group(&past)), "distort.transform"),
(
"a compound path scaled with Transform Objects off and Transform Patterns on, its guide past",
read(tr, scale_patterns, BLUE_FILL, &compound(&past)),
"distort.transform",
),
("a group distorted, its guide inside", read(fd, &slanted, None, &group(&inside)), "distort.freeDistort"),
("a group distorted with no corner moved, its guide past", read(fd, "", None, &group(&past)), "distort.freeDistort"),
// A hidden member is measured too, and this one takes in the guide.
(
"a group scaled, its guide past the square and inside a hidden member",
read(tr, &scale, None, &group(&format!("1 Xw\n{RED}{}f\n0 Xw\n{past}", rect_path(10.0, 10.0, 80.0, 60.0)))),
"distort.transform",
),
] {
assert!(!r.warnings.iter().any(|w| w.contains("drawn look")), "{what}: {:?}", r.warnings);
let a = art(&r.doc);
assert_eq!(a.len(), 1, "{what}: {a:#?}");
assert!(a[0].children().map_or(0, |c| c.len()) >= 2, "{what}: the object, not its look: {a:#?}");
let [e] = a[0].appearance.effects.as_slice() else { panic!("{what}: {:?}", a[0].appearance) };
assert_eq!(e.id, id, "{what}");
}
for (what, r) in [
("a compound path scaled, its guide past", read(tr, &scale, BLUE_FILL, &compound(&past))),
("a compound path turned, its guide past", read(tr, &turn, BLUE_FILL, &compound(&past))),
("a compound path reflected, its guide past", read(tr, &reflect, BLUE_FILL, &compound(&past))),
("a group scaled, its guide past", read(tr, &scale, None, &group(&past))),
("a group turned, its guide past", read(tr, &turn, None, &group(&past))),
("a group distorted, its guide past", read(fd, &slanted, None, &group(&past))),
("a group scaled, its guide past in a group in it", read(tr, &scale, None, &group(&nested))),
(
"a group scaled, its guide past in a compound path in it",
read(tr, &scale, None, &group(&format!("*u\n{RED}{}f\n{past}*U\n", rect_path(25.0, 25.0, 35.0, 35.0)))),
),
] {
let a = art(&r.doc);
assert_eq!(a.len(), 1, "{what}: {a:#?}");
assert!(a[0].appearance.effects.is_empty(), "{what}: the drawn look: {a:#?}");
assert!(r.warnings.iter().any(|w| w.contains("drawn look")), "{what}: {:?}", r.warnings);
}
}
#[test]
fn twist_on_a_straight_compound_path_keeps_the_drawn_look_where_a_guide_reaches_past_its_other_members() {
// GUARDS: a straight compound path whose guide members reach past its other members was read
+1
View File
@@ -122,6 +122,7 @@ const DIAMOND: &str = "diamond gradients are written as four linear gradients cl
const SPREAD: &str = "gradients that repeat or reflect are written with their stops repeated across the shape (legacy .ai gradients only pad)";
const SPREAD_CAPPED: &str = "gradients that repeat or reflect are written with at most 256 stops; they pad past those";
const HUE_STOPS: &str = "gradients mixed around the hue wheel are written in process colors, with the colors between their stops as stops of their own (at most 256; legacy .ai gradients mix their stops' colors directly)";
const PERCEPTUAL_STOPS: &str = "Perceptual gradients are written in process colors, with the colors between their stops as stops of their own (at most 256; legacy .ai gradients mix their stops' colors directly)";
/// Wedges a conic gradient is written as: one a degree.
const CONIC_WEDGES: usize = 360;
const STROKES: &str =
+132
View File
@@ -272,6 +272,81 @@ fn hue_wheel_gradients_are_written_with_the_stops_on_their_curve() {
}
}
/// The written definition of the gradient named `name` in `text`, and how many stops it holds.
fn definition<'a>(text: &'a str, name: &str) -> (&'a str, usize) {
let def = text.split(&format!("%AI5_BeginGradient: ({name})\n")).nth(1).and_then(|d| d.split("%AI5_EndGradient").next()).unwrap();
(def, def.matches(" %_Bs\n").count())
}
/// The format's gradients mix their stops' colors directly: a Perceptual gradient is written in
/// process colors with the colors on its curve as stops, no more than the reader reads, in a
/// definition of its own rather than its swatch's, with a warning, and opens with the colors it
/// had. A Classic gradient keeps its own stops and gives no warning.
#[test]
fn perceptual_gradients_are_written_with_the_stops_on_their_curve() {
use vectorcraft_color::{GradientMethod, Swatch};
let mut doc = Document::new(200.0, 100.0);
for (name, color) in [("Night", Color::cmyk(1.0, 1.0, 0.0, 0.0)), ("Sun", Color::cmyk(0.0, 0.0, 1.0, 0.0))] {
doc.swatches.push(Swatch { name: name.into(), paint: Paint::solid(color), global: true, spot: true });
}
let stop = |offset: f32, color: Color, swatch: &str| GradientStop { swatch: Some(swatch.into()), ..GradientStop::new(offset, color) };
let stops = vec![stop(0.0, Color::cmyk(1.0, 1.0, 0.0, 0.0), "Night"), stop(1.0, Color::cmyk(0.0, 0.0, 1.0, 0.0), "Sun")];
let mut g = GradientPaint::new(Gradient { method: GradientMethod::Perceptual, ..Gradient::new(GradientKind::Linear, stops) });
g.swatch = Some("Dusk".into());
let want = g.gradient.clone();
// The same stops mixed directly stray from the Perceptual curve, so a file holding only the
// two stops would not open with the colors it had.
let classic = Gradient { method: GradientMethod::Classic, ..want.clone() };
assert!(
(0..=100).any(|k| {
let t = k as f32 / 100.0;
want.sample(t).0.to_rgb().iter().zip(classic.sample(t).0.to_rgb()).any(|(a, b)| (a - b).abs() > 0.05)
}),
"the methods mix alike"
);
let n = shape(&mut doc, shapes::rectangle(Rect::new(20.0, 10.0, 180.0, 90.0)), Paint::Gradient(Box::new(g)), Paint::None);
let l = doc.layers[0].id;
doc.insert(Some(l), 0, n).unwrap();
let out = write(&doc);
assert!(out.warnings.iter().any(|w| w == PERCEPTUAL_STOPS), "{:?}", out.warnings);
assert!(!out.warnings.iter().any(|w| w == HUE_STOPS), "{:?}", out.warnings);
let text = String::from_utf8_lossy(&out.bytes).into_owned();
assert!(!text.contains("(Dusk)"), "the curve is not the swatch's gradient");
assert!(!text.contains("(Night)") && !text.contains("(Sun)"), "the stops are process colors: {text}");
let (_, written) = definition(&text, "Gradient");
assert!((3..=crate::import::MAX_GRADIENT_STOPS).contains(&written), "{written} stops");
let read = crate::import(&out.bytes).unwrap().document;
let mut back = None;
read.walk(|n| {
if let (None, Paint::Gradient(g)) = (&back, n.appearance.fill_paint()) {
back = Some(g.gradient.clone());
}
});
let back = back.unwrap();
assert!(back.method.is_classic());
assert_eq!(back.stops.len(), written, "every stop written is read");
assert!(back.stops.iter().all(|s| s.swatch.is_none()), "{:?}", back.stops);
for k in 0..=100 {
let t = k as f32 / 100.0;
let (a, b) = (want.sample(t).0.to_rgb(), back.sample(t).0.to_rgb());
assert!(a.iter().zip(b).all(|(x, y)| (x - y).abs() < 0.03), "at {t}: {a:?} vs {b:?}");
}
// Classic: its own two stops, its spot colors and its swatch's name, without the warning.
let mut doc = Document::new(200.0, 100.0);
doc.swatches.push(Swatch { name: "Night".into(), paint: Paint::solid(Color::cmyk(1.0, 1.0, 0.0, 0.0)), global: true, spot: true });
let mut g = GradientPaint::new(classic);
g.swatch = Some("Dusk".into());
let n = shape(&mut doc, shapes::rectangle(Rect::new(20.0, 10.0, 180.0, 90.0)), Paint::Gradient(Box::new(g)), Paint::None);
let l = doc.layers[0].id;
doc.insert(Some(l), 0, n).unwrap();
let out = write(&doc);
assert!(!out.warnings.iter().any(|w| w == PERCEPTUAL_STOPS), "{:?}", out.warnings);
let text = String::from_utf8_lossy(&out.bytes).into_owned();
assert_eq!(definition(&text, "Dusk").1, 2);
assert!(text.contains("%%DocumentCustomColors: (Night)"), "{text}");
}
/// A radial gradient repeated out from a center far from the shape is written with its ramp points
/// (percent) to five decimals, so its runs keep their places hundreds of runs out.
#[test]
@@ -1075,6 +1150,63 @@ fn rgb_stops_are_written_again_unchanged() {
assert_eq!(again, first);
}
/// With a working RGB space other than sRGB, a Lab fill and a freeform gradient's average color
/// are written as RGB values in the working RGB space, so they read back as RGB colors that show as
/// the colors they were written for.
#[test]
fn a_lab_fill_reads_back_as_the_same_color_in_a_wide_gamut_working_space() {
const CHILD: &str = "VECTORCRAFT_TEST_LEGACY_AI_WIDE_GAMUT_LAB";
if std::env::var_os(CHILD).is_none() {
// Color settings are process-wide: exercise this profile in a separate test process.
let output = std::process::Command::new(std::env::current_exe().unwrap())
.args(["--exact", "legacy_ai::tests::a_lab_fill_reads_back_as_the_same_color_in_a_wide_gamut_working_space", "--nocapture"])
.env(CHILD, "1")
.output()
.unwrap();
let stdout = String::from_utf8_lossy(&output.stdout);
assert!(
output.status.success() && stdout.contains("test result: ok. 1 passed; 0 failed;"),
"isolated color profile test failed:\n{stdout}\n{}",
String::from_utf8_lossy(&output.stderr),
);
return;
}
use vectorcraft_color::cms;
cms::set_active(&cms::ColorSettings { rgb: cms::WIDE_GAMUT_RGB.into(), ..Default::default() }).unwrap();
assert!(!cms::active().rgb_is_srgb());
let lab = Color::lab(60.0, 20.0, -30.0);
let mut doc = Document::new(100.0, 100.0);
let n = shape(&mut doc, shapes::rectangle(Rect::new(10.0, 10.0, 50.0, 50.0)), Paint::solid(lab), Paint::None);
let layer = doc.layers[0].id;
doc.insert(Some(layer), usize::MAX, n).unwrap();
// A freeform gradient is written as the average of its stops' display colors.
let (a, b) = (Color::rgb(0.9, 0.2, 0.1), Color::lab(50.0, -40.0, -20.0));
let stops = vec![GradientStop::new(0.0, a), GradientStop::new(1.0, b)];
let free = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Freeform, stops))));
let n = shape(&mut doc, shapes::rectangle(Rect::new(60.0, 10.0, 90.0, 50.0)), free, Paint::None);
doc.insert(Some(layer), usize::MAX, n).unwrap();
let average = {
let (a, b) = (a.to_rgb(), b.to_rgb());
[0, 1, 2].map(|i| (a[i] + b[i]) / 2.0)
};
// Written without [`write`]'s printed comparison, which paints a gradient in its first stop's
// color and not in the average color the writer writes for a freeform gradient.
let back = crate::import(&export_legacy_ai(&doc, &LegacyAiOptions::default()).unwrap().bytes).unwrap().document;
let mut read = vec![];
back.walk(|n| {
if let NodeKind::Path { .. } = n.kind {
read.push(n.appearance.fill_paint());
}
});
let [Paint::Solid { color: got @ Color::Rgb { .. }, .. }, Paint::Solid { color: avg @ Color::Rgb { .. }, .. }] = read.as_slice() else {
panic!("two RGB fills: {read:?}")
};
for (got, w, what) in [(got, lab.to_rgb(), "Lab fill"), (avg, average, "freeform gradient's average")] {
let g = got.to_rgb();
assert!(g.iter().zip(w).all(|(a, b)| (a - b).abs() < 2e-3), "{what} {got:?} shows as {g:?}, not {w:?}");
}
}
/// A gradient from white to #1b2a6b, the colors of #2687's circle, placed at `geom` (None: fitted
/// to the object).
fn white_to_navy(kind: GradientKind, geom: Option<vectorcraft_color::GradientGeom>) -> Paint {
+7 -10
View File
@@ -9,7 +9,7 @@ use super::{
ROTATED_TYPE, Rect, STROKES, SUBLAYERS, Shape, StrokeLayer, SubPath, TITLE_AND_COLOR_NAMES, TRANSPARENCY, TYPE, TYPE_ATTRIBUTES, TextKind,
TextObject, UNDECODED, Vec2, Write, ai_ops, latin, ps, stroke,
};
use super::{CONIC, CONIC_WEDGES, DIAMOND, GRAPHS, HUE_STOPS, SPREAD, SPREAD_CAPPED};
use super::{CONIC, CONIC_WEDGES, DIAMOND, GRAPHS, HUE_STOPS, PERCEPTUAL_STOPS, SPREAD, SPREAD_CAPPED};
#[cfg(test)]
thread_local! {
@@ -710,10 +710,7 @@ impl<'a> Writer<'a> {
Color::Cmyk { c, m, y, k } => Ink::Cmyk([c, m, y, k].map(unit)),
// The CMYK equivalent of the RGB values as written.
Color::Rgb { r, g, b } => Ink::Rgb(self.cms.to_cmyk(&ai_ops::as_written(*color), intent).map(unit), [r, g, b].map(unit)),
Color::Lab { .. } => {
let rgb = color.to_rgb().map(unit);
Ink::Rgb(self.cms.to_cmyk(color, intent).map(unit), rgb)
}
Color::Lab { .. } => Ink::Rgb(self.cms.to_cmyk(color, intent).map(unit), ai_ops::rgb_values(*color)),
}
}
@@ -755,11 +752,11 @@ impl<'a> Writer<'a> {
/// (its distance a fraction of the radius, at most 1, §3.5.5; `0 0 0 0 Bh` at the center,
/// §3.5.6), `1 (name) x y angle length 1 0 0 1 0 0 Bg`.
fn gradient(&mut self, g: &GradientPaint, bounds: Rect) -> String {
// A gradient mixed around the hue wheel (the format's gradients mix their stops' colors
// directly): the stops on its curve, no more than the reader reads, in a definition of
// its own.
if g.gradient.method.is_hue() {
self.warn(HUE_STOPS);
// A gradient mixed by the Perceptual method or around the hue wheel (the format's
// gradients mix their stops' colors directly): the stops on its curve, in process colors,
// no more than the reader reads, in a definition of its own.
if !g.gradient.method.is_classic() {
self.warn(if g.gradient.method.is_hue() { HUE_STOPS } else { PERCEPTUAL_STOPS });
let curve = g.gradient.as_classic_curve();
let gradient = if curve.is_spread() { curve } else { curve.fitted(crate::import::MAX_GRADIENT_STOPS).into_owned() };
let p = GradientPaint { gradient, swatch: None, ..g.clone() };
+10
View File
@@ -1569,6 +1569,16 @@ fn headless_backend_methods() {
assert_eq!(entry["label"], "Trim at Crossings Tool");
assert!(entry["shortcut"].is_null());
assert_eq!(h.call("ui.tool.select", json!({"tool": trim})).unwrap()["tool"], trim);
// The Enclosing Lasso Tool is listed once, in the Lasso tool's group after the Lasso.
let enclosing = vectorcraft_tools::addons::enclosing_lasso::ID;
let with_enclosing: Vec<_> =
groups.iter().map(|group| group.as_array().unwrap()).filter(|group| group.iter().any(|entry| entry["id"] == enclosing)).collect();
assert_eq!(with_enclosing.len(), 1, "{enclosing} is in one group");
let ids: Vec<_> = with_enclosing[0].iter().map(|entry| entry["id"].clone()).collect();
assert_eq!(ids, [json!("lasso"), json!(enclosing)]);
assert_eq!(with_enclosing[0][1]["label"], "Enclosing Lasso Tool");
assert!(with_enclosing[0][1]["shortcut"].is_null());
assert_eq!(h.call("ui.tool.select", json!({"tool": enclosing})).unwrap()["tool"], enclosing);
let polygonal = groups.iter().flat_map(|group| group.as_array().unwrap()).find(|entry| entry["id"] == "polygonalLasso");
assert_eq!(polygonal.map(|entry| entry["label"].clone()), Some(json!("Polygonal Lasso Tool")));
assert!(h.call("ui.resize", json!({})).is_err());
+74 -18
View File
@@ -46,12 +46,7 @@ use crate::{Imported, Kind};
const PATTERNS: &str = "hatched and pattern brushes are filled with their average color";
const ENDS_EARLY: &str = "the file ends early: what it held was imported";
const TOO_MANY: &str = "objects past the most one file may hold were left out";
const AT_LIMIT: &str = "the file reached the most objects one file may hold: any after them were not read";
/// The most items `craft_metafile` keeps from one file (its `MAX_ITEMS`). It stops reading at the
/// limit and does not say whether more items followed, so a picture holding this many may have
/// been cut short.
const READER_ITEMS: usize = 200_000;
const AT_LIMIT: &str = "the file or a picture inside it reached a limit on what one file may hold: what came after the limit was not read";
/// Points a unit of a WMF without a placeable header (1440 units an inch).
const WMF_UNIT: f64 = 72.0 / 1440.0;
@@ -217,6 +212,18 @@ struct Pending {
path: BezPath,
}
/// What `craft_metafile` counted as not read or not played as the file asks.
struct Lost {
/// Records of kinds it doesn't read.
skipped: u32,
/// Images, and pattern brushes (a pen's included), whose bitmap it couldn't read.
images: u32,
/// Clip changes it didn't apply as the file sets them.
clips: u32,
/// Raster operations drawn as a plain copy or left out.
rops: u32,
}
/// Clip paths already made, by address (the `Arc` keeps the address from being reused); None for
/// one that clips nothing in the picture.
type MadeClips = HashMap<*const ClipPath, (Arc<ClipPath>, Option<Arc<Clip>>)>;
@@ -561,10 +568,7 @@ impl Mapper {
let shape = if k > 1e-12 && k.is_finite() && linear.determinant().abs() > 1e-24 { Affine::scale(1.0 / k) * linear } else { Affine::IDENTITY };
let f = &t.font;
let h = f64::from(f.height);
// A negative height is the em; a positive one the cell (the em and the internal leading).
let em = if h < 0.0 { -h } else { h * 0.85 };
let size = if em > 0.0 && (em * k).is_finite() { (em * k).clamp(0.5, 5000.0) } else { 12.0 };
let mut style = CharStyle { size, fill: color(t.color), stroke: Paint::None, ..CharStyle::default() };
let mut style = CharStyle { fill: color(t.color), stroke: Paint::None, ..CharStyle::default() };
if !f.family.trim().is_empty() {
style.font_family = f.family.trim().to_string();
}
@@ -575,6 +579,33 @@ impl Mapper {
(false, false) => "Regular",
}
.into();
// The face the font maps to (the fallback face for a font that isn't installed). Characters
// it has no glyph for are drawn from other faces at the same size and Horizontal Scale.
let face = vectorcraft_text::FontDb::global().style_face(&style);
// A negative height is the em. A positive height is the character cell, and the em is
// the cell times unitsPerEm divided by the face's OS/2 usWinAscent plus usWinDescent at
// its instance of a variable font (its own ascent plus descent when it has no OS/2 table).
let cell_em = face.as_ref().and_then(|face| {
let (a, d) = face.vertical_metrics();
Some(face.units_per_em() / face.win_cell_height().unwrap_or(a + d)).filter(|r| r.is_finite() && *r > 0.0)
});
let em = if h < 0.0 { -h } else { h * cell_em.unwrap_or(0.85) };
let sized = em > 0.0 && (em * k).is_finite();
let size = if sized { (em * k).clamp(0.5, 5000.0) } else { 12.0 };
style.size = size;
// An average character width, negative or positive, becomes Horizontal Scale: the face's
// own average width (OS/2 xAvgCharWidth) at the type size is stretched or narrowed to it,
// also when the size was held to its range. A width is ignored when the height is 0.
let width = f64::from(f.width).abs();
if width > 0.0
&& sized
&& let Some(avg) = face.as_ref().and_then(|face| Some(face.average_char_width()? / face.units_per_em()))
{
let h_scale = width * k / (avg * size) * 100.0;
if h_scale.is_finite() {
style.h_scale = h_scale.clamp(1.0, 10000.0);
}
}
style.underline = f.underline;
style.strikethrough = f.strike;
let db = vectorcraft_text::FontDb::global();
@@ -696,14 +727,38 @@ impl Mapper {
}
/// The document: what was drawn on one layer, clipped art in clipping groups.
fn finish(mut self, kind: Kind, skipped: u32) -> Imported {
fn finish(mut self, kind: Kind, lost: Lost) -> Imported {
self.flush();
if skipped > 0 {
let n = skipped;
let s = |n: u32| if n == 1 { "" } else { "s" };
let was = |n: u32| if n == 1 { "was" } else { "were" };
let n = lost.skipped;
if n > 0 {
self.warnings.push(format!("{n} record{} of kinds VectorCraft doesn't read {} skipped", s(n), was(n)));
}
let n = lost.images;
if n > 0 {
self.warnings.push(format!(
"{n} record{} of kinds VectorCraft doesn't read {} skipped",
if n == 1 { "" } else { "s" },
if n == 1 { "was" } else { "were" }
"{n} image{} or pattern brush{} that couldn't be read {} left out",
s(n),
if n == 1 { "" } else { "es" },
was(n)
));
}
let n = lost.clips;
if n > 0 {
self.warnings.push(format!(
"{n} clip{} couldn't be applied as the file sets {}: what is drawn after {} may show more or less than the file does",
s(n),
if n == 1 { "it" } else { "them" },
if n == 1 { "it" } else { "them" }
));
}
let n = lost.rops;
if n > 0 {
self.warnings.push(format!(
"{n} raster operation{} other than a plain copy (masks, inversions) {} drawn as a plain copy or left out",
s(n),
was(n)
));
}
let out = std::mem::take(&mut self.out);
@@ -957,11 +1012,12 @@ pub(crate) fn import(bytes: &[u8]) -> Result<Imported, String> {
if ends_early(bytes, kind) {
m.warn(ENDS_EARLY);
}
if pic.items.len() >= READER_ITEMS {
if pic.truncated {
m.warn(AT_LIMIT);
}
let lost = Lost { skipped: pic.skipped_records, images: pic.dropped_images, clips: pic.ignored_clips, rops: pic.unplayed_raster_ops };
for item in pic.items {
m.item(item);
}
Ok(m.finish(kind, pic.skipped_records))
Ok(m.finish(kind, lost))
}
+2
View File
@@ -16,6 +16,8 @@
//! [`import`] reads either format (an EMF with its EMF+ records too, through `craft_metafile`)
//! into a document of one artboard (the picture's frame) and one layer: paths with fills and
//! strokes, clipping, images and text. Records it 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.
//! [`import_pict`] reads QuickDraw pictures (PICT, versions 1 and 2) into the same kind of
//! document.
//!
+208 -1
View File
@@ -527,11 +527,100 @@ fn a_file_with_more_objects_than_are_read_says_so() {
let many = hand_emf(5000, 3000, &vec![rect.clone(); 200_010]);
let back = import(&many).unwrap();
assert_eq!(paths(&back.document).len(), 200_000);
assert!(back.warnings.iter().any(|w| w.contains("reached the most objects")), "{:?}", back.warnings);
assert!(back.warnings.iter().any(|w| w.contains("reached a limit")), "{:?}", back.warnings);
// Exactly as many as the reader keeps: nothing was left unread.
let full = import(&hand_emf(5000, 3000, &vec![rect.clone(); 200_000])).unwrap();
assert_eq!(paths(&full.document).len(), 200_000);
assert!(full.warnings.is_empty(), "{:?}", full.warnings);
let few = import(&hand_emf(5000, 3000, &vec![rect; 3])).unwrap();
assert!(few.warnings.is_empty(), "{:?}", few.warnings);
}
#[test]
fn a_file_cut_short_by_another_limit_says_so() {
// SAVEDC past the 1,024 levels the reader keeps stops the parse: the rectangle after them is
// not read.
let mut records = vec![(43, le(&[0, 0, 100, 100]))];
records.extend(vec![(33, vec![]); 1100]);
records.push((43, le(&[200, 200, 300, 300])));
let back = import(&hand_emf(5000, 3000, &records)).unwrap();
assert_eq!(paths(&back.document).len(), 1);
assert_eq!(
back.warnings,
vec!["the file or a picture inside it reached a limit on what one file may hold: what came after the limit was not read".to_string()]
);
}
#[test]
fn images_the_reader_does_not_read_are_counted() {
let records = vec![(81, png_stretch_dibits(&png_claiming(1 << 13, 1 << 13))); 2];
let back = import(&hand_emf(5000, 3000, &records)).unwrap();
assert_eq!(back.warnings, vec!["2 images or pattern brushes that couldn't be read were left out".to_string()]);
let back = import(&hand_emf(5000, 3000, &records[..1])).unwrap();
assert_eq!(back.warnings, vec!["1 image or pattern brush that couldn't be read was left out".to_string()]);
}
#[test]
fn a_wmf_reports_unread_pattern_brushes_and_raster_operations() {
let records = vec![
// DIBCREATEPATTERNBRUSH (style 5, usage 0) whose bitmap header can't be read.
(0x0142, [le16(&[5, 0]), vec![0xFF; 8]].concat()),
// A bitmap-less DIBBITBLT with DSTINVERT (0x00550009): rop, ySrc, xSrc, reserved, height,
// width, yDest, xDest.
(0x0940, le16(&[0x0009, 0x0055, 0, 0, 0, 100, 100, 0, 0])),
];
let back = import(&hand_wmf(1440, 1440, &records)).unwrap();
assert_eq!(
back.warnings,
vec![
"1 image or pattern brush that couldn't be read was left out".to_string(),
"1 raster operation other than a plain copy (masks, inversions) was drawn as a plain copy or left out".to_string(),
]
);
}
#[test]
fn clips_that_are_not_applied_are_counted() {
// BEGINPATH, a rectangle, ENDPATH, SELECTCLIPPATH with RGN_XOR (3), then a rectangle drawn after it.
let records = vec![(59, vec![]), (43, le(&[100, 100, 2000, 2000])), (60, vec![]), (67, le(&[3])), (43, le(&[500, 500, 600, 600]))];
let back = import(&hand_emf(5000, 3000, &records)).unwrap();
assert_eq!(paths(&back.document).len(), 1);
assert_eq!(
back.warnings,
vec!["1 clip couldn't be applied as the file sets it: what is drawn after it may show more or less than the file does".to_string()]
);
// RGN_AND (1) is applied.
let mut records = records;
records[3] = (67, le(&[1]));
let back = import(&hand_emf(5000, 3000, &records)).unwrap();
assert!(back.warnings.is_empty(), "{:?}", back.warnings);
}
/// An EMR_BITBLT of the 100 × 100 box at the origin with `rop` and no source bitmap.
fn bitblt(rop: u32) -> Vec<u8> {
// Bounds; destination; the operation; the source origin, transform (identity) and background
// color; usage, then no BITMAPINFO and no bits.
let mut body = vec![0; 16];
body.extend(le(&[0, 0, 100, 100, rop as i32, 0, 0]));
body.extend(le_f32(&[1.0, 0.0, 0.0, 1.0, 0.0, 0.0]));
body.extend(le(&[0, 0, 0, 0, 0, 0]));
body
}
#[test]
fn raster_operations_that_are_not_played_are_counted() {
// DSTINVERT and PATINVERT take no source bitmap and are left out.
let records = vec![(76, bitblt(0x0055_0009)), (76, bitblt(0x005A_0049))];
let back = import(&hand_emf(5000, 3000, &records)).unwrap();
assert_eq!(
back.warnings,
vec!["2 raster operations other than a plain copy (masks, inversions) were drawn as a plain copy or left out".to_string()]
);
// WHITENESS is played.
let back = import(&hand_emf(5000, 3000, &[(76, bitblt(0x00FF_0062))])).unwrap();
assert!(back.warnings.is_empty(), "{:?}", back.warnings);
}
/// An EMR_STRETCHDIBITS copying `png` (a BI_PNG bitmap) to a 10 × 10 box.
fn png_stretch_dibits(png: &[u8]) -> Vec<u8> {
// Bounds; destination, source and its size; the BITMAPINFO and the bits (from the record start);
@@ -677,6 +766,124 @@ fn text_keeps_a_stretch_across() {
assert!((a - 2.0).abs() < 1e-6 && b.abs() < 1e-6 && c.abs() < 1e-6 && (d - 1.0).abs() < 1e-6, "{:?}", t.xf);
}
/// Source Sans 3 Regular's own values, read from its table directory: unitsPerEm (`head`),
/// xAvgCharWidth and usWinAscent + usWinDescent (`OS/2`), in font units.
fn source_sans_metrics() -> (f64, f64, f64) {
let font: &[u8] = include_bytes!("../../../../assets/fonts/SourceSans3-Regular.ttf");
let u16_at = |at: usize| u16::from_be_bytes([font[at], font[at + 1]]);
let table = |tag: &[u8; 4]| {
let at = (0..usize::from(u16_at(4))).map(|i| 12 + 16 * i).find(|at| &font[*at..*at + 4] == tag).unwrap();
u32::from_be_bytes([font[at + 8], font[at + 9], font[at + 10], font[at + 11]]) as usize
};
let (head, os2) = (table(b"head"), table(b"OS/2"));
let avg = f64::from(i16::from_be_bytes([font[os2 + 2], font[os2 + 3]]));
(f64::from(u16_at(head + 18)), avg, f64::from(u16_at(os2 + 74)) + f64::from(u16_at(os2 + 76)))
}
/// The style of "Hi" drawn in an EMF in Source Sans 3 with a LOGFONT of `height` and `width`
/// (hundredths of a millimeter).
fn emf_font_style(height: i32, width: i32) -> vectorcraft_doc::CharStyle {
emf_font_style_in("Source Sans 3", height, width)
}
/// [`emf_font_style`] with the LOGFONT naming `family`.
fn emf_font_style_in(family: &str, height: i32, width: i32) -> vectorcraft_doc::CharStyle {
let mut text = vec![0; 16];
text.extend(le(&[1, 0, 0]));
text.extend(le(&[1000, 1500, 2, 76, 0, 0, 0, 0, 0, 0]));
text.extend("Hi".encode_utf16().flat_map(u16::to_le_bytes));
let mut font = le(&[2, height, width, 0, 0, 400]);
font.extend([0u8; 8]);
font.extend(family.encode_utf16().chain(std::iter::repeat_n(0, 32 - family.encode_utf16().count())).flat_map(u16::to_le_bytes));
let records = vec![(82, font), (37, le(&[2])), (84, text)];
let back = import(&hand_emf(5000, 3000, &records)).unwrap();
let t = all(&back.document)
.into_iter()
.find_map(|n| match n.kind {
NodeKind::Text(t) => Some(t),
_ => None,
})
.unwrap();
t.runs[0].style.clone()
}
#[test]
fn a_font_width_becomes_horizontal_scale() {
let (upem, avg, _) = source_sans_metrics();
let mm = 72.0 / 25.4;
// A 10 mm em and an average character width of 6 mm: the face's average width, avg/upem of
// the em, is scaled to 6 mm.
let want = 6.0 / (avg / upem * 10.0) * 100.0;
for width in [600, -600] {
let st = emf_font_style(-1000, width);
assert_eq!(st.font_family, "Source Sans 3");
assert!((st.size - 10.0 * mm).abs() < 1e-9, "{}", st.size);
assert!((st.h_scale - want).abs() < 1e-9, "width {width}: {} for {want}", st.h_scale);
}
assert_eq!(emf_font_style(-1000, 0).h_scale, 100.0);
// A 4 m em is set at the largest type size, 5000 pt, and a 2.4 m average width keeps its
// width at that size.
let st = emf_font_style(-400_000, 240_000);
assert_eq!(st.size, 5000.0);
let want = 2400.0 * mm / (avg / upem * 5000.0) * 100.0;
assert!((st.h_scale - want).abs() < 1e-9, "{} for {want}", st.h_scale);
// With a height of 0 the type is set at the default size and the width is ignored.
assert_eq!(emf_font_style(0, 600).h_scale, 100.0);
}
#[test]
fn a_positive_font_height_is_the_character_cell() {
let (upem, avg, cell) = source_sans_metrics();
let mm = 72.0 / 25.4;
// A 10 mm cell: the em is the cell times unitsPerEm divided by the face's usWinAscent plus
// usWinDescent, and a 6 mm average width is measured against that em.
let em = 10.0 * upem / cell;
let st = emf_font_style(1000, 600);
assert!((st.size - em * mm).abs() < 1e-9, "{} for {}", st.size, em * mm);
let want = 6.0 / (avg / upem * em) * 100.0;
assert!((st.h_scale - want).abs() < 1e-9, "{} for {want}", st.h_scale);
}
#[test]
fn a_font_the_system_lacks_is_measured_in_the_face_that_draws_it() {
// A family no system has keeps its name, and layout draws it in Source Sans 3: the cell and
// the average width are measured in that face.
let (upem, avg, cell) = source_sans_metrics();
let mm = 72.0 / 25.4;
let st = emf_font_style_in("Missing Family 7183", 1000, 600);
assert_eq!(st.font_family, "Missing Family 7183");
let em = 10.0 * upem / cell;
assert!((st.size - em * mm).abs() < 1e-9, "{} for {}", st.size, em * mm);
let want = 6.0 / (avg / upem * em) * 100.0;
assert!((st.h_scale - want).abs() < 1e-9, "{} for {want}", st.h_scale);
}
#[test]
fn wmf_font_width_becomes_horizontal_scale() {
let (upem, avg, _) = source_sans_metrics();
// CREATEFONTINDIRECT: a 0.1 inch em (144 units) with an average width of 72 units, then
// SELECTOBJECT and TEXTOUT "Hi" at (720, 360).
let mut font = le16(&[-144, 72, 0, 0, 400]);
font.extend([0u8; 8]);
font.extend(b"Source Sans 3".iter().copied().chain(std::iter::repeat_n(0, 19)));
let mut text = le16(&[2]);
text.extend(b"Hi");
text.extend(le16(&[360, 720]));
let records = vec![(0x02FB, font), (0x012D, le16(&[0])), (0x0521, text)];
let back = import(&hand_wmf(1440, 1440, &records)).unwrap();
let t = all(&back.document)
.into_iter()
.find_map(|n| match n.kind {
NodeKind::Text(t) => Some(t),
_ => None,
})
.unwrap();
let st = &t.runs[0].style;
assert!((st.size - 7.2).abs() < 1e-9, "{}", st.size);
let want = 72.0 / (avg / upem * 144.0) * 100.0;
assert!((st.h_scale - want).abs() < 1e-9, "{} for {want}", st.h_scale);
}
#[test]
fn a_clip_whose_box_holds_the_picture_still_clips() {
// A diamond around the middle of the picture, whose box holds the whole frame but which cuts
@@ -34,9 +34,19 @@ fn flat(c: &CubicBez) -> bool {
off(c.p1) <= FLAT && off(c.p2) <= FLAT
}
/// Where the chords of `a` and `b` cross: (s, u) along each, or `None` when they don't (parallel
/// ones never do).
fn chords_cross(a: &CubicBez, b: &CubicBez) -> Option<(f64, f64)> {
/// Which ends of a segment are open ends of its path: (start, end).
type Open = (bool, bool);
/// The open ends of segment `s` of `sp`.
fn open_ends(sp: &SubPath, s: usize) -> Open {
(!sp.closed && s == 0, !sp.closed && s + 1 == sp.segment_count())
}
/// Where the straight pieces `a` and `b` cross: (t on `a`, t on `b`), or `None` when their chords
/// don't cross (parallel ones never do, so paths lying along each other don't cross). An end in
/// `open_a` or `open_b` (start, end) that lies within [`SAME`] of the other piece meets it at the
/// point of that piece nearest it, at any angle.
fn pieces_cross(a: &CubicBez, b: &CubicBez, open_a: Open, open_b: Open) -> Option<(f64, f64)> {
let (da, db) = (a.p3 - a.p0, b.p3 - b.p0);
let den = da.cross(db);
if den.abs() <= 1e-12 * da.hypot() * db.hypot() || den == 0.0 {
@@ -45,7 +55,20 @@ fn chords_cross(a: &CubicBez, b: &CubicBez) -> Option<(f64, f64)> {
let w = b.p0 - a.p0;
let (s, u) = (w.cross(db) / den, w.cross(da) / den);
let within = |v: f64| (-1e-9..=1.0 + 1e-9).contains(&v);
(within(s) && within(u)).then(|| (s.clamp(0.0, 1.0), u.clamp(0.0, 1.0)))
if within(s) && within(u) {
// The pieces are straight but their parameters needn't run evenly along them.
let (s, u) = (s.clamp(0.0, 1.0), u.clamp(0.0, 1.0));
return Some((a.nearest(a.p0.lerp(a.p3, s), 1e-9).t, b.nearest(b.p0.lerp(b.p3, u), 1e-9).t));
}
let ends_a = [(open_a.0, 0.0, a.p0), (open_a.1, 1.0, a.p3)].into_iter().filter(|e| e.0).map(|(_, ta, p)| {
let n = b.nearest(p, 1e-9);
((ta, n.t), n.distance_sq)
});
let ends_b = [(open_b.0, 0.0, b.p0), (open_b.1, 1.0, b.p3)].into_iter().filter(|e| e.0).map(|(_, tb, p)| {
let n = a.nearest(p, 1e-9);
((n.t, tb), n.distance_sq)
});
ends_a.chain(ends_b).filter(|e| e.1 < SAME * SAME).min_by(|x, y| x.1.total_cmp(&y.1)).map(|e| e.0)
}
/// `(s, t)` moved to where `a` and `b` cross exactly, by Newton's method on a(s) = b(t), or as it
@@ -85,8 +108,11 @@ fn refined(a: &CubicBez, b: &CubicBez, (s0, t0): (f64, f64)) -> (f64, f64) {
}
/// Where segments `a` and `b` cross: (t on `a`, t on `b`) pairs, halving both while their control
/// boxes meet until each piece is straight. `None` once `budget` steps are spent.
fn segment_crossings(a: &CubicBez, b: &CubicBez, budget: &mut usize) -> Option<Vec<(f64, f64)>> {
/// boxes meet until each piece is straight. `None` once `budget` steps are spent. `open_a` and
/// `open_b` are the segments' ends that are open ends of their paths (start, end): such an end
/// within [`SAME`] of the other segment meets it there, as a path cut where another crosses it
/// ends a little off that path.
fn segment_crossings(a: &CubicBez, b: &CubicBez, open_a: Open, open_b: Open, budget: &mut usize) -> Option<Vec<(f64, f64)>> {
let mut stack = vec![(0.0, 1.0, 0.0, 1.0, 0u32)];
let mut found: Vec<(f64, f64)> = vec![];
while let Some((a0, a1, b0, b1, depth)) = stack.pop() {
@@ -96,10 +122,9 @@ fn segment_crossings(a: &CubicBez, b: &CubicBez, budget: &mut usize) -> Option<V
continue;
}
if (flat(&ca) && flat(&cb)) || depth >= MAX_DEPTH {
if let Some((s, u)) = chords_cross(&ca, &cb) {
// The pieces are straight but their parameters needn't run evenly along them.
let x = ca.p0.lerp(ca.p3, s);
let (ta, tb) = (ca.nearest(x, 1e-9).t, cb.nearest(cb.p0.lerp(cb.p3, u), 1e-9).t);
// Only a piece's ends that are the segment's open ends reach past it.
let (oa, ob) = ((open_a.0 && a0 == 0.0, open_a.1 && a1 == 1.0), (open_b.0 && b0 == 0.0, open_b.1 && b1 == 1.0));
if let Some((ta, tb)) = pieces_cross(&ca, &cb, oa, ob) {
found.push((a0 + ta * (a1 - a0), b0 + tb * (b1 - b0)));
}
continue;
@@ -193,18 +218,21 @@ fn shared_anchors(sp: &SubPath, with_length: &[usize], i: usize, j: usize) -> Ve
/// Where segments `a` and `b` cross, without the places at the anchors in `shared`: two segments that
/// meet at an anchor don't cross there, but they can cross again elsewhere.
fn crossings_apart(a: &CubicBez, b: &CubicBez, shared: &[Point], budget: &mut usize) -> Option<Vec<(f64, f64)>> {
let mut found = segment_crossings(a, b, budget)?;
fn crossings_apart(a: (&CubicBez, Open), b: (&CubicBez, Open), shared: &[Point], budget: &mut usize) -> Option<Vec<(f64, f64)>> {
let ((a, open_a), (b, open_b)) = (a, b);
let mut found = segment_crossings(a, b, open_a, open_b, budget)?;
found.retain(|(ta, _)| !shared.iter().any(|p| a.eval(*ta).distance(*p) < SAME));
Some(found)
}
/// Where `paths` cross one another (and, with `self_crossings`, where each crosses itself, a segment
/// that loops over itself included): for each path, the places on it, in order. Segments that meet
/// at an anchor they share don't count as crossing there. `None` past [`MAX_CROSSING_SEGMENTS`]
/// segments or when the curves are too tangled to sort out, or when a coordinate isn't finite.
/// at an anchor they share don't count as crossing there, and an open end of a path that lies
/// within 0.001 pt of another path (or of itself) meets it there; paths that lie along each other
/// don't cross. `None` past [`MAX_CROSSING_SEGMENTS`] segments or when the curves are too tangled
/// to sort out, or when a coordinate isn't finite.
pub fn crossings(paths: &[&PathData], self_crossings: bool) -> Option<Vec<Vec<Place>>> {
let mut segs: Vec<(usize, usize, usize, CubicBez, Rect)> = vec![];
let mut segs: Vec<(usize, usize, usize, CubicBez, Rect, Open)> = vec![];
for (k, path) in paths.iter().enumerate() {
for (si, sp) in path.subpaths.iter().enumerate() {
for s in 0..sp.segment_count() {
@@ -212,7 +240,7 @@ pub fn crossings(paths: &[&PathData], self_crossings: bool) -> Option<Vec<Vec<Pl
if ![c.p0, c.p1, c.p2, c.p3].iter().all(|p| p.x.is_finite() && p.y.is_finite()) {
return None;
}
segs.push((k, si, s, c, control_box(&c)));
segs.push((k, si, s, c, control_box(&c), open_ends(sp, s)));
if segs.len() > MAX_CROSSING_SEGMENTS {
return None;
}
@@ -222,11 +250,11 @@ pub fn crossings(paths: &[&PathData], self_crossings: bool) -> Option<Vec<Vec<Pl
let with_length: Vec<Vec<Vec<usize>>> = paths.iter().map(|p| p.subpaths.iter().map(with_length_from).collect()).collect();
let mut out: Vec<Vec<Place>> = vec![vec![]; paths.len()];
let mut budget = MAX_STEPS;
for (i, (ka, sa, ia, ca, ra)) in segs.iter().enumerate() {
for (i, (ka, sa, ia, ca, ra, oa)) in segs.iter().enumerate() {
if self_crossings && let Some((s, t)) = self_crossing(ca) {
out.get_mut(*ka)?.extend([(*sa, *ia, s), (*sa, *ia, t)]);
}
for (kb, sb, ib, cb, rb) in segs.iter().skip(i + 1) {
for (kb, sb, ib, cb, rb, ob) in segs.iter().skip(i + 1) {
if (ka == kb && !self_crossings) || !ra.inflate(SAME, SAME).overlaps(*rb) {
continue;
}
@@ -234,7 +262,7 @@ pub fn crossings(paths: &[&PathData], self_crossings: bool) -> Option<Vec<Vec<Pl
(Some(sp), Some(w)) if ka == kb && sa == sb => shared_anchors(sp, w, *ia, *ib),
_ => vec![],
};
for (ta, tb) in crossings_apart(ca, cb, &shared, &mut budget)? {
for (ta, tb) in crossings_apart((ca, *oa), (cb, *ob), &shared, &mut budget)? {
out.get_mut(*ka)?.push((*sa, *ia, ta));
out.get_mut(*kb)?.push((*sb, *ib, tb));
}
@@ -289,41 +317,43 @@ impl Work {
}
/// Where `others` cross `path`, and where `path` crosses itself (a segment that loops over itself
/// included): the places on `path`, in order, within the work of [`Work::default`].
/// included): the places on `path`, in order, within the work of [`Work::default`]. An open end of
/// a path that lies within 0.001 pt of another meets it there, as [`crossings_on_within`] says.
pub fn crossings_on(path: &PathData, others: &[&PathData]) -> Option<Vec<Place>> {
crossings_on_within(path, others, &mut Work::default())
}
/// [`crossings_on`], drawing on `work`. Only the segments of `others` whose control boxes meet the
/// box of `path` are compared with it, so the paths far from it cost one box test per segment.
/// Segments of `path` that meet at an anchor they share don't count as crossing there, and a
/// segment of `others` with a coordinate that isn't finite is left out. `None` when `path` has more
/// than [`MAX_CROSSING_SEGMENTS`] segments or a coordinate that isn't finite, when more than
/// Segments of `path` that meet at an anchor they share don't count as crossing there, an open end
/// of a path that lies within 0.001 pt of another meets it there, and a segment of `others` with a
/// coordinate that isn't finite is left out. `None` when `path` has more than
/// [`MAX_CROSSING_SEGMENTS`] segments or a coordinate that isn't finite, when more than
/// [`MAX_CROSSED_BY_SEGMENTS`] segments of `others` lie in its box, when the pairs of segments to
/// look at are more than `work` has left, or when the curves are too tangled to sort out in the
/// steps it has left.
pub fn crossings_on_within(path: &PathData, others: &[&PathData], work: &mut Work) -> Option<Vec<Place>> {
let mut own: Vec<(usize, usize, CubicBez, Rect)> = vec![];
let mut own: Vec<(usize, usize, CubicBez, Rect, Open)> = vec![];
for (si, sp) in path.subpaths.iter().enumerate() {
for s in 0..sp.segment_count() {
let c = sp.segment(s);
if ![c.p0, c.p1, c.p2, c.p3].iter().all(|p| p.x.is_finite() && p.y.is_finite()) {
return None;
}
own.push((si, s, c, control_box(&c)));
own.push((si, s, c, control_box(&c), open_ends(sp, s)));
if own.len() > MAX_CROSSING_SEGMENTS {
return None;
}
}
}
let Some(reach) = own.iter().map(|o| o.3).reduce(|a, b| a.union(b)).map(|r| r.inflate(SAME, SAME)) else { return Some(vec![]) };
let mut near: Vec<(CubicBez, Rect)> = vec![];
let mut near: Vec<(CubicBez, Rect, Open)> = vec![];
for sp in others.iter().flat_map(|p| &p.subpaths) {
for s in 0..sp.segment_count() {
let c = sp.segment(s);
let r = control_box(&c);
if [c.p0, c.p1, c.p2, c.p3].iter().all(|p| p.x.is_finite() && p.y.is_finite()) && reach.overlaps(r) {
near.push((c, r));
near.push((c, r, open_ends(sp, s)));
if near.len() > MAX_CROSSED_BY_SEGMENTS {
return None;
}
@@ -334,17 +364,17 @@ pub fn crossings_on_within(path: &PathData, others: &[&PathData], work: &mut Wor
let with_length: Vec<Vec<usize>> = path.subpaths.iter().map(with_length_from).collect();
let mut out: Vec<Place> = vec![];
let budget = &mut work.steps;
for (i, (sa, ia, ca, ra)) in own.iter().enumerate() {
for (i, (sa, ia, ca, ra, oa)) in own.iter().enumerate() {
let ra = ra.inflate(SAME, SAME);
if let Some((s, t)) = self_crossing(ca) {
out.extend([(*sa, *ia, s), (*sa, *ia, t)]);
}
for (cb, rb) in &near {
for (cb, rb, ob) in &near {
if ra.overlaps(*rb) {
out.extend(segment_crossings(ca, cb, budget)?.into_iter().map(|(ta, _)| (*sa, *ia, ta)));
out.extend(segment_crossings(ca, cb, *oa, *ob, budget)?.into_iter().map(|(ta, _)| (*sa, *ia, ta)));
}
}
for (sb, ib, cb, rb) in own.iter().skip(i + 1) {
for (sb, ib, cb, rb, ob) in own.iter().skip(i + 1) {
if !ra.overlaps(*rb) {
continue;
}
@@ -352,7 +382,7 @@ pub fn crossings_on_within(path: &PathData, others: &[&PathData], work: &mut Wor
(Some(sp), Some(w)) if sa == sb => shared_anchors(sp, w, *ia, *ib),
_ => vec![],
};
for (ta, tb) in crossings_apart(ca, cb, &shared, budget)? {
for (ta, tb) in crossings_apart((ca, *oa), (cb, *ob), &shared, budget)? {
out.push((*sa, *ia, ta));
out.push((*sb, *ib, tb));
}
@@ -725,3 +725,58 @@ fn a_slice_of_a_curve_keeps_its_shape_and_the_anchors_it_runs_through() {
assert!(slice(&circle, (2.0, 1.0)).anchors.is_empty());
assert!(slice(&circle, (f64::NAN, 1.0)).anchors.is_empty());
}
#[test]
fn an_open_end_a_hair_off_another_path_still_meets_it() {
// A bow from (0, 0) to (100, 100), and where a line across at y = 50 crosses it.
let bow = PathData::single(SubPath::new(
vec![Anchor { h_out: pt(0.0, 55.0), ..Anchor::corner(pt(0.0, 0.0)) }, Anchor { h_in: pt(45.0, 100.0), ..Anchor::corner(pt(100.0, 100.0)) }],
false,
));
let across = PathData::single(line(&[(-50.0, 50.0), (150.0, 50.0)], false));
let at = crossings_on(&across, &[&bow]).unwrap();
assert_eq!(at.len(), 1);
let p = across.subpaths[0].segment(0).eval(at[0].2);
// A line ending 0.00005 pt short of the bow, or past it, as a line cut where the bow crosses it
// can: the bow is crossed there, on both searches.
let on_bow = |l: &PathData| crossings_on(&bow, &[l]).unwrap().iter().map(|q| bow.subpaths[0].segment(q.1).eval(q.2)).collect::<Vec<_>>();
for off in [-5e-5, 5e-5] {
let stub = PathData::single(line(&[(-50.0, 50.0), (p.x + off, 50.0)], false));
let found = on_bow(&stub);
assert!(found.len() == 1 && found[0].distance(p) < 1e-3, "{off}: {found:?}");
let both = crossings(&[&stub, &bow], false).unwrap();
assert_eq!((both[0].len(), both[1].len()), (1, 1), "{off}: {both:?}");
}
// 0.01 pt short is not on it.
assert!(on_bow(&PathData::single(line(&[(-50.0, 50.0), (p.x - 0.01, 50.0)], false))).is_empty());
// The bow's own open end 0.00005 pt short of an upright meets it there.
let upright = PathData::single(line(&[(100.00005, 50.0), (100.00005, 150.0)], false));
let found = crossings_on(&upright, &[&bow]).unwrap();
assert!(found.len() == 1 && near(upright.subpaths[0].segment(0).eval(found[0].2).y, 100.0, 1e-3), "{found:?}");
// Two ends that each stop 0.0009 pt short of a corner lie 0.0013 pt apart: they don't meet.
let flat = PathData::single(line(&[(0.0, 0.0), (99.9991, 0.0)], false));
let post = PathData::single(line(&[(100.0, 0.0009), (100.0, 50.0)], false));
assert!(crossings_on(&flat, &[&post]).unwrap().is_empty() && crossings_on(&post, &[&flat]).unwrap().is_empty());
// Two ends that each stop 0.0004 pt short of a corner lie 0.0006 pt apart: they meet.
let flat = PathData::single(line(&[(0.0, 0.0), (99.9996, 0.0)], false));
let post = PathData::single(line(&[(100.0, 0.0004), (100.0, 50.0)], false));
assert_eq!((crossings_on(&flat, &[&post]).unwrap().len(), crossings_on(&post, &[&flat]).unwrap().len()), (1, 1));
// A level line that crosses a quarter circle near its top, where the two meet at under 3
// degrees, cut 0.0015 pt short along its length: its end lies under 0.0001 pt from the arc and
// meets it there.
use kurbo::ParamCurveNearest;
let arc = PathData::single(quarter());
let level = PathData::single(line(&[(50.0, 99.9), (-50.0, 99.9)], false));
let at = crossings_on(&level, &[&arc]).unwrap();
assert_eq!(at.len(), 1);
let end = level.subpaths[0].segment(0).eval(at[0].2) + Vec2::new(0.0015, 0.0);
assert!(arc.subpaths[0].segment(0).nearest(end, 1e-12).distance_sq.sqrt() < 1e-4);
let stub = PathData::single(line(&[(50.0, 99.9), (end.x, end.y)], false));
let found = crossings_on(&arc, &[&stub]).unwrap();
assert!(found.len() == 1 && arc.subpaths[0].segment(0).eval(found[0].2).distance(end) < 1e-3, "{found:?}");
assert_eq!(crossings(&[&stub, &arc], false).unwrap().iter().map(Vec::len).collect::<Vec<_>>(), [1, 1]);
// A corner of a closed path as near a line is not an open end: it doesn't reach the line.
let wedge = PathData::single(line(&[(180.0, 0.0), (220.0, 0.0), (200.0, 49.99995)], true));
let floor = PathData::single(line(&[(150.0, 50.0), (250.0, 50.0)], false));
assert!(crossings_on(&floor, &[&wedge]).unwrap().is_empty() && crossings_on(&wedge, &[&floor]).unwrap().is_empty());
}
+2
View File
@@ -54,6 +54,8 @@ vectorcraft-text = { workspace = true, features = ["test-fonts"] }
serde_json = { workspace = true }
# `draw_text`, to write test files with live text as other writers do.
krilla = { workspace = true, features = ["simple-text"] }
# How many times the symbol list is read to find symbols by name.
vectorcraft-doc = { workspace = true, features = ["symbol-read-count"] }
# An independent raster oracle for gradient placement in PDF forms. These are test-only macOS
# bindings; the exporter stays portable Rust and does not depend on an OS PDF renderer.
+18 -15
View File
@@ -118,7 +118,7 @@ impl Exporter<'_> {
if several && !elements.iter().skip(1).all(|(c, _)| shape_is_coverage(c)) {
let doc = self.doc;
let brushes = self.brushes.get_or_insert_with(|| vectorcraft_brush::library(doc));
match knockout_masks(BrushSearch::new(doc, brushes), &elements) {
match knockout_masks(BrushSearch::new(&self.symbols, brushes), &elements) {
Ok(above) => {
// Every mask is made before anything is drawn: when the symbol objects the
// masks may hold run out, one would leave out art its element covers, and
@@ -452,7 +452,7 @@ impl Exporter<'_> {
// A dynamic symbol's instance shows its own appearance changes, and the instance's
// fill stains its art, as on the canvas.
let doc = self.doc;
if let Some(sym) = doc.symbols.iter().find(|x| &x.name == symbol) {
if let Some(sym) = self.symbols.symbol(symbol) {
let changed;
let art: &Node = if n.extras().symbol_overrides.is_empty() && vectorcraft_doc::symbol_overrides::stain(n).is_none() {
&sym.art
@@ -968,8 +968,10 @@ enum SharedArt {
/// A search for the brushed strokes drawing an object draws, whose brush art can hold many more
/// objects than the stroked path.
struct BrushSearch<'a> {
doc: &'a Document,
struct BrushSearch<'a, 'd> {
doc: &'d Document,
/// `doc`'s symbols, found by name.
symbols: &'a vectorcraft_doc::SymbolBoxes<'d>,
/// The brushes the export draws strokes with ([`Exporter::brush_art`]); a stroke whose brush
/// is not among them is drawn as a plain stroke.
brushes: &'a [vectorcraft_brush::Brush],
@@ -983,9 +985,10 @@ struct BrushSearch<'a> {
exhausted: bool,
}
impl<'a> BrushSearch<'a> {
fn new(doc: &'a Document, brushes: &'a [vectorcraft_brush::Brush]) -> Self {
Self { doc, brushes, seen: HashMap::new(), left: MAX_KNOCKOUT_MASK_OBJECTS, exhausted: false }
impl<'a, 'd> BrushSearch<'a, 'd> {
/// A search through the document of `symbols`.
fn new(symbols: &'a vectorcraft_doc::SymbolBoxes<'d>, brushes: &'a [vectorcraft_brush::Brush]) -> Self {
Self { doc: symbols.document(), symbols, brushes, seen: HashMap::new(), left: MAX_KNOCKOUT_MASK_OBJECTS, exhausted: false }
}
/// Takes `n` objects from [`Self::left`]; false, and the search exhausted, when fewer are left.
@@ -1046,8 +1049,7 @@ impl<'a> BrushSearch<'a> {
NodeKind::SymbolInstance { symbol, .. } => {
// A dynamic symbol's instance draws its art with its own appearance changes: the
// art is copied once for each set of changes, counted before it is copied.
let doc = self.doc;
match doc.symbols.iter().find(|s| &s.name == symbol) {
match self.symbols.symbol(symbol) {
Some(s) if !n.extras().symbol_overrides.is_empty() => {
let key = format!("{symbol}\u{0}{:?}", n.extras().symbol_overrides);
self.shared(SharedArt::Dynamic, &key, |search| {
@@ -1080,8 +1082,7 @@ impl<'a> BrushSearch<'a> {
/// Whether the art of the symbol named `name` draws a brushed stroke.
fn symbol(&mut self, name: &str, depth: usize) -> bool {
let doc = self.doc;
let Some(s) = doc.symbols.iter().find(|s| s.name == name) else { return false };
let Some(s) = self.symbols.symbol(name) else { return false };
self.shared(SharedArt::Symbol, name, |search| search.node(&s.art, true, depth))
}
@@ -1177,7 +1178,8 @@ mod tests {
let square = Node::path(NodeId(0), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::basic(Paint::None, Paint::None, 0.0));
let art = Node::group(NodeId(0), vec![Arc::new(square), Arc::new(instance())]);
d.symbols.push(Symbol { dynamic: true, name: "Loop".into(), art: Arc::new(art) });
let mut search = BrushSearch::new(&d, &[]);
let symbols = d.symbol_boxes();
let mut search = BrushSearch::new(&symbols, &[]);
assert!(!search.node(&instance(), true, 0));
assert!(!search.exhausted);
assert!(MAX_KNOCKOUT_MASK_OBJECTS - search.left < 10, "{} objects", MAX_KNOCKOUT_MASK_OBJECTS - search.left);
@@ -1205,11 +1207,12 @@ mod tests {
.collect();
Node::group(NodeId(0), instances)
};
let mut search = BrushSearch::new(&d, &[]);
let symbols = d.symbol_boxes();
let mut search = BrushSearch::new(&symbols, &[]);
assert!(search.node(&group(true), true, 0));
assert!(search.exhausted);
assert_eq!(search.left, 0);
let mut search = BrushSearch::new(&d, &[]);
let mut search = BrushSearch::new(&symbols, &[]);
assert!(!search.node(&group(false), true, 0));
assert!(!search.exhausted);
// The group, the 1,000 instances, and one copy of the art counted and looked through.
@@ -1247,6 +1250,6 @@ mod tests {
vectorcraft_doc::placed_document::prime(&placed, Arc::new(vec![]), brushed_art());
let n = Node::new(NodeId(0), NodeKind::PlacedDocument(Box::new(placed)));
let brushes = vectorcraft_brush::library(&d);
assert!(BrushSearch::new(&d, &brushes).node(&n, true, 0));
assert!(BrushSearch::new(&d.symbol_boxes(), &brushes).node(&n, true, 0));
}
}
+1 -1
View File
@@ -134,7 +134,7 @@ impl Exporter<'_> {
self.inline_depth += 1;
for ig in &layout.inlines {
let Some(art) = t.runs.get(ig.run).and_then(|r| r.inline.as_ref()) else { continue };
let Some(sym) = doc.symbols.iter().find(|x| x.name == art.symbol) else { continue };
let Some(sym) = self.symbols.symbol(&art.symbol) else { continue };
let mut node = (*sym.art).clone();
// Strokes scale with the art, as on the canvas.
node.transform(t.xf * ig.xf * doc.symbol_natural_xf(&art.symbol), true);
+22 -10
View File
@@ -1,6 +1,6 @@
use super::entry::{INVISIBLE_TEXT_NOTE, MAX_NESTED, OUTLINED_TEXT_NOTE, UNSORTED, WHITE_KEY};
use super::state::{
Builder, Decoded, Frame, FrameKind, GlyphRun, blend, fill_rule, gray_png, line_width, mean_scale, resize_alpha, rgba_png, same_outline,
Builder, Decoded, Frame, FrameKind, GlyphRun, blend, fill_rule, gray_png, line_width, mean_scale, resize_alpha, rgb_png, rgba_png, same_outline,
stroke_layer, stroke_outline,
};
use super::{
@@ -304,27 +304,39 @@ impl<'a> Device<'a> for Builder<'_> {
self.add_image(key, || None, xf);
return;
}
let mut decoded: Option<Decoded> = None;
// RGB samples, or RGBA when the image has an alpha channel or is drawn white.
let mut decoded: Option<(Decoded, bool)> = None;
r.with_rgba(
|img, alpha| {
let (w, h, sf) = (img.width(), img.height(), img.scale_factors());
let a = alpha.map(|a| resize_alpha(&a, w, h)).unwrap_or_else(|| vec![255; (w * h) as usize]);
let rgba: Vec<u8> = match img {
_ if white => a.into_iter().flat_map(|a| [255, 255, 255, a]).collect(),
ImageData::Rgb(d) => d.data.as_chunks::<3>().0.iter().zip(a).flat_map(|(c, a)| [c[0], c[1], c[2], a]).collect(),
ImageData::Luma(d) => d.data.iter().zip(a).flat_map(|(g, a)| [*g, *g, *g, a]).collect(),
let px = match (img, alpha) {
// An opaque image's RGB samples are encoded as they are, with no copy.
(ImageData::Rgb(d), None) if !white => (d.data, false),
// Gray samples are stored as RGB: as a gray PNG, the image would become a
// grayscale image that a fill color colorizes.
(ImageData::Luma(d), None) if !white => (d.data.iter().flat_map(|g| [*g; 3]).collect(), false),
(img, alpha) => {
let a = alpha.map(|a| resize_alpha(&a, w, h)).unwrap_or_else(|| vec![255; (w * h) as usize]);
let rgba: Vec<u8> = match img {
_ if white => a.into_iter().flat_map(|a| [255, 255, 255, a]).collect(),
ImageData::Rgb(d) => d.data.as_chunks::<3>().0.iter().zip(a).flat_map(|(c, a)| [c[0], c[1], c[2], a]).collect(),
ImageData::Luma(d) => d.data.iter().zip(a).flat_map(|(g, a)| [*g, *g, *g, a]).collect(),
};
(rgba, true)
}
};
decoded = Some((rgba, w, h, sf));
decoded = Some(((px.0, w, h, sf), px.1));
},
None,
);
let Some((rgba, w, h, sf)) = decoded else {
let Some(((px, w, h, sf), alpha)) = decoded else {
self.warn("an image could not be decoded and was skipped");
return;
};
self.raster_scales.insert(key, sf);
let xf = transform * Affine::scale_non_uniform(sf.0 as f64, sf.1 as f64);
self.add_image(key, || rgba_png(rgba, w, h).map(|png| (ImageBlob::new("image/png", png), w, h)), xf);
let png = move || if alpha { rgba_png(px, w, h) } else { rgb_png(px, w, h) };
self.add_image(key, || png().map(|png| (ImageBlob::new("image/png", png), w, h)), xf);
}
Image::Stencil(s) => {
let white = self.white_images;
+5
View File
@@ -340,6 +340,11 @@ pub(super) fn rgba_png(rgba: Vec<u8>, w: u32, h: u32) -> Option<Vec<u8>> {
craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok()
}
pub(super) fn rgb_png(rgb: Vec<u8>, w: u32, h: u32) -> Option<Vec<u8>> {
let img = craft_image_codecs::Image::from_raw(w, h, craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, rgb).ok()?;
craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok()
}
pub(super) fn gray_png(gray: Vec<u8>, w: u32, h: u32) -> Option<Vec<u8>> {
let img = craft_image_codecs::Image::from_raw(w, h, craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, gray).ok()?;
craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok()
+7 -4
View File
@@ -215,7 +215,7 @@ fn stream_kind(pdf: &Pdf, id: ObjectIdentifier, dict: &Dict<'_>) -> String {
}
/// `bytes` for a message, in whole megabytes, or gigabytes when it is a whole number of them.
fn decoded_size(bytes: usize) -> String {
pub(crate) fn decoded_size(bytes: usize) -> String {
const GB: usize = 1 << 30;
if bytes >= GB && bytes.is_multiple_of(GB) { format!("{} GB", bytes / GB) } else { format!("{} MB", bytes >> 20) }
}
@@ -323,10 +323,13 @@ pub struct TrimPages {
pub bleed: [f64; 4],
}
/// Preserve the application's existing accepted file sizes. Ordinary stream decoding still
/// uses the shared reader's immutable per-document limits, and its input copy is fallible.
/// The shared reader's options: files of any size are accepted. Ordinary stream decoding uses the shared reader's immutable per-document limits, and its input
/// copy is fallible. One image may decode to the bytes and pixels of
/// [`crate::streams::image_limits`] for this build, past the shared reader's defaults.
pub(crate) fn open_options() -> craft_pdf::OpenOptions {
craft_pdf::OpenOptions { max_input_bytes: usize::MAX, ..Default::default() }
let (bytes, pixels) = crate::streams::image_limits(crate::streams::LARGE_IMAGES);
let decode_limits = craft_pdf::syntax::DecodeLimits::default().with_max_decoded_image(bytes).with_max_image_pixels(pixels);
craft_pdf::OpenOptions { max_input_bytes: usize::MAX, decode_limits }
}
pub(crate) fn open_with_options(bytes: &[u8], password: Option<&str>, options: &craft_pdf::OpenOptions) -> Result<Pdf, PdfError> {
+7 -2
View File
@@ -465,9 +465,14 @@ impl Default for SecuritySettings {
}
}
/// `v` lies in `lo..=hi` (and is a number).
/// `v` lies in `lo..=hi` (and is a number). The error names the range with its unit as one value
/// (`72–2400 ppi`), so a catalog can match the message and translate it.
pub(crate) fn within(name: &str, v: f64, lo: f64, hi: f64, unit: &str) -> Result<(), PdfError> {
if (lo..=hi).contains(&v) { Ok(()) } else { Err(PdfError::BadSetting(format!("{name} must be {lo}–{hi}{unit} (got {v})"))) }
if (lo..=hi).contains(&v) {
return Ok(());
}
let range = format!("{lo}–{hi}{unit}");
Err(PdfError::BadSetting(format!("{name} must be {range} (got {v})")))
}
impl PdfSettings {

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