Merge main into feat/palette-dimmed-rows

This commit is contained in:
dotCooCoo committed 2026-11-17 19:22:47 -08:00
commit ba8804bfe8
454 files changed
+33234 -2399

No files matched your search

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" }
+2
View File
@@ -128,11 +128,13 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
- 2026-11-14: Built-in Tech Circuit brush library: Circuit Trace (chamfered art with 45-degree elbows and terminal pads), Bus Lines (parallel conductor pattern) and Terminal Nodes (repeating solder pads, test points and leads), all original geometry generated in code. Ten built-in brush libraries; G5 remaining estimate 3–13 h (estimated), headline numbers unchanged.
- 2026-11-05: Window › Toolbars › Keep Tools Beside the Canvas, off by default, docks the Tools panel between left-side panels and the canvas instead of at the window's left edge, and the canvas's left edge then also docks a floating Tools panel (`window.toolsBesideCanvas`, #5395). Workspaces keep the setting; workspaces saved without it keep Tools at the window's edge. An optional VectorCraft layout choice; headline numbers unchanged.
- 2026-11-17: The canvas's left edge docks a floating Tools panel whichever way Keep Tools Beside the Canvas is set: a drop there, right of panels docked on the left, turns the setting on, and a drop on the window's left edge turns it off (#7837). Headline numbers unchanged.
- 2026-11-12: Stencil Bridges in the Cutting Tools add-on (Object › Plug-ins › Cutting Tools): strips of a set width are cut out of the selected art so that every island of a stencil cut from it (the inside of an O, a hole in a shape) stays attached to the sheet, by the shortest crossings first, vertical, horizontal or the shortest among 12 directions 15° apart, with up to 16 bridges per island; type is measured by its glyph outlines and stays type, and the original goes to a hidden layer or is replaced. One undo step (`addon.cutting.bridges`). A VectorCraft addition: headline numbers unchanged.
- 2026-11-13: Banner Hems and Grommets in the Cutting Tools add-on (Object › Plug-ins › Cutting Tools): on the chosen sides of the selected art's bounds, or of each artboard, a hem line at a set depth inside the edge and grommet marks (a circle with a cross) at a set inset, one at each end of a side and the rest spread evenly at most a set spacing apart, stroked in a chosen swatch; a dialog with Preview, one undo step (`addon.cutting.banner`). A VectorCraft addition: headline numbers unchanged.
- 2026-11-14: Nest Shapes in the Cutting Tools add-on (Object › Plug-ins › Cutting Tools): the selected objects move close together onto an artboard, a sheet of a set size or a roll of a set width, packed by their bounding boxes with a margin inside the edges and a spacing between them, optionally turning objects 90° to fit; objects that do not fit go in a column beside the sheet; a dialog with Preview, one undo step (`addon.cutting.nest`). A VectorCraft addition: headline numbers unchanged.
- 2026-11-15: With Smart Guides and Snap to Tangent on, a circle drawn from its center with the Ellipse tool (Alt and Shift) snaps its radius so that the circle touches a nearby path (a straight segment, a curve, or another circle from outside or inside) when the radius comes within the snapping tolerance of that size, and the touch point shows the "tangent" label. A VectorCraft addition: headline numbers unchanged.
- 2026-11-05: Release Type on a Path joins the Type Tools add-on (Object › Plug-ins › Type Tools): each selected type on a path splits into point type with the same text and attributes, on one straight line starting where its first character sat, and the plain path it was set on, with its exact shape and place in the stacking order and no paint; or keeps only the path or only the text, optionally leaving the original. A dialog with Preview, one undo step (`addon.type.releasePath`, #5532). A VectorCraft addition: headline numbers unchanged.
- 2026-11-14: Unit Converter add-on (Object › Plug-ins › Unit Converter): a panel with one field per unit (pt, picas, in, mm, cm, px, ft & in, m, yd, ft, Q, Ha) where a length typed in any field updates the others as it is typed; From Selection reads the selection's width or height, Apply sets it as one undo step, and each field copies its value with or without the unit (`addon.units.convert`, `addon.units.selectionSize`, #5528). A VectorCraft addition: headline numbers unchanged.
- 2026-11-04: New Document: the units chosen in Preset Details now belong to the chosen document, as the pane's options are listed for the selected preset; the chosen card shows them, every other Recent and Saved card keeps the units its document or preset was made in, and the built-in tabs still follow the chosen units, so switching between inches and millimetres no longer restyles every recent template. Scores and estimates unchanged.
- 2026-11-14: Packaging Tools add-on (Object › Plug-ins › Packaging Tools): fold line roles for dielines (Cut, Crease, Partial Cut, Perforation), each carried by the swatch on a path's top stroke through a per-document role table that native files keep; PDF prints a role line on its swatch's separation when that swatch is a spot color, as the default role swatches are, and SVG, DXF and HP-GL keep the stroke's color. Make Cut Line, Make Crease Line, Make Partial Cut Line and Make Perforation Line give the selected paths a role, overprinting by default, and make a missing role swatch; the Fold Lines panel counts each role in the selection or the document, and its Role Swatches… picks another swatch for a role (`addon.packaging.setRole`, `addon.packaging.roles`, `addon.packaging.setRoleSwatch`). A VectorCraft addition: headline numbers unchanged.
- 2026-11-16: Check Fold Lines in the Packaging Tools add-on (Object › Plug-ins › Packaging Tools, and the Fold Lines panel's Check button): the fold lines of the selection or the document are split into blanks, panels and hinges (cut lines bound the material, and creases, partial cuts and perforations divide it into panels), and 15 kinds of issue are listed, errors and warnings, each naming its lines: cut lines that enclose nothing or end loose, gaps closed within a tolerance, a cut on top of a crease, duplicate lines, creases that end inside a panel, divide nothing, lie outside the blank or are not straight, gaps too narrow to map, fold lines in a hole, panels joined by no crease, and fold lines on a non-printing layer. The panel lists the issues in the interface language; clicking one selects its lines (`addon.packaging.check`). A VectorCraft addition: headline numbers unchanged.
+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 }
+10
View File
@@ -43,6 +43,16 @@ impl eframe::App for App {
/// Restore the borderless caption, apply platform menu and pen input, and hand the frame to the
/// app's raw-input hook while the keyboard user is unconfined.
fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) {
// Without vsync, a main-window frame starts no sooner than the minimum interval after the
// last one. eframe runs this hook once per frame, shown or not, before egui reads the input.
// The frame's time moves on by the wait, and the hang report's frame time starts after it.
if raw.viewport_id == egui::ViewportId::ROOT {
if let Some(wait) = super::presentation::frame_wait(self.min_frame, self.last_frame_began.map(|t| t.elapsed())) {
std::thread::sleep(wait);
raw.time = raw.time.map(|time| time + wait.as_secs_f64());
}
self.last_frame_began = Some(std::time::Instant::now());
}
let _timed = BEACON.enter_timed(Stage::Input);
self.frame_start = Some(std::time::Instant::now());
// winit gives the window its caption back when it changes the window's flags (maximize,
+28 -10
View File
@@ -142,6 +142,11 @@ struct App {
display_profile: display_profile::Reader,
/// When this frame's input hook started, for the hang report's frame times (`hang_watch`).
frame_start: Option<std::time::Instant>,
/// The shortest time between the starts of two frames, while the window presents without vsync
/// ([`presentation::min_frame_interval`]).
min_frame: Option<std::time::Duration>,
/// When the last frame started, after its wait for [`Self::min_frame`].
last_frame_began: Option<std::time::Instant>,
}
/// `vectorcraft --help`. Headless work (convert, run, MCP) is `vectorcraft-cli`'s.
@@ -365,6 +370,10 @@ fn main() -> std::process::ExitCode {
let saved_window = saved.as_ref().and_then(|ui| ui.window);
#[cfg(feature = "wgpu")]
let gpu_pref = saved.as_ref().and_then(|ui| ui.engine_prefs.get("gpuPreference")).and_then(serde_json::Value::as_str);
// Preferences › Performance › Low-Latency Drawing; anything but `true` in the file is off.
#[cfg(feature = "wgpu")]
let low_latency_drawing =
saved.as_ref().and_then(|ui| ui.engine_prefs.get("lowLatencyDrawing")).and_then(serde_json::Value::as_bool).unwrap_or(false);
#[cfg(feature = "wgpu")]
let power_env = eframe::wgpu::PowerPreference::from_env();
#[cfg(feature = "wgpu")]
@@ -458,10 +467,11 @@ fn main() -> std::process::ExitCode {
let mut options = options;
// One frame queued, not two: the canvas is rasterized on the CPU and the GPU only
// composites it, so the window answers the pointer a frame sooner (#444).
// `--present-mode` and `--frame-latency` change it for a launch (`presentation`).
options.wgpu_options.surface = presentation.apply(eframe::egui_wgpu::SurfaceConfig::LOW_LATENCY);
// `--present-mode` and `--frame-latency` change it for a launch, and Low-Latency Drawing
// asks for no vsync when neither sets the mode (`presentation`).
options.wgpu_options.surface = presentation.apply(eframe::egui_wgpu::SurfaceConfig::LOW_LATENCY, low_latency_drawing);
// What the app asks for: the driver picks novsync's mode and may clamp the latency.
log::info!("requested window surface: {}", presentation::describe(&options.wgpu_options.surface, &presentation));
log::info!("requested window surface: {}", presentation::describe(&options.wgpu_options.surface, &presentation, low_latency_drawing));
// Only adapters that can show the window, in the order `gpu` gives (#306, #502).
if let eframe::egui_wgpu::WgpuSetup::CreateNew(create) = &mut options.wgpu_options.wgpu_setup {
create.native_adapter_selector = Some(gpu::selector(power, displays, compositor, left_out.adapters.clone(), startup.clone()));
@@ -508,6 +518,11 @@ fn main() -> std::process::ExitCode {
// For the hang report (`hang_watch`).
#[cfg(feature = "wgpu")]
let requested_surface = options.wgpu_options.surface;
// Without vsync, frames start at most 240 times a second (`presentation`).
#[cfg(feature = "wgpu")]
let min_frame = presentation::min_frame_interval(&requested_surface);
#[cfg(not(feature = "wgpu"))]
let min_frame = None;
// A panic that ends the window (egui-wgpu's own, #502) is caught here: never a crash.
let run = |options: eframe::NativeOptions, app_creator: eframe::AppCreator<'_>| {
#[cfg(target_os = "linux")]
@@ -591,14 +606,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!(
@@ -693,6 +709,8 @@ fn main() -> std::process::ExitCode {
monitors_listed: None,
display_profile: Default::default(),
frame_start: None,
min_frame,
last_frame_began: None,
}))
}),
)
+123 -15
View File
@@ -6,9 +6,17 @@
//! frames the swap chain may queue, 1 to 3. Unset, the app keeps its own surface settings. A flag
//! overrides its variable; a value that isn't one of these stops the app with a message, as
//! `--control` does. A launch that sets either one runs as its own app, as with `--new-instance`.
//! The surface the app asks for is logged at start-up.
//! Preferences › Performance › Low-Latency Drawing (`lowLatencyDrawing`, off by default, read at
//! start-up) asks for `novsync` when neither the flag nor the variable sets the mode. Whenever the
//! surface presents without vsync, frames start at most 240 times a second. The surface the app
//! asks for is logged at start-up, with where its present mode came from.
use std::ffi::OsString;
use std::time::Duration;
/// The most frames a second the window draws while it presents without vsync.
#[cfg(feature = "wgpu")]
pub const UNSYNCED_FRAME_CAP: u32 = 240;
/// A present mode the command line or the environment can ask for.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -54,6 +62,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()
}
@@ -95,25 +104,44 @@ impl Overrides {
Ok(Self { mode, latency })
}
/// `surface` with the overrides applied.
/// `surface` with the overrides applied. With Low-Latency Drawing on (`low_latency_drawing`) and
/// no present mode override, the mode is `novsync`.
#[cfg(feature = "wgpu")]
pub fn apply(&self, surface: eframe::egui_wgpu::SurfaceConfig) -> eframe::egui_wgpu::SurfaceConfig {
pub fn apply(&self, surface: eframe::egui_wgpu::SurfaceConfig, low_latency_drawing: bool) -> eframe::egui_wgpu::SurfaceConfig {
use eframe::wgpu::PresentMode;
let present_mode = match self.mode {
Some(Mode::Fifo) => PresentMode::Fifo,
Some(Mode::AutoVsync) => PresentMode::AutoVsync,
Some(Mode::NoVsync) => PresentMode::AutoNoVsync,
None if low_latency_drawing => PresentMode::AutoNoVsync,
None => surface.present_mode,
};
eframe::egui_wgpu::SurfaceConfig { present_mode, desired_maximum_frame_latency: self.latency.or(surface.desired_maximum_frame_latency) }
}
}
/// The present mode and frame latency `surface` asks for, for the start-up log:
/// "autovsync, frame latency 1", with "(override)"
/// after a value a flag or variable set.
/// The shortest time between the starts of two frames on `surface`: `None` with vsync, where the
/// display paces the frames, and 1/[`UNSYNCED_FRAME_CAP`] of a second without it.
#[cfg(feature = "wgpu")]
pub fn describe(surface: &eframe::egui_wgpu::SurfaceConfig, overrides: &Overrides) -> String {
pub fn min_frame_interval(surface: &eframe::egui_wgpu::SurfaceConfig) -> Option<Duration> {
use eframe::wgpu::PresentMode;
match surface.present_mode {
PresentMode::AutoNoVsync | PresentMode::Immediate | PresentMode::Mailbox => Some(Duration::from_secs(1) / UNSYNCED_FRAME_CAP),
PresentMode::AutoVsync | PresentMode::Fifo | PresentMode::FifoRelaxed => None,
}
}
/// How long a frame waits before it starts, `since_last` after the previous frame started, so that
/// frames start at least `min` apart. `None`: no wait (no cap, the first frame, or `min` has passed).
pub fn frame_wait(min: Option<Duration>, since_last: Option<Duration>) -> Option<Duration> {
min?.checked_sub(since_last?).filter(|wait| !wait.is_zero())
}
/// The present mode and frame latency `surface` asks for, for the start-up log:
/// "autovsync, frame latency 1", with "(override)" after a value a flag or variable set, and
/// "(preference)" after a present mode Low-Latency Drawing set.
#[cfg(feature = "wgpu")]
pub fn describe(surface: &eframe::egui_wgpu::SurfaceConfig, overrides: &Overrides, low_latency_drawing: bool) -> String {
use eframe::wgpu::PresentMode;
let mode = match surface.present_mode {
PresentMode::AutoVsync => "autovsync",
@@ -125,7 +153,8 @@ pub fn describe(surface: &eframe::egui_wgpu::SurfaceConfig, overrides: &Override
};
let latency = surface.desired_maximum_frame_latency.map_or("default".to_string(), |n| n.to_string());
let tag = |set: bool| if set { " (override)" } else { "" };
format!("{mode}{}, frame latency {latency}{}", tag(overrides.mode.is_some()), tag(overrides.latency.is_some()))
let mode_tag = if overrides.mode.is_none() && low_latency_drawing { " (preference)" } else { tag(overrides.mode.is_some()) };
format!("{mode}{mode_tag}, frame latency {latency}{}", tag(overrides.latency.is_some()))
}
#[cfg(test)]
@@ -223,20 +252,99 @@ mod tests {
use eframe::wgpu::PresentMode;
let app = SurfaceConfig::LOW_LATENCY;
// No override: the surface the app asks for is unchanged.
assert_eq!(Overrides::default().apply(app), app);
assert_eq!(Overrides::default().apply(app, false), app);
let latency = Overrides { mode: None, latency: Some(2) };
let s = latency.apply(app);
let s = latency.apply(app, false);
assert_eq!((s.present_mode, s.desired_maximum_frame_latency), (PresentMode::AutoVsync, Some(2)));
assert_eq!(describe(&s, &latency), "autovsync, frame latency 2 (override)");
assert_eq!(describe(&s, &latency, false), "autovsync, frame latency 2 (override)");
let fifo = Overrides { mode: Some(Mode::Fifo), latency: None };
let s = fifo.apply(app);
let s = fifo.apply(app, false);
assert_eq!((s.present_mode, s.desired_maximum_frame_latency), (PresentMode::Fifo, app.desired_maximum_frame_latency));
// Never a mode the driver may lack: no vsync lets wgpu fall back by support.
let novsync = Overrides { mode: Some(Mode::NoVsync), latency: Some(3) };
let s = novsync.apply(app);
let s = novsync.apply(app, false);
assert_eq!((s.present_mode, s.desired_maximum_frame_latency), (PresentMode::AutoNoVsync, Some(3)));
assert_eq!(describe(&s, &novsync), "novsync (override), frame latency 3 (override)");
assert_eq!(describe(&s, &novsync, false), "novsync (override), frame latency 3 (override)");
let unset = SurfaceConfig { present_mode: PresentMode::Fifo, desired_maximum_frame_latency: None };
assert_eq!(describe(&unset, &Overrides::default()), "fifo, frame latency default");
assert_eq!(describe(&unset, &Overrides::default(), false), "fifo, frame latency default");
}
/// Low-Latency Drawing alone asks for no vsync, through wgpu's fallback by support and never an
/// explicit Immediate or Mailbox; off, the app's surface is exactly its own.
#[cfg(feature = "wgpu")]
#[test]
fn low_latency_drawing_alone_presents_without_vsync_and_off_keeps_the_app_surface() {
use eframe::egui_wgpu::SurfaceConfig;
use eframe::wgpu::PresentMode;
let app = SurfaceConfig::LOW_LATENCY;
let none = Overrides::default();
assert_eq!(none.apply(app, false), app);
let s = none.apply(app, true);
assert_eq!(s.present_mode, PresentMode::AutoNoVsync);
assert_eq!(s.desired_maximum_frame_latency, app.desired_maximum_frame_latency);
let frames = app.desired_maximum_frame_latency.map_or("default".to_string(), |n| n.to_string());
assert_eq!(describe(&s, &none, true), format!("novsync (preference), frame latency {frames}"));
// A latency override still applies with the preference's mode.
let latency = Overrides { mode: None, latency: Some(2) };
let s = latency.apply(app, true);
assert_eq!((s.present_mode, s.desired_maximum_frame_latency), (PresentMode::AutoNoVsync, Some(2)));
assert_eq!(describe(&s, &latency, true), "novsync (preference), frame latency 2 (override)");
}
/// The flag and the variable each set the present mode over Low-Latency Drawing.
#[cfg(feature = "wgpu")]
#[test]
fn the_flag_and_the_variable_win_over_low_latency_drawing() {
use eframe::egui_wgpu::SurfaceConfig;
use eframe::wgpu::PresentMode;
let app = SurfaceConfig::LOW_LATENCY;
let flag = parse(&["--present-mode", "fifo"]).unwrap();
let s = flag.apply(app, true);
assert_eq!(s.present_mode, PresentMode::Fifo);
assert!(describe(&s, &flag, true).starts_with("fifo (override),"), "{}", describe(&s, &flag, true));
let var = Overrides::default().with_env(Some("autovsync".into()), None).unwrap();
let s = var.apply(app, true);
assert_eq!(s.present_mode, PresentMode::AutoVsync);
assert!(describe(&s, &var, true).starts_with("autovsync (override),"), "{}", describe(&s, &var, true));
// The flag wins over the variable, and both over the preference.
let both = parse(&["--present-mode=fifo"]).unwrap().with_env(Some("novsync".into()), None).unwrap();
assert_eq!(both.apply(app, true).present_mode, PresentMode::Fifo);
}
/// Frames start at most 240 times a second without vsync, from the preference or an override,
/// and the display paces them with vsync.
#[cfg(feature = "wgpu")]
#[test]
fn the_frame_cap_applies_only_without_vsync_at_240_frames_a_second() {
use eframe::egui_wgpu::SurfaceConfig;
use eframe::wgpu::PresentMode;
let app = SurfaceConfig::LOW_LATENCY;
let cap = Duration::from_secs(1) / 240;
assert_eq!(cap.as_nanos(), 4_166_666);
assert_eq!(min_frame_interval(&Overrides::default().apply(app, true)), Some(cap));
assert_eq!(min_frame_interval(&Overrides { mode: Some(Mode::NoVsync), latency: None }.apply(app, false)), Some(cap));
assert_eq!(min_frame_interval(&Overrides::default().apply(app, false)), None);
assert_eq!(min_frame_interval(&Overrides { mode: Some(Mode::Fifo), latency: None }.apply(app, true)), None);
for (mode, capped) in [
(PresentMode::Immediate, true),
(PresentMode::Mailbox, true),
(PresentMode::AutoNoVsync, true),
(PresentMode::Fifo, false),
(PresentMode::FifoRelaxed, false),
(PresentMode::AutoVsync, false),
] {
let s = SurfaceConfig { present_mode: mode, desired_maximum_frame_latency: Some(1) };
assert_eq!(min_frame_interval(&s).is_some(), capped, "{mode:?}");
}
}
#[test]
fn a_frame_waits_out_the_rest_of_the_minimum_interval() {
let min = Some(Duration::from_millis(4));
assert_eq!(frame_wait(min, Some(Duration::from_millis(1))), Some(Duration::from_millis(3)));
assert_eq!(frame_wait(min, Some(Duration::from_millis(4))), None);
assert_eq!(frame_wait(min, Some(Duration::from_millis(9))), None);
assert_eq!(frame_wait(min, None), None, "the first frame starts at once");
assert_eq!(frame_wait(None, Some(Duration::ZERO)), None, "no cap with vsync");
}
}
+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]
+238 -1
View File
@@ -753,6 +753,229 @@ impl Brush {
}
}
// ---------- stroke options ----------
/// The Scatter brush fields a stroke can set for itself ([`BrushKind::stroke_option_keys`]).
#[derive(Serialize, Deserialize)]
struct ScatterOptions {
size: (f64, f64),
spacing: (f64, f64),
scatter: (f64, f64),
rotation: (f64, f64),
modes: Option<[Variation; 4]>,
rotation_relative_to_path: bool,
colorization: Colorization,
}
/// The Art brush fields a stroke can set for itself.
#[derive(Serialize, Deserialize)]
struct ArtOptions {
width: f64,
width_mode: Option<Variation>,
width_max: Option<f64>,
flip_along: bool,
flip_across: bool,
overlap: bool,
colorization: Colorization,
}
/// The Pattern brush fields a stroke can set for itself.
#[derive(Serialize, Deserialize)]
struct PatternOptions {
scale: f64,
spacing: f64,
fit: PatternFit,
flip_along: bool,
flip_across: bool,
colorization: Colorization,
}
impl BrushKind {
/// The definition fields, by their `brush.options` names, that one stroke can set for itself
/// (the Brushes panel's Options of Selected Object, [`StrokeLayer::brush_options`]). A Bristle
/// brush has none.
pub fn stroke_option_keys(&self) -> &'static [&'static str] {
match self {
BrushKind::Calligraphic(_) => &["angle", "roundness", "size", "variation", "modes"],
BrushKind::Scatter(_) => &["size", "spacing", "scatter", "rotation", "modes", "rotation_relative_to_path", "colorization"],
BrushKind::Art(_) => &["width", "width_mode", "width_max", "flip_along", "flip_across", "overlap", "colorization"],
BrushKind::Pattern(_) => &["scale", "spacing", "fit", "flip_along", "flip_across", "colorization"],
BrushKind::Bristle(_) => &[],
}
}
/// The values of [`Self::stroke_option_keys`], as a JSON object. Calligraphic modes left to the
/// values are a `null` `modes`, so a stroke that sets them so keeps that setting.
fn option_values(&self) -> serde_json::Value {
let v = match self {
BrushKind::Calligraphic(c) => serde_json::to_value(c).map(|mut v| {
if let Some(o) = v.as_object_mut() {
o.entry("modes").or_insert(serde_json::Value::Null);
}
v
}),
BrushKind::Scatter(s) => serde_json::to_value(ScatterOptions {
size: s.size,
spacing: s.spacing,
scatter: s.scatter,
rotation: s.rotation,
modes: s.modes,
rotation_relative_to_path: s.rotation_relative_to_path,
colorization: s.colorization,
}),
BrushKind::Art(a) => serde_json::to_value(ArtOptions {
width: a.width,
width_mode: a.width_mode,
width_max: a.width_max,
flip_along: a.flip_along,
flip_across: a.flip_across,
overlap: a.overlap,
colorization: a.colorization,
}),
BrushKind::Pattern(p) => serde_json::to_value(PatternOptions {
scale: p.scale,
spacing: p.spacing,
fit: p.fit,
flip_along: p.flip_along,
flip_across: p.flip_across,
colorization: p.colorization,
}),
BrushKind::Bristle(_) => Ok(serde_json::Value::Object(serde_json::Map::new())),
};
v.unwrap_or_default()
}
/// Set the values of [`Self::stroke_option_keys`] from `v` (as [`Self::option_values`] gives
/// them). An error when a value is of the wrong kind.
fn set_option_values(&mut self, v: serde_json::Value) -> Result<(), serde_json::Error> {
match self {
BrushKind::Calligraphic(c) => *c = serde_json::from_value(v)?,
BrushKind::Scatter(s) => {
let o: ScatterOptions = serde_json::from_value(v)?;
(s.size, s.spacing, s.scatter, s.rotation, s.modes) = (o.size, o.spacing, o.scatter, o.rotation, o.modes);
(s.rotation_relative_to_path, s.colorization) = (o.rotation_relative_to_path, o.colorization);
}
BrushKind::Art(a) => {
let o: ArtOptions = serde_json::from_value(v)?;
(a.width, a.width_mode, a.width_max, a.flip_along, a.flip_across) = (o.width, o.width_mode, o.width_max, o.flip_along, o.flip_across);
(a.overlap, a.colorization) = (o.overlap, o.colorization);
}
BrushKind::Pattern(p) => {
let o: PatternOptions = serde_json::from_value(v)?;
(p.scale, p.spacing, p.fit, p.flip_along, p.flip_across, p.colorization) =
(o.scale, o.spacing, o.fit, o.flip_along, o.flip_across, o.colorization);
}
BrushKind::Bristle(_) => {}
}
Ok(())
}
}
/// Stroke option value `new` with each `null` item of an array taken from the same place in
/// `current`, an array of the same length: a stroke option that changes some items of a range or a
/// list of modes and keeps the others ([`Brush::with_stroke_options`]). Any other `new` is given as
/// it is.
pub fn keep_items(new: &serde_json::Value, current: &serde_json::Value) -> serde_json::Value {
match (new, current) {
(serde_json::Value::Array(n), serde_json::Value::Array(c)) if n.len() == c.len() => {
serde_json::Value::Array(n.iter().zip(c).map(|(n, c)| if n.is_null() { c.clone() } else { n.clone() }).collect())
}
_ => new.clone(),
}
}
impl Brush {
/// The brush as a stroke whose own settings are `options` draws it: each field of
/// [`BrushKind::stroke_option_keys`] in `options` replaces the brush's value (a `colorization`
/// object changes only the fields it gives), and the values are kept within their ranges
/// ([`Brush::sanitize`]). A `null` item of an array keeps the brush's item there
/// ([`keep_items`]). Fields the type does not take are passed over. An error when a value is of
/// the wrong kind.
pub fn with_stroke_options(&self, options: &serde_json::Map<String, serde_json::Value>) -> Result<Brush, String> {
let keys = self.kind.stroke_option_keys();
let mut values = self.kind.option_values();
let Some(o) = values.as_object_mut() else { return Ok(self.clone()) };
for (k, v) in options {
if !keys.contains(&k.as_str()) {
continue;
}
match (o.get_mut(k).and_then(serde_json::Value::as_object_mut), v.as_object()) {
(Some(inner), Some(fields)) if k == "colorization" => {
for (f, fv) in fields {
inner.insert(f.clone(), fv.clone());
}
}
// Set below, once the values the modes may follow are in.
_ if k == "modes" => {}
_ => {
let current = o.get(k).cloned().unwrap_or_default();
o.insert(k.clone(), keep_items(v, &current));
}
}
}
// A Hue Shift without a key takes the art's main color, as `Brush::from_json` gives it.
if let Some(c) = o.get_mut("colorization").and_then(serde_json::Value::as_object_mut)
&& c.get("method").and_then(serde_json::Value::as_str) == Some("hueShift")
&& c.get("key").is_none_or(serde_json::Value::is_null)
{
let key = art_colors(self.art()).first().copied().unwrap_or(vectorcraft_color::Color::BLACK);
c.insert("key".into(), serde_json::to_value(key).map_err(|e| e.to_string())?);
}
let mut b = self.clone();
b.kind.set_option_values(values.clone()).map_err(|e| e.to_string())?;
if let Some(m) = options.get("modes")
&& keys.contains(&"modes")
{
// A null item keeps the mode the brush with the other settings has: modes it leaves to
// its values follow the stroke's values, as they are kept within their ranges. Modes
// equal to those are left as the brush has them, so they keep following the values.
b.sanitize();
let current = match &b.kind {
BrushKind::Calligraphic(c) => serde_json::to_value(c.modes()).unwrap_or_default(),
BrushKind::Scatter(s) => serde_json::to_value(s.modes()).unwrap_or_default(),
_ => serde_json::Value::Null,
};
let modes = keep_items(m, &current);
if modes != current {
if let Some(o) = values.as_object_mut() {
o.insert("modes".into(), modes);
}
b = self.clone();
b.kind.set_option_values(values).map_err(|e| e.to_string())?;
}
}
b.sanitize();
Ok(b)
}
/// The stroke options of `options` that make the brush draw differently: each field of
/// [`BrushKind::stroke_option_keys`] whose value, after [`Self::with_stroke_options`], differs
/// from the brush's own, with that value (kept within its range). An error for a field the
/// type does not take and for a value of the wrong kind.
pub fn stroke_options_that_differ(
&self,
options: &serde_json::Map<String, serde_json::Value>,
) -> Result<serde_json::Map<String, serde_json::Value>, String> {
let keys = self.kind.stroke_option_keys();
if let Some(k) = options.keys().find(|k| !keys.contains(&k.as_str())) {
return Err(if keys.is_empty() {
format!("a {} brush has no options of its own on a stroke", self.kind.label().to_lowercase())
} else {
format!("a {} brush's stroke options do not include `{k}` (they are {})", self.kind.label().to_lowercase(), keys.join(", "))
});
}
let edited = self.with_stroke_options(options)?.kind.option_values();
let own = self.kind.option_values();
Ok(keys
.iter()
.filter_map(|k| {
let v = edited.get(*k)?;
(own.get(*k) != Some(v)).then(|| ((*k).to_string(), v.clone()))
})
.collect())
}
}
// ---------- library ----------
/// The brush library of `doc`: its stored brushes, or the defaults when it has none.
@@ -842,8 +1065,22 @@ fn tolerance(scale: f64) -> f64 {
/// Filled art for one brushed stroke along `bp`, in `doc`. Pieces are in document space with id
/// 0, and never draw a brushed stroke (so they never recurse): their own strokes carry no brush,
/// and what they draw by name that would draw one is left out ([`leave_out_brushed`]).
/// Stroke-level opacity/blend are the caller's job (`StrokeLayer::opacity`).
/// Stroke-level opacity/blend are the caller's job (`StrokeLayer::opacity`). The stroke's own
/// brush settings ([`StrokeLayer::brush_options`]) replace the brush's values
/// ([`Brush::with_stroke_options`]); settings that do not read draw the brush as it is.
pub fn stroke_pieces(doc: &Document, brush: &Brush, bp: &BezPath, stroke: &StrokeLayer) -> Vec<Node> {
let edited;
let brush = if stroke.brush_options.is_empty() {
brush
} else {
match brush.with_stroke_options(&stroke.brush_options) {
Ok(b) => {
edited = b;
&edited
}
Err(_) => brush,
}
};
let w = if stroke.width > 0.0 { stroke.width } else { 1.0 };
let mut out = match &brush.kind {
BrushKind::Calligraphic(c) => calli::calligraphic(c, bp, w, stroke, &brush.name),
+98
View File
@@ -1,3 +1,4 @@
use serde_json::json;
use vectorcraft_color::{Color, Paint};
use vectorcraft_doc::{Appearance, Document, Node, NodeId, NodeKind, StrokeLayer};
use vectorcraft_geom::{Affine, BezPath, Point, Rect, Vec2, shapes};
@@ -2037,3 +2038,100 @@ fn a_straight_run_keeps_the_same_node_kinds_as_a_bend() {
}
}
}
/// `options` as a stroke's own brush settings.
fn with_options(options: serde_json::Value) -> StrokeLayer {
StrokeLayer { brush_options: options.as_object().cloned().unwrap_or_default(), ..stroke(1.0) }
}
#[test]
fn a_strokes_own_options_change_its_art_and_leave_the_brush() {
let doc = Document::new(1.0, 1.0);
let brush = art_brush(rect_art(10.0, 4.0), ArtScale::Stretch);
let path = line(20.0, 50.0, 220.0, 50.0);
let half = stroke_pieces(&doc, &brush, &path, &with_options(json!({"width": 50.0})));
assert!(near(bounds(&half).height(), 2.0, 1e-6), "width 50% halves the art across the stroke: {:?}", bounds(&half));
assert!(near(bounds(&stroke_pieces(&doc, &brush, &path, &stroke(1.0))).height(), 4.0, 1e-6), "a stroke without options draws the brush");
let BrushKind::Art(a) = &brush.kind else { panic!("art brush") };
assert_eq!(a.width, 100.0, "the brush keeps its width");
// A calligraphic stroke's own size and angle.
let nib = stroke_pieces(&doc, &calli(0.0, 20.0, 10.0), &line(0.0, 0.0, 100.0, 0.0), &with_options(json!({"angle": 90.0})));
assert!(near(bounds(&nib).height(), 10.0, 0.05), "{:?}", bounds(&nib));
// A pattern stroke's own scale doubles the tiles across it.
let pattern = pattern_brush(PatternFit::Stretch, false);
let plain = bounds(&stroke_pieces(&doc, &pattern, &path, &stroke(1.0))).height();
let doubled = bounds(&stroke_pieces(&doc, &pattern, &path, &with_options(json!({"scale": 200.0})))).height();
assert!(near(doubled, plain * 2.0, 1e-6), "{plain} → {doubled}");
}
#[test]
fn stroke_options_are_checked_and_kept_within_their_ranges() {
let brush = art_brush(rect_art(10.0, 4.0), ArtScale::Stretch);
let map = |v: serde_json::Value| v.as_object().cloned().unwrap_or_default();
// Out of range: clamped; equal to the brush's own value: left out.
let got = brush.stroke_options_that_differ(&map(json!({"width": 5000.0, "flip_along": false}))).unwrap();
assert_eq!(serde_json::Value::Object(got), json!({"width": 1000.0}));
// A field the type does not take, and a value of the wrong kind, are errors.
assert!(brush.stroke_options_that_differ(&map(json!({"angle": 10.0}))).unwrap_err().contains("angle"));
assert!(brush.stroke_options_that_differ(&map(json!({"width": "wide"}))).is_err());
let bristle = Brush { name: "b".into(), kind: BrushKind::Bristle(Bristle::default()) };
assert!(bristle.stroke_options_that_differ(&map(json!({"size": 2.0}))).is_err());
assert!(bristle.stroke_options_that_differ(&map(json!({}))).unwrap().is_empty());
// A colorization object changes only the fields it gives: Hue Shift keeps the key it has.
let key = Color::rgb(0.0, 0.0, 1.0);
let hue = Brush {
name: "h".into(),
kind: BrushKind::Art(ArtBrush { art: rect_art(10.0, 4.0), colorization: Colorization::HueShift { key }, ..Default::default() }),
};
let tints = hue.with_stroke_options(&map(json!({"colorization": {"method": "tints"}}))).unwrap();
assert_eq!(tints.kind.colorization(), Colorization::Tints);
let back = hue.stroke_options_that_differ(&map(json!({"colorization": {"method": "hueShift"}}))).unwrap();
assert!(back.is_empty(), "the brush's own colorization: {back:?}");
// Hue Shift without a key takes the art's main color, as brush.options gives it.
let keyless = tints.stroke_options_that_differ(&map(json!({"colorization": {"method": "hueShift"}}))).unwrap();
let want = art_colors(tints.art()).first().copied().unwrap_or(Color::BLACK);
assert_eq!(keyless["colorization"]["method"], json!("hueShift"));
assert_eq!(keyless["colorization"]["key"], serde_json::to_value(want).unwrap());
// Settings that do not read draw the brush as it is.
let doc = Document::new(1.0, 1.0);
let path = line(20.0, 50.0, 220.0, 50.0);
let odd = stroke_pieces(&doc, &brush, &path, &with_options(json!({"width": [1, 2]})));
assert!(near(bounds(&odd).height(), 4.0, 1e-6));
}
#[test]
fn null_stroke_option_items_keep_the_items_the_stroke_has() {
let map = |v: serde_json::Value| v.as_object().cloned().unwrap_or_default();
// A scatter brush at fixed sizes, with no modes of its own: they follow its values.
let b = Brush { name: "s".into(), kind: BrushKind::Scatter(Scatter { size: (100.0, 100.0), ..Default::default() }) };
let BrushKind::Scatter(s) = b.with_stroke_options(&map(json!({"size": [null, 150]}))).unwrap().kind else { panic!("scatter") };
assert_eq!(s.size, (100.0, 150.0), "the smallest size stays the brush's");
// A stroke whose sizes vary keeps that random size mode when it sets only the spacing mode.
let e = b.with_stroke_options(&map(json!({"size": [50, 80], "modes": [null, "pressure", null, null]}))).unwrap();
let BrushKind::Scatter(s) = e.kind else { panic!("scatter") };
assert_eq!(s.modes(), [Variation::Random, Variation::Pressure, Variation::Fixed, Variation::Fixed]);
// The kept modes follow the values as they are kept within their ranges.
let c = calli(0.0, 100.0, 3.0).with_stroke_options(&map(json!({"variation": [-2, 0, 0], "modes": [null, "pressure", null]}))).unwrap();
let BrushKind::Calligraphic(c) = c.kind else { panic!("calligraphic") };
assert_eq!(c.modes(), [Variation::Fixed, Variation::Pressure, Variation::Fixed]);
// Modes that change nothing are no setting of the stroke's: they keep following its values.
let same = b.stroke_options_that_differ(&map(json!({"modes": [null, null, null, null]}))).unwrap();
assert!(same.is_empty(), "{same:?}");
}
#[test]
fn a_null_calligraphic_modes_setting_stays_when_another_value_changes() {
let map = |v: serde_json::Value| v.as_object().cloned().unwrap_or_default();
// A brush whose modes are its own, and a stroke whose modes follow its values instead.
let mut b = calli(0.0, 100.0, 3.0);
if let BrushKind::Calligraphic(c) = &mut b.kind {
c.modes = Some([Variation::Pressure; 3]);
}
let got = b.stroke_options_that_differ(&map(json!({"modes": null, "angle": 30.0}))).unwrap();
assert_eq!(serde_json::Value::Object(got), json!({"modes": null, "angle": 30.0}));
let BrushKind::Calligraphic(c) = b.with_stroke_options(&map(json!({"modes": null, "angle": 30.0}))).unwrap().kind else { panic!("calligraphic") };
assert_eq!(c.modes(), [Variation::Fixed; 3], "the stroke draws with the modes its values give");
// A brush whose modes follow its values: a null `modes` is the brush's own and is left out.
let plain = calli(0.0, 100.0, 3.0).stroke_options_that_differ(&map(json!({"modes": null}))).unwrap();
assert!(plain.is_empty(), "{plain:?}");
}
+7 -1
View File
@@ -294,13 +294,19 @@ impl GuideOptions {
}
}
/// The share of the way to its target (black or white, cool or warm, gray or full color) that the
/// variation at `step` goes: 0 at the center, the options' reach at the outermost steps.
pub fn step_fraction(opts: &GuideOptions, step: i32) -> f32 {
(step.unsigned_abs() as f32 / opts.steps.max(1) as f32).min(1.0) * opts.reach()
}
/// Variation of `c` at `step` (−steps..=steps: negative towards shades/cool/muted, positive towards
/// tints/warm/vivid; 0 is `c` itself), in `c`'s model.
pub fn variation(c: Color, opts: &GuideOptions, step: i32) -> Color {
if step == 0 {
return c;
}
let f = (step.unsigned_abs() as f32 / opts.steps.max(1) as f32).min(1.0) * opts.reach();
let f = step_fraction(opts, step);
let v = match opts.variation {
Variation::TintsShades => c.lerp(if step < 0 { &Color::BLACK } else { &Color::WHITE }, f),
Variation::WarmCool => {
+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 }
+6
View File
@@ -71,6 +71,11 @@ pub struct StrokeLayer {
/// Brush applied to the stroke (by brush name).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub brush: Option<String>,
/// This stroke's own brush settings (the Brushes panel's Options of Selected Object): brush
/// definition fields, by their `brush.options` names, that replace the brush's values on this
/// stroke only. Empty: the stroke draws the brush as it is. `vectorcraft-brush` reads them.
#[serde(default, skip_serializing_if = "serde_json::Map::is_empty")]
pub brush_options: serde_json::Map<String, serde_json::Value>,
#[serde(default = "one", skip_serializing_if = "crate::skip::is_one")]
pub opacity: f32,
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
@@ -170,6 +175,7 @@ impl StrokeLayer {
arrow_scale: (100.0, 100.0),
profile: None,
brush: None,
brush_options: serde_json::Map::new(),
opacity: 1.0,
blend: BlendMode::Normal,
visible: true,
+106
View File
@@ -2174,6 +2174,70 @@ pub fn blend_steps(keys: &[Arc<Node>], spec: &BlendSpec) -> Vec<usize> {
StepCount::default().blend(keys, spec, Rail::new(keys, spec).as_ref()).0
}
/// Does each pair of `keys` blended with `spec` ask for the same number of steps
/// ([`blend_step_count`]) when each coordinate it counts from moves by up to `length` points and,
/// for Smooth Color, the difference between keys of different colors by up to `color` (0 to 1)?
/// False when a count sits that close to where it changes, and for Smooth Color by distance when
/// the keys are at most `4 × length` wide or high. Specified Steps always asks for the same number.
pub fn blend_steps_settled(keys: &[Arc<Node>], spec: &BlendSpec, length: f64, color: f64) -> bool {
let rail = Rail::new(keys, spec);
keys.windows(2).enumerate().all(|(i, w)| {
let [a, b] = w else { return true };
match spec.spacing {
BlendSpacing::Steps(_) => true,
// The count is `len / d` rounded, which grows with `len`.
BlendSpacing::Distance(d) => {
let len = rail.as_ref().map_or_else(|| center_of(a).distance(center_of(b)), |r| r.len(i));
let count = |len: f64| blend_step_count(a, b, BlendSpacing::Distance(d), len);
count(len - length) == count(len + length)
}
BlendSpacing::SmoothColor => smooth_color_settled(a, b, length, color),
}
})
}
/// [`blend_steps_settled`] for one pair of Smooth Color keys. Each count [`blend_step_count`]
/// takes grows with what it counts from (the color difference, the keys' reach, the distance
/// between their edges in key sizes), so the pair is settled when the least and the most of
/// these ask for the same count.
fn smooth_color_settled(a: &Node, b: &Node, length: f64, color: f64) -> bool {
let bounds = a.visual_bounds().zip(b.visual_bounds());
let by_level = |d: f64| level_steps(d.max(0.0)) as usize;
match (color_distance(a, b), bounds) {
// Colors that differ, but by too little to count, or by little more: moving them may cross
// where they stop counting as the same. (The same colors stay the same.)
(Some(d), _) if d > 0.0 && d * 255.0 <= 1e-3 + color * 255.0 => false,
(Some(d), Some((ba, bb))) if d * 255.0 > 1e-3 => {
let (ca, cb) = (ba.center(), bb.center());
let reach =
[(ca.x - cb.x).abs(), (ca.y - cb.y).abs(), ba.width(), ba.height(), bb.width(), bb.height()].into_iter().fold(0.0f64, f64::max);
// The centers and sizes move by up to twice `length`.
let by_density = |r: f64| (8.0 * r.max(0.0) + 0.5).floor().clamp(1.0, 254.0) as usize;
let least = by_level(d - color).min(by_density(reach - 2.0 * length));
let most = by_level(d + color).min(by_density(reach + 2.0 * length));
reach.is_finite() && least == most
}
(Some(d), None) if d * 255.0 > 1e-3 => by_level(d - color) == by_level(d + color),
(_, Some((ba, bb))) => {
let (w, h) = ((ba.width() + bb.width()) / 2.0, (ba.height() + bb.height()) / 2.0);
if w <= 4.0 * length || h <= 4.0 * length {
return false;
}
let dx = (ba.x0 - bb.x0).abs().max((ba.x1 - bb.x1).abs());
let dy = (ba.y0 - bb.y0).abs().max((ba.y1 - bb.y1).abs());
// Each edge moves by up to `length`: the distances between them by up to twice that,
// and the mean sizes too.
let q = |dx: f64, dy: f64, w: f64, h: f64| (dx.max(0.0) / w).max(dy.max(0.0) / h);
let count = |q: f64| ((q + 0.5).floor() - 1.0).clamp(1.0, 1000.0) as usize;
let m = 2.0 * length;
let least = q(dx - m, dy - m, w + m, h + m);
let most = q(dx + m, dy + m, w - m, h - m);
least.is_finite() && most.is_finite() && count(least) == count(most)
}
(_, None) => true,
}
}
/// Evaluate a blend: the keys and generated steps in paint order. The steps keep to
/// [`MAX_BLEND_STEPS`] in all ([`blend_steps`]).
pub fn blend_expand(keys: &[Arc<Node>], spec: &BlendSpec) -> Vec<Node> {
@@ -3535,4 +3599,46 @@ mod tests {
let (keys, spec) = blend_parts(&outer).unwrap();
assert_eq!(blend_steps(keys, spec), vec![99]);
}
/// A count is settled when moving the lengths by 0.01 pt and the colors by 0.001 can't change
/// it: Specified Steps always; Specified Distance unless the spine's length is a half step from
/// where its count changes; Smooth Color unless the colors differ by too little to count, the
/// color difference or the keys' reach sits where its count changes, or keys of the same color
/// are at most four times 0.01 pt wide.
#[test]
fn steps_settle_unless_rounding_can_change_their_count() {
let (length, color) = (0.01, 0.001);
let settled = |a: Node, b: Node, spacing: BlendSpacing| {
let spec = BlendSpec { spacing, ..Default::default() };
blend_steps_settled(&[Arc::new(a), Arc::new(b)], &spec, length, color)
};
let filled = |x: f64, size: f64, c: Color| smooth_key((x, 0.0), (size, size), Paint::solid(c), Paint::None, 0.0);
let gray = |x: f64| filled(x, 10.0, Color::rgb(0.5, 0.5, 0.5));
// The keys' centers are 100 pt apart: 100 / 25 is 4, and 100 / (100 / 3.5) is 3.5.
assert!(settled(gray(0.0), gray(100.0), BlendSpacing::Steps(3)));
assert!(settled(gray(0.0), gray(100.0), BlendSpacing::Distance(25.0)));
assert!(!settled(gray(0.0), gray(100.0), BlendSpacing::Distance(100.0 / 3.5)));
// Smooth Color between colors that differ: by a 2,000th of a step, by 51 steps of 255
// (settled) and by 51.5 (where the count changes).
let red = |x: f64, r: f32| filled(x, 10.0, Color::rgb(r, 0.0, 0.0));
assert!(!settled(red(0.0, 0.0), red(100.0, 0.0005), BlendSpacing::SmoothColor));
assert!(settled(red(0.0, 0.0), red(100.0, 51.0 / 255.0), BlendSpacing::SmoothColor));
assert!(!settled(red(0.0, 0.0), red(100.0, 51.5 / 255.0), BlendSpacing::SmoothColor));
// Black to white is counted by the keys' reach, eight steps a point: 10 pt is settled,
// 10.0625 pt (80.5 steps) is not.
let near = |size: f64| settled(filled(0.0, size, Color::BLACK), filled(5.0, size, Color::WHITE), BlendSpacing::SmoothColor);
assert!(near(10.0));
assert!(!near(10.0625));
// Keys without bounds are counted by their colors alone.
let bare = |r: f32| Node::path(NodeId(1), PathData::default(), Appearance::basic(Paint::solid(Color::rgb(r, 0.0, 0.0)), Paint::None, 0.0));
assert!(settled(bare(0.0), bare(51.0 / 255.0), BlendSpacing::SmoothColor));
assert!(!settled(bare(0.0), bare(51.5 / 255.0), BlendSpacing::SmoothColor));
// Keys of the same color are counted by distance in key sizes; keys 0.04 pt wide or less
// are never settled.
assert!(settled(gray(0.0), gray(100.0), BlendSpacing::SmoothColor));
assert!(!settled(filled(0.0, 0.04, Color::rgb(0.5, 0.5, 0.5)), filled(100.0, 0.04, Color::rgb(0.5, 0.5, 0.5)), BlendSpacing::SmoothColor));
assert!(settled(filled(0.0, 0.05, Color::rgb(0.5, 0.5, 0.5)), filled(100.0, 0.05, Color::rgb(0.5, 0.5, 0.5)), BlendSpacing::SmoothColor));
}
}
+4 -1
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;
@@ -165,7 +168,7 @@ use limits::MAX_NEXT_ID;
pub use limits::{DocError, FORMAT_VERSION, MAX_COORD};
pub use records::{ImageBlob, MaskEdit, NewArtIds, SavedSelection, SavedView, SvgFilter, Symbol, SymbolEdit};
pub use stored_art::{StoredPlace, StoredRoot};
pub use units::{ColorMode, Unit, parse_number};
pub use units::{ColorMode, Unit, decimal_point, finite_in_every_unit, parse_number};
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Document {
+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
+2 -2
View File
@@ -32,8 +32,8 @@ pub use para_style::{
pub use runs::PATH_LEAD_MAX;
pub use runs::{INLINE_CHAR, INLINE_MAX_SCALE, InlineArt, RubyAlign, RubyPosition, RubySpan, TextKind, TextRun, TextStyleDef, TypeAntiAlias};
pub use tabs_lists::{
Bullet, DEFAULT_TAB_INTERVAL, LIST_HANGING_INDENT, LIST_LEVEL_INDENT, LIST_LEVELS, ListAlign, ListCounts, NumberStyle, ParaList, TabAlign,
TabStop,
Bullet, DEFAULT_TAB_INTERVAL, LIST_HANGING_INDENT, LIST_LEVEL_INDENT, LIST_LEVELS, ListAlign, ListCounts, MAX_LIST_START, NumberStyle, ParaList,
TabAlign, TabStop,
};
pub use wrap::{resolve_wrap, wrap_outline, wrap_sources, wrap_work};
+54 -11
View File
@@ -27,7 +27,11 @@ impl TextObject {
/// Character attributes as presented by controls (stored runs stay local for layout
/// and rich-text clipboard operations). Explicit vertical character scale stays separate.
pub fn effective_char_style(&self, style: &CharStyle) -> Option<CharStyle> {
let scale = self.style_scale()?;
Self::scaled_char_style(style, self.style_scale()?)
}
/// `style` with `scale` taken into its attributes ([`Self::effective_char_style`]).
fn scaled_char_style(style: &CharStyle, scale: TextStyleScale) -> Option<CharStyle> {
let mut style = style.clone();
style.size *= scale.points;
style.leading = style.leading.map(|v| v * scale.points);
@@ -57,19 +61,27 @@ impl TextObject {
/// scale from `xf`, so panels show document-point sizes without a separate transform factor.
/// Returns `false` when there is nothing to bake (identity scale or an unrepresentable
/// transform).
///
/// Type on a path bakes only the uniform part of the scale (the vertical one) and keeps any
/// stretch in `xf`: its brackets and glyphs sit at fractions of the path's length, which a
/// non-uniform scale of the path would move, and a uniform one keeps.
pub fn scale_text_attributes(&mut self) -> bool {
let Some(scale) = self.style_scale() else { return false };
if (scale.points - 1.0).abs() <= 1e-12 && (scale.horizontal - 1.0).abs() <= 1e-12 {
let Some(mut scale) = self.style_scale() else { return false };
let [a, b, c, d, _, _] = self.xf.as_coeffs();
let (mut sx, sy) = (a.hypot(b), c.hypot(d));
if sx <= 1e-12 || sy <= 1e-12 {
return false;
}
let [a, b, c, d, _, _] = self.xf.as_coeffs();
let (sx, sy) = (a.hypot(b), c.hypot(d));
if sx <= 1e-12 || sy <= 1e-12 {
if matches!(self.kind, TextKind::OnPath { .. }) {
scale.horizontal = 1.0;
sx = sy;
}
if (scale.points - 1.0).abs() <= 1e-12 && (scale.horizontal - 1.0).abs() <= 1e-12 {
return false;
}
let mut baked = Vec::with_capacity(self.runs.len());
for run in &self.runs {
let Some(eff) = self.effective_char_style(&run.style) else { return false };
let Some(eff) = Self::scaled_char_style(&run.style, scale) else { return false };
baked.push(eff);
}
for (run, style) in self.runs.iter_mut().zip(baked) {
@@ -78,6 +90,14 @@ impl TextObject {
// Character strokes are drawn in text space: widen them by the vertical scale we remove.
self.scale_char_strokes(1.0 / sy);
self.xf *= Affine::scale_non_uniform(1.0 / sx, 1.0 / sy);
// An area's frame and a path type's path are drawn through `xf` too: give them the scale
// `xf` loses, so the frame (and so the line breaks) and the path stay where they were.
let grow = Affine::scale_non_uniform(sx, sy);
match &mut self.kind {
TextKind::Area { frame } => frame.transform(grow),
TextKind::OnPath { path, .. } => path.transform(grow),
TextKind::Point => {}
}
self.cached_bounds = None;
self.cached_baselines.clear();
self.cached_ink = None;
@@ -284,17 +304,40 @@ impl TextObject {
/// Update the paragraph styles for replacing bytes `start..end` of the current plain text by
/// `insert` (call before changing the runs). The paragraph the range starts in keeps its
/// style (merging paragraphs: the first one's wins); paragraphs the insertion starts take that
/// style too (Return continues the paragraph it splits); later paragraphs keep theirs.
/// style too (Return continues the paragraph it splits), without the number its list gives it
/// ([`ParaList::start`]); later paragraphs keep theirs. When an insertion that starts new
/// paragraphs is made at the start of a paragraph and some of that paragraph's text stays
/// after it, that number moves with the text to the last paragraph the insertion starts.
pub fn splice_paras(&mut self, start: usize, end: usize, insert: &str) {
if self.paras.is_empty() {
let added = insert.bytes().filter(|&b| b == b'\n').count();
let numbered = |p: &ParaStyle| p.list.is_some_and(|l| l.start.is_some());
// With one style for every paragraph, the new paragraphs take it as it is unless its list
// gives the paragraph a number.
if self.paras.is_empty() && (added == 0 || !numbered(&self.para)) {
return;
}
let r = self.paragraphs_in(start, end);
let v = self.paragraph_styles();
let Some(keep) = v.get(r.start).cloned() else { return };
let added = insert.bytes().filter(|&b| b == b'\n').count();
let Some(mut keep) = v.get(r.start).cloned() else { return };
let given = keep.list.and_then(|l| l.start);
if let Some(l) = keep.list.as_mut() {
l.start = None;
}
let mut out: Vec<ParaStyle> = v.iter().take(r.start + 1).cloned().collect();
out.extend(std::iter::repeat_n(keep, added));
let text = self.plain_text();
let (at, to) = (start.min(end).min(text.len()), start.max(end).min(text.len()));
let at_para_start = text.as_bytes().get(..at).is_some_and(|b| b.last().is_none_or(|&c| c == b'\n'));
// The paragraph's text after the replaced bytes, which the last new paragraph then holds.
let text_kept = r.len() == 1 && text.as_bytes().get(to).is_some_and(|&c| c != b'\n');
if given.is_some() && added > 0 && at_para_start && text_kept {
if let Some(l) = out.get_mut(r.start).and_then(|p| p.list.as_mut()) {
l.start = None;
}
if let Some(l) = out.last_mut().and_then(|p| p.list.as_mut()) {
l.start = given;
}
}
out.extend(v.iter().skip(r.end).cloned());
self.paras = out;
if let Some(first) = self.paras.first() {
+38 -5
View File
@@ -206,15 +206,41 @@ pub struct ParaList {
/// ([`Self::depth`]). The file saves it only when it is not 1.
#[serde(skip_serializing_if = "is_first_level", deserialize_with = "read_level")]
pub level: u8,
/// The number a numbered paragraph is given, 1 to [`MAX_LIST_START`]: the numbered paragraphs
/// after it at its level count on from it ([`Self::next_marker`]). None: it counts on from the
/// numbered paragraph before it. A bulleted paragraph does not use it. A paragraph made
/// with Return in a paragraph that has one does not take it, and a paragraph style does not
/// keep it. A saved number outside the range is read as the nearest one. The file saves it
/// only when it is set.
#[serde(skip_serializing_if = "Option::is_none", deserialize_with = "read_start")]
pub start: Option<u32>,
}
impl Default for ParaList {
/// A bulleted list with a dot, its marker aligned left, at level 1.
/// A bulleted list with a dot, its marker aligned left, at level 1, numbered on from the
/// paragraph before.
fn default() -> Self {
Self { bullet: Bullet::default(), number: None, align: ListAlign::default(), level: 1 }
Self { bullet: Bullet::default(), number: None, align: ListAlign::default(), level: 1, start: None }
}
}
/// The largest number a numbered paragraph can be given ([`ParaList::start`]).
pub const MAX_LIST_START: u32 = 999_999_999;
/// Reads a saved list start, a whole number or null, as the nearest of 1 to [`MAX_LIST_START`],
/// so a start such as 0 or 5000000000 opens the file at 1 or [`MAX_LIST_START`]. Anything else
/// is an error.
fn read_start<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<u32>, D::Error> {
let start = match serde_json::Value::deserialize(d)? {
serde_json::Value::Null => return Ok(None),
serde_json::Value::Number(n) if n.is_i64() || n.is_u64() => {
n.as_i64().map_or(i64::from(MAX_LIST_START), |n| n.clamp(1, i64::from(MAX_LIST_START)))
}
_ => return Err(serde::de::Error::custom("a list start must be a whole number")),
};
Ok(u32::try_from(start).ok())
}
/// Is `level` the first list level, which the file does not save?
fn is_first_level(level: &u8) -> bool {
*level == 1
@@ -307,6 +333,12 @@ impl ParaList {
Self { level, ..self }
}
/// This list with the paragraph numbered `start` (1 to [`MAX_LIST_START`]; None: on from the
/// paragraph before).
pub fn starting_at(self, start: Option<u32>) -> Self {
Self { start, ..self }
}
/// The list's level, 1 to [`LIST_LEVELS`]: [`Self::level`], a value outside the range taken
/// as the nearest level.
pub fn depth(&self) -> usize {
@@ -334,8 +366,9 @@ impl ParaList {
/// paragraph has none and leaves the counts as they are. A paragraph with text sets the counts
/// of the levels deeper than its own back to 0, so a deeper paragraph after it counts from 1
/// again; a bulleted one has its bullet and leaves the count of its level as it is, and a
/// numbered one adds one to the count of its level and is numbered with it. A paragraph back
/// at a shallower level then goes on with that level's count.
/// numbered one adds one to the count of its level and is numbered with it, or with the number
/// it is given ([`Self::start`]), which becomes the count of its level. A paragraph back at a
/// shallower level then goes on with that level's count.
pub fn next_marker(list: Option<ParaList>, empty: bool, counts: &mut ListCounts) -> Option<String> {
let Some(list) = list else {
*counts = ListCounts::default();
@@ -350,7 +383,7 @@ impl ParaList {
}
let count = &mut counts.0[level];
if list.number.is_some() {
*count = count.saturating_add(1);
*count = list.start.map_or_else(|| count.saturating_add(1), |s| s.clamp(1, MAX_LIST_START));
}
Some(list.marker(*count))
}
+93
View File
@@ -456,6 +456,99 @@ fn list_levels_count_their_own_numbers_and_save_only_past_the_first() {
assert_eq!(opened.list_level_counts, (1..=8).collect::<Vec<u32>>(), "a file keeps only the counts of levels 2 to 9");
}
/// A numbered paragraph given a number shows it, and the numbered paragraphs after it at its level
/// count on from it; deeper levels still count from 1 after it, a bulleted or empty paragraph does
/// not use the number, and a paragraph in no list still starts the count again. The file saves the
/// number only when it is set, and a saved number outside 1 to 999999999 reads as the nearest one.
#[test]
fn a_numbered_paragraph_given_a_number_starts_its_level_count_there() {
let num = |level, start| Some(ParaList::numbered(NumberStyle::Arabic).at_level(level).starting_at(start));
let dot = Some(ParaList::bulleted(Bullet::Dot).starting_at(Some(7)));
let mut counts = ListCounts::default();
let markers: Vec<Option<String>> = [
(num(1, None), false),
(num(1, Some(5)), false),
(num(1, None), false),
(num(2, None), false),
(num(2, Some(1)), false),
(num(2, None), false),
(num(1, None), false),
(num(1, Some(9)), true),
(num(1, None), false),
(dot, false),
(num(1, Some(1)), false),
(None, false),
(num(1, None), false),
]
.iter()
.map(|&(l, empty)| ParaList::next_marker(l, empty, &mut counts))
.collect();
let want = ["1.", "5.", "6.", "1.", "1.", "2.", "7.", "", "8.", "\u{2022}", "1.", "", "1."];
assert_eq!(markers.iter().map(|m| m.as_deref().unwrap_or("")).collect::<Vec<_>>(), want);
let mut counts = ListCounts::default();
let roman = Some(ParaList::numbered(NumberStyle::UpperRoman).starting_at(Some(MAX_LIST_START)));
assert_eq!(ParaList::next_marker(roman, false, &mut counts).as_deref(), Some("999999999."));
let zero = Some(ParaList::numbered(NumberStyle::Arabic).starting_at(Some(0)));
assert_eq!(ParaList::next_marker(zero, false, &mut counts).as_deref(), Some("1."), "a number below 1 counts as 1");
assert_eq!(serde_json::to_value(num(1, None)).unwrap(), serde_json::json!({"bullet": "dot", "number": "arabic"}));
assert_eq!(serde_json::to_value(num(1, Some(5))).unwrap(), serde_json::json!({"bullet": "dot", "number": "arabic", "start": 5}));
let read = |v: serde_json::Value| serde_json::from_value::<ParaList>(v).unwrap().start;
assert_eq!(read(serde_json::json!({"number": "arabic", "start": 5})), Some(5));
assert_eq!(read(serde_json::json!({"number": "arabic"})), None);
assert_eq!(read(serde_json::json!({"number": "arabic", "start": null})), None);
let starts = [serde_json::json!(0), serde_json::json!(-3), serde_json::json!(5_000_000_000_u64), serde_json::json!(u64::MAX)];
assert_eq!(
starts.map(|s| read(serde_json::json!({ "number": "arabic", "start": s }))),
[Some(1), Some(1), Some(MAX_LIST_START), Some(MAX_LIST_START)],
"a saved number outside 1 to 999999999 reads as the nearest one"
);
for bad in [serde_json::json!(2.5), serde_json::json!("5"), serde_json::json!(true)] {
assert!(serde_json::from_value::<ParaList>(serde_json::json!({ "start": bad })).is_err(), "{bad}");
}
}
/// Return in a paragraph that its list gives a number makes paragraphs without it, also while
/// every paragraph shares one style; Return at the start of its text moves the number with the
/// text, and Return elsewhere leaves it where it was.
#[test]
fn return_does_not_copy_a_paragraphs_number() {
let five = ParaStyle { list: Some(ParaList::numbered(NumberStyle::Arabic).starting_at(Some(5))), ..ParaStyle::default() };
let starts = |t: &TextObject| t.paragraph_styles().iter().map(|p| p.list.and_then(|l| l.start)).collect::<Vec<_>>();
// One style for the whole text: Return after "one" splits it.
let mut t = TextObject::point(Point::ZERO, "onetwo", CharStyle::default());
t.set_all_paras(five);
t.splice_paras(3, 3, "\n");
t.runs[0].text.insert(3, '\n');
t.normalize_paras();
assert_eq!(starts(&t), [Some(5), None]);
assert!(t.para_at(1).list.is_some_and(|l| l.number == Some(NumberStyle::Arabic)), "the new paragraph stays in the list");
// Return at the start of "two" (a paragraph with a number of its own): the number moves on
// with the text, and the empty paragraph left before it has none.
t.edit_paras(Some(1..2), |p| p.list = p.list.map(|l| l.starting_at(Some(8))));
t.splice_paras(4, 4, "\n\n");
t.runs[0].text.insert_str(4, "\n\n");
t.normalize_paras();
assert_eq!(t.plain_text(), "one\n\n\ntwo");
assert_eq!(starts(&t), [Some(5), None, None, Some(8)]);
// A whole paragraph pasted at the start of "two": the number stays with "two".
t.splice_paras(6, 6, "Pasted\n");
t.runs[0].text.insert_str(6, "Pasted\n");
t.normalize_paras();
assert_eq!(t.plain_text(), "one\n\n\nPasted\ntwo");
assert_eq!(starts(&t), [Some(5), None, None, None, Some(8)]);
// "two" replaced by two paragraphs: none of its text is left, so the first new one keeps it.
t.splice_paras(13, 16, "A\nB");
t.runs[0].text.replace_range(13..16, "A\nB");
t.normalize_paras();
assert_eq!(t.plain_text(), "one\n\n\nPasted\nA\nB");
assert_eq!(starts(&t), [Some(5), None, None, None, Some(8), None]);
// Text without a number keeps one style for every paragraph.
let mut t = TextObject::point(Point::ZERO, "onetwo", CharStyle::default());
t.set_all_paras(ParaStyle { list: Some(ParaList::numbered(NumberStyle::Arabic)), ..ParaStyle::default() });
t.splice_paras(3, 3, "\n");
assert!(t.paras.is_empty());
}
/// In a threaded frame whose first paragraph continues from the frame before, the text at the
/// frame's start is not the start of a paragraph, so typing a list's start there starts nothing.
/// The paragraphs after it still start lists.
+31
View File
@@ -316,6 +316,37 @@ fn percent(s: &str) -> Option<f64> {
}
}
/// `text` typed in a numeric field, with a decimal comma read as a point: `0,1 mm` is `0.1 mm`
/// (#3837), and each number of a sum reads its own separator, so `100.5 mm-0,5` (a comma typed
/// after the value the field shows) is 100 mm (#5684). A number written with both separators has
/// two points once read, so `1,000.5` and `1.234,5` are refused rather than guessed at; so is a
/// number that reads as thousands ([`thousands`]).
pub fn decimal_point(text: &str) -> std::borrow::Cow<'_, str> {
if text.contains(',') && !thousands(text) { text.replace(',', ".").into() } else { text.into() }
}
/// Is `text` a number written with a thousands comma, as `1,000`, `+1,000`, `12,500 mm` or
/// `1,000"`: a sign, one to three digits (not a lone 0), a comma, exactly three digits, then at
/// most a unit? Read as a decimal it would be a thousand times too small, so the field refuses it
/// instead (`0,125` and `1,25` are decimals).
fn thousands(text: &str) -> bool {
let number = text.trim();
let number = number.strip_prefix(['+', '-']).unwrap_or(number);
let Some((whole, rest)) = number.split_once(',') else { return false };
let (part, unit) = rest.split_at(rest.find(|c: char| !c.is_ascii_digit()).unwrap_or(rest.len()));
(1..=3).contains(&whole.len())
&& whole.bytes().all(|b| b.is_ascii_digit())
&& !whole.starts_with('0')
&& part.len() == 3
&& unit.trim().chars().all(|c| c.is_alphabetic() || c == '"' || c == '\'')
}
/// Is the length `pt` (points) a finite number in every unit of [`Unit::EAST_ASIAN`]? A length
/// near the largest number in points is too large in Q and Ha.
pub fn finite_in_every_unit(pt: f64) -> bool {
pt.is_finite() && Unit::EAST_ASIAN.iter().all(|u| u.from_pt(pt).is_finite())
}
/// A unitless field value (percent, degrees, counts) with the same `+ - * /` arithmetic as
/// [`Unit::parse`] (`45*2`, `100/3`); text other than digits, `.` and operators reads as nothing.
pub fn parse_number(s: &str) -> Option<f64> {
+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
@@ -94,13 +94,13 @@ pub use revolve::{
CLASSIC_REVOLVE, REVOLVE, has_revolve, is_revolve, revolve_art, revolve_art_in, revolve_options, validate_revolve, validate_revolve_in,
};
pub use solids::{
CLASSIC_EXTRUDE, CLASSIC_ROTATE, EXTRUDE, GRAPHICS, GraphicFrame, INFLATE, MAX_GRAPHICS, MappedGraphic, RENDER, RENDER_MODES, ROTATE,
ROTATE_SURFACES, ROTATION_PRESETS, SHADING_COLORS, SOLIDS, SolidMesh, THREE_D_TYPES, classic_extrude_options, classic_shading, extrude_options,
graphic_bounds, graphic_frame, graphic_symbols, has_solid, inflate_options, is_classic_three_d, is_three_d, mapped_graphics, missing_symbol,
names_graphic_symbol, rename_graphic_symbol, rename_graphic_symbol_in, renders_wireframe, solid_art, solid_art_in, takes_graphics,
three_d_meshes, three_d_meshes_in, three_d_meshes_of, three_d_meshes_of_in, three_d_params_as, three_d_wireframe_in, validate_solid,
validate_solid_in, validate_three_d, validate_three_d_at, validate_three_d_at_in, validate_three_d_in, validate_three_d_params, view_options,
with_graphic,
CLASSIC_EXTRUDE, CLASSIC_ROTATE, EXTRUDE, GRAPHICS, GraphicFrame, INFLATE, MAX_GRAPHICS, MappedGraphic, MeshGraphics, RENDER, RENDER_MODES,
ROTATE, ROTATE_SURFACES, ROTATION_PRESETS, SHADING_COLORS, SOLIDS, SolidMesh, THREE_D_TYPES, classic_extrude_options, classic_shading,
extrude_options, graphic_bounds, graphic_frame, graphic_symbols, has_solid, inflate_options, is_classic_three_d, is_three_d, mapped_graphics,
mesh_graphics_art, missing_symbol, names_graphic_symbol, rename_graphic_symbol, rename_graphic_symbol_in, renders_wireframe, solid_art,
solid_art_in, takes_graphics, three_d_meshes, three_d_meshes_in, three_d_meshes_of, three_d_meshes_of_in, three_d_params_as,
three_d_wireframe_in, validate_solid, validate_solid_in, validate_three_d, validate_three_d_at, validate_three_d_at_in, validate_three_d_in,
validate_three_d_params, view_options, with_graphic,
};
pub use solids::{
GRAPHIC_MAX_OFFSET, GRAPHIC_SCALE_RANGE, GRAPHICS_NOT_TAKEN, appearance_graphic_symbols, exports_three_d, graphic_frame_at,
+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)));
}
}
+7
View File
@@ -886,6 +886,9 @@ pub(crate) use buildcmds::TracePresetChanges;
/// The shapes a group selected alone gives the Pathfinder panel.
pub use pathops::shape_count;
/// The Shape Mode commands' warning when a selected open path encloses no area.
pub use pathops::SHAPE_MODE_OPEN_PATH_NO_AREA;
/// The gaps View › Show Live Paint Gaps shows on a Live Paint group.
pub use buildcmds::live_paint_gaps;
@@ -901,6 +904,10 @@ pub use brushsym::current_symbol;
/// Data window reads files by it too).
pub use variablecmds::utf16_order_without_mark;
/// How the Graph Data window's Import Data and Import Data Sets' `%` columns read a graph data
/// file: its size limit, its text, its cells and the data `graph.setData` takes from them.
pub use graph::{MAX_GRAPH_DATA_FILE, graph_cell_text, graph_data_from_grid, graph_data_text, graph_grid_from_text};
/// The Variables panel's sort (`variable.sort`) and its rows in that order.
pub use variablecmds::{VariableSort, VariableSortKey, variable_order};
+2
View File
@@ -14,6 +14,7 @@ mod pen;
mod select;
mod shapes;
mod typetools;
mod units;
pub(crate) use image::{DecodedImages, refresh_color_masks};
pub(crate) use packaging::{role_swatch_edited, role_swatches_merged};
@@ -35,5 +36,6 @@ pub fn specs() -> Vec<CommandSpec> {
v.extend(select::specs());
v.extend(shapes::specs());
v.extend(typetools::specs());
v.extend(units::specs());
v
}
+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");
}
}
}
+124
View File
@@ -0,0 +1,124 @@
//! Unit Converter (`addon.units.*`), a built-in add-on that shows one length in every unit at once.
//! `addon.units.convert` reads a length as a number field reads it ([`Unit::parse`]: units and
//! arithmetic) and gives it in each unit of Preferences › Units › East Asian Type
//! ([`Unit::EAST_ASIAN`]), written as the fields write it ([`Unit::number`], [`Unit::format`]).
//! `addon.units.selectionSize` gives the selection's width and height, measured as the Transform
//! panel measures them, in the same units. Its panel and its place in Object › Plug-ins are the
//! UI's; the panel applies a length to the selection with `object.setBounds`.
#[cfg(test)]
mod tests;
use serde_json::{Value, json};
use vectorcraft_doc::{OrientedBox, Unit, decimal_point, finite_in_every_unit};
use vectorcraft_render::effects;
use super::super::{CommandSpec, always, bad, cmd, has_selection};
use crate::{Result, Session};
const CONVERT: &str = "addon.units.convert";
const SELECTION_SIZE: &str = "addon.units.selectionSize";
/// The most characters of a refused value an error message shows.
const SHOWN_CHARS: usize = 64;
/// The longest `value` or `unit` text `addon.units.convert` reads, in bytes.
const MAX_TEXT_LEN: usize = 1024;
/// The most `+ - * /` signs `addon.units.convert` reads in one `value`: [`Unit::parse`] takes one
/// level of recursion per sign.
const MAX_OPERATORS: usize = 128;
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!(
query "addon.units.convert",
"Convert Units",
[],
None,
"{value: a length (a number, or text as a number field reads it, with a unit suffix and + - * / arithmetic: \"10mm\", \"1in/2\", \"2p6\", \"3cm*50%\"; a decimal comma reads as a point: \"0,5 mm\"; at most 1024 bytes and 128 operators), unit?: the unit of a number without a suffix (a unit's name, suffix or key: points, picas, inches, millimeters, centimeters, pixels, feetInches, meters, yards, feet, q, ha; default: points)} the length in every unit of Preferences › Units › East Asian Type, written as the number fields write it (rounded to 3 decimals in pt, px, picas, Q and Ha and to 4 in the others; pixels are points). Nothing in the document changes → {points, units: [{unit (its key), label, number (no suffix), text (with the suffix)}]}",
always,
convert
),
cmd!(
query "addon.units.selectionSize",
"Selection Size in Units",
[],
None,
"{} the selection's width and height as the Transform panel shows them (its bounding box, rotated with rotated objects; with Use Preview Bounds, the visual bounds; with anchor points selected (Direct Selection), the box around those points), each as addon.units.convert gives it → {width: {points, units}, height: {points, units}}",
has_selection,
selection_size
),
]
}
/// The length `pt` (points) in every unit of [`Unit::EAST_ASIAN`]: `{points, units: [{unit,
/// label, number, text}]}`.
pub fn in_every_unit(pt: f64) -> Value {
let units: Vec<Value> =
Unit::EAST_ASIAN.iter().map(|u| json!({"unit": u.key(), "label": u.label(), "number": u.number(pt), "text": u.format(pt)})).collect();
json!({ "points": pt, "units": units })
}
/// The unit `p` gives for a number without a suffix (points when left out; null is an error).
fn unit_param(p: &Value) -> Result<Unit> {
let Some(given) = p.get("unit") else { return Ok(Unit::Points) };
let named = given.as_str().filter(|name| name.len() <= MAX_TEXT_LEN).and_then(Unit::named_east_asian);
named.ok_or_else(|| {
let u = match given {
Value::String(s) => clipped(s).escape_debug().to_string(),
other => shown(other),
};
bad(CONVERT, format!("unknown units `{u}`"))
})
}
fn convert(_: &mut Session, p: &Value) -> Result<Value> {
let unit = unit_param(p)?;
let Some(v) = p.get("value").filter(|v| !v.is_null()) else {
return Err(bad(CONVERT, "missing `value`"));
};
let pt = match v {
Value::String(s) if readable(s) => unit.parse(&decimal_point(s)),
Value::Number(n) => n.as_f64().map(|n| unit.to_pt(n)),
_ => None,
};
let pt = pt.filter(|&pt| finite_in_every_unit(pt));
pt.map(in_every_unit).ok_or_else(|| {
let v = shown(v);
bad(CONVERT, format!("`value` must be a number, not {v}"))
})
}
/// Is `s` short enough to read: at most [`MAX_TEXT_LEN`] bytes and [`MAX_OPERATORS`] `+ - * /`
/// signs?
fn readable(s: &str) -> bool {
s.len() <= MAX_TEXT_LEN && s.chars().filter(|c| matches!(c, '+' | '-' | '*' | '/')).count() <= MAX_OPERATORS
}
/// `v` as an error message shows it: text cut at [`SHOWN_CHARS`] characters with "…", as JSON,
/// an array as `[…]` and an object as `{…}`.
fn shown(v: &Value) -> String {
match v {
Value::String(s) => Value::String(clipped(s)).to_string(),
Value::Array(_) => "[…]".into(),
Value::Object(_) => "{…}".into(),
other => other.to_string(),
}
}
/// `s` cut at [`SHOWN_CHARS`] characters, with "…" when it is longer.
fn clipped(s: &str) -> String {
match s.char_indices().nth(SHOWN_CHARS) {
Some((at, _)) => format!("{}…", s.get(..at).unwrap_or_default()),
None => s.to_string(),
}
}
fn selection_size(s: &mut Session, _: &Value) -> Result<Value> {
let st = s.doc()?;
let measure = s.bounds_measure();
let b = match effects::preview::anchor_bounds_with(&st.selection, &st.doc, measure) {
Some(r) => Some(OrientedBox::aligned(r)),
None => s.transform_box(&st.selection.objects),
};
let b = b.ok_or_else(|| bad(SELECTION_SIZE, "nothing selected"))?;
Ok(json!({ "width": in_every_unit(b.rect.width()), "height": in_every_unit(b.rect.height()) }))
}
+209
View File
@@ -0,0 +1,209 @@
//! Unit Converter's commands: a length in every unit, read as number fields read it, the selection's
//! size as the Transform panel measures it, bad params refused, and nothing in the document changed.
use serde_json::{Value, json};
use vectorcraft_doc::Unit;
use crate::{EngineError, Session};
fn session() -> Session {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
s
}
fn convert(s: &mut Session, p: Value) -> Value {
s.execute("addon.units.convert", &p).unwrap()
}
/// The row of `r` for the unit with key `key`.
fn row<'a>(r: &'a Value, key: &str) -> &'a Value {
r["units"].as_array().unwrap().iter().find(|u| u["unit"] == key).unwrap_or_else(|| panic!("{key} in {r}"))
}
fn near(a: f64, b: f64) -> bool {
(a - b).abs() < 1e-9
}
#[test]
fn a_length_comes_back_in_every_unit_in_order() {
let mut s = session();
let r = convert(&mut s, json!({"value": "10mm"}));
assert!(near(r["points"].as_f64().unwrap(), 720.0 / 25.4));
let keys: Vec<&str> = r["units"].as_array().unwrap().iter().map(|u| u["unit"].as_str().unwrap()).collect();
assert_eq!(keys, Unit::EAST_ASIAN.map(Unit::key));
assert_eq!(row(&r, "millimeters")["number"], "10");
assert_eq!(row(&r, "millimeters")["text"], "10 mm");
assert_eq!(row(&r, "centimeters")["text"], "1 cm");
assert_eq!(row(&r, "inches")["text"], "0.3937 in");
assert_eq!(row(&r, "points")["text"], "28.346 pt");
assert_eq!(row(&r, "q")["text"], "40 Q");
assert_eq!(row(&r, "ha")["text"], "40 H");
assert_eq!(row(&r, "pixels")["number"], row(&r, "points")["number"], "pixels are points");
assert_eq!(row(&r, "feetInches")["label"], "Feet & Inches");
// Each row is what a field of that unit shows for the length.
for u in Unit::EAST_ASIAN {
let pt = 720.0 / 25.4;
assert_eq!(row(&r, u.key())["text"], u.format(pt), "{u:?}");
assert_eq!(row(&r, u.key())["number"], u.number(pt), "{u:?}");
}
}
#[test]
fn values_read_as_number_fields_read_them() {
let mut s = session();
let pt = |s: &mut Session, p: Value| convert(s, p)["points"].as_f64().unwrap();
assert!(near(pt(&mut s, json!({"value": "1in/2"})), 36.0));
assert!(near(pt(&mut s, json!({"value": "2p6"})), 30.0));
assert!(near(pt(&mut s, json!({"value": "1080/2 px"})), 540.0));
assert!(near(pt(&mut s, json!({"value": "3cm*50%"})), 1.5 * 72.0 / 2.54));
assert!(near(pt(&mut s, json!({"value": "13q"})), 13.0 * 72.0 / 101.6));
// A number without a unit is in `unit`, points by default.
assert!(near(pt(&mut s, json!({"value": 12})), 12.0));
assert!(near(pt(&mut s, json!({"value": 2, "unit": "in"})), 144.0));
assert!(near(pt(&mut s, json!({"value": "2", "unit": "Inches"})), 144.0));
assert!(near(pt(&mut s, json!({"value": "3+1", "unit": "cm"})), 4.0 * 72.0 / 2.54));
assert!(near(pt(&mut s, json!({"value": 6, "unit": "ha"})), 6.0 * 72.0 / 101.6));
assert!(near(pt(&mut s, json!({"value": 1, "unit": "feetInches"})), 864.0));
// A suffix wins over `unit`.
assert!(near(pt(&mut s, json!({"value": "1in", "unit": "mm"})), 72.0));
// A decimal comma reads as a point, as in the number fields.
assert!(near(pt(&mut s, json!({"value": "0,5 in"})), 36.0));
assert!(near(pt(&mut s, json!({"value": "1,5", "unit": "in"})), 108.0));
// Each number of a sum reads its own separator.
assert!(near(pt(&mut s, json!({"value": "100.5 mm-0,5", "unit": "mm"})), 100.0 * 72.0 / 25.4));
// A comma in a sum is a decimal comma, as in the number fields: 1,500+2 is 3.5.
assert!(near(pt(&mut s, json!({"value": "1,500+2", "unit": "mm"})), 3.5 * 72.0 / 25.4));
// A sum of 128 signs still reads.
assert!(near(pt(&mut s, json!({"value": format!("1{}", "+1".repeat(128))})), 129.0));
}
#[test]
fn keys_the_commands_do_not_take_are_refused() {
let s = session();
s.check_params("addon.units.convert", &json!({"value": 1, "unit": "mm"})).unwrap();
s.check_params("addon.units.selectionSize", &json!({})).unwrap();
for (id, p) in [
("addon.units.convert", json!({"value": 1, "units": "mm"})),
("addon.units.convert", json!({"value": 1, "ids": [1]})),
("addon.units.selectionSize", json!({"ids": [1]})),
("addon.units.selectionSize", json!({"value": 1})),
] {
match s.check_params(id, &p) {
Err(EngineError::BadParams { cmd, .. }) => assert_eq!(cmd, id, "{p}"),
other => panic!("{id} {p}: expected BadParams, got {other:?}"),
}
}
}
#[test]
fn the_selection_size_follows_preview_bounds_and_selected_anchors() {
let mut s = session();
let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 72, "height": 36})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [id]})).unwrap();
s.execute("paint.setStroke", &json!({"ids": [id], "color": "#000000"})).unwrap();
s.execute("stroke.set", &json!({"ids": [id], "weight": 10})).unwrap();
let wh = |s: &mut Session| {
let r = s.execute("addon.units.selectionSize", &json!({})).unwrap();
(r["width"]["points"].as_f64().unwrap(), r["height"]["points"].as_f64().unwrap())
};
assert_eq!(wh(&mut s), (72.0, 36.0), "geometric bounds");
// Use Preview Bounds: the stroke's outer half on every side.
s.execute("prefs.set", &json!({"key": "usePreviewBounds", "value": true})).unwrap();
let (w, h) = wh(&mut s);
assert!(near(w, 82.0) && near(h, 46.0), "{w} × {h}");
s.execute("prefs.set", &json!({"key": "usePreviewBounds", "value": false})).unwrap();
// Two neighboring anchors selected (Direct Selection): the box around them, one edge of the
// rectangle.
s.execute("select.anchors", &json!({"id": id, "anchors": [[0, 0], [0, 1]], "mode": "set"})).unwrap();
let (w, h) = wh(&mut s);
assert!((near(w, 72.0) && near(h, 0.0)) || (near(w, 0.0) && near(h, 36.0)), "{w} × {h}");
}
#[test]
fn it_needs_no_document_and_changes_nothing() {
let mut s = Session::new();
assert!(near(convert(&mut s, json!({"value": "1in"}))["points"].as_f64().unwrap(), 72.0));
let mut s = session();
let (before, steps) = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len());
convert(&mut s, json!({"value": "5mm"}));
assert_eq!(s.doc().unwrap().history.undo.len(), steps);
assert!(*s.doc().unwrap().doc == *before);
}
#[test]
fn bad_values_and_units_are_refused() {
let mut s = session();
for p in [
json!({}),
json!({"value": null}),
json!({"value": "abc"}),
json!({"value": "10 furlongs"}),
json!({"value": "1in/0"}),
json!({"value": "1e400"}),
// Finite in points, too large in Q and Ha.
json!({"value": 1.5e308}),
json!({"value": "1.5e308"}),
// A thousands comma is refused, as the number fields refuse it.
json!({"value": "1,000 mm"}),
json!({"value": "1,000.5"}),
json!({"value": "+1,000"}),
json!({"value": "1,000\""}),
json!({"value": "1,000'"}),
// A long expression is refused instead of exhausting the stack.
json!({"value": format!("1{}", "+1".repeat(200_000))}),
json!({"value": format!("1{}", "+1".repeat(129))}),
json!({"value": true}),
json!({"value": [1]}),
json!({"value": 1, "unit": "furlongs"}),
json!({"value": 1, "unit": 5}),
json!({"value": 1, "unit": ["mm"]}),
// Only an omitted `unit` is points.
json!({"value": 1, "unit": null}),
] {
match s.execute("addon.units.convert", &p) {
Err(EngineError::BadParams { cmd, .. }) => assert_eq!(cmd, "addon.units.convert", "{p}"),
other => panic!("{p}: expected BadParams, got {other:?}"),
}
}
}
#[test]
fn a_long_value_or_unit_is_refused_with_a_short_message() {
let mut s = session();
let long = "9".repeat(100_000);
for (p, says) in [
(json!({"value": long.clone()}), format!("`value` must be a number, not \"{}…\"", "9".repeat(64))),
(json!({"value": [long.clone()]}), "`value` must be a number, not […]".to_string()),
(json!({"value": 1, "unit": long.clone()}), format!("unknown units `{}…`", "9".repeat(64))),
(json!({"value": 1, "unit": "furlongs"}), "unknown units `furlongs`".to_string()),
(json!({"value": "a\"b\nc"}), "`value` must be a number, not \"a\\\"b\\nc\"".to_string()),
] {
match s.execute("addon.units.convert", &p) {
Err(e @ EngineError::BadParams { .. }) => assert!(e.to_string().ends_with(&says), "{e}"),
other => panic!("expected BadParams, got {other:?}"),
}
}
}
#[test]
fn the_selection_size_is_the_transform_panels() {
let mut s = session();
assert!(s.execute("addon.units.selectionSize", &json!({})).is_err(), "nothing selected");
let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 72, "height": 36})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [id]})).unwrap();
let steps = s.doc().unwrap().history.undo.len();
let r = s.execute("addon.units.selectionSize", &json!({})).unwrap();
assert!(near(r["width"]["points"].as_f64().unwrap(), 72.0));
assert!(near(r["height"]["points"].as_f64().unwrap(), 36.0));
assert_eq!(row(&r["width"], "inches")["text"], "1 in");
assert_eq!(row(&r["height"], "picas")["text"], "3 p");
// A turned object keeps its own sides, as the Transform panel's W and H show them.
s.execute("object.rotate", &json!({"angle": 30})).unwrap();
let r = s.execute("addon.units.selectionSize", &json!({})).unwrap();
let b = s.transform_box(&s.doc().unwrap().selection.objects).unwrap();
assert!(near(r["width"]["points"].as_f64().unwrap(), b.rect.width()));
assert!(near(r["width"]["points"].as_f64().unwrap(), 72.0));
assert!(near(r["height"]["points"].as_f64().unwrap(), 36.0));
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "only the rotation is a step");
}
+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)")))?;
+11 -2
View File
@@ -36,8 +36,8 @@ mod symbols;
pub(crate) use brushes::{apply_brush, brush_targets, stroke_paint};
use brushes::{
brush_apply, brush_delete, brush_duplicate, brush_freehand, brush_get, brush_list, brush_move, brush_new, brush_options, brush_place_art,
brush_remove, brush_replace_art, brush_selection_art, brush_set_current, brush_unused, expand_brush,
brush_apply, brush_delete, brush_duplicate, brush_freehand, brush_get, brush_list, brush_move, brush_new, brush_object_options, brush_options,
brush_place_art, brush_remove, brush_replace_art, brush_selection_art, brush_set_current, brush_unused, expand_brush,
};
pub(crate) use dynamic::{edit_part, fit_parts, part_only, selected_part};
use dynamic::{symbol_instance_reset, symbol_instance_select_part, symbol_instance_set_appearance};
@@ -169,6 +169,15 @@ pub fn specs() -> Vec<CommandSpec> {
has_doc,
brush_options
),
cmd!(
"brush.objectOptions",
"Options of Selected Object…",
[],
None,
"{ids?|id?, params?: {…the fields brush.options takes that a path can set for itself: calligraphic angle (counter-clockwise from level), roundness, size, variation, modes; scatter size, spacing, scatter, rotation (counter-clockwise), modes, rotation_relative_to_path, colorization; art width, width_mode, width_max, flip_along, flip_across, overlap, colorization; pattern scale, spacing, fit, flip_along, flip_across, colorization (values outside their ranges are clamped; a colorization object changes only the fields it gives; a null item of an array such as size: [40, null] keeps each stroke's own item, else the brush's)}, reset?: bool} set the brush settings of the brushed strokes of the selected paths on those strokes only, leaving the brush and its other strokes as they are (the Brushes panel's Options of Selected Object); params add to each stroke's own settings, a mode params does not set (no modes, or a null item) stays the one each stroke draws with when a changed variation or range would change it, a setting equal to the brush's own value is dropped, and reset: true clears them so the strokes draw the brush again; without params or reset nothing changes; one undo step, none when nothing changes. The brushes' own edits (brush.options) still reach the settings a stroke does not set, applying a brush (brush.apply, stroke.setAdvanced or a brush.freehand extend with another brush) or removing it clears them, and a renamed brush keeps them. Refused with nothing painted with a brush selected, for paths painted with brushes of different types, for a bristle brush, for a field the type does not take and for a value of the wrong kind → {ids: the brushed paths, changed: the paths whose settings changed, options: the first stroke's own settings}",
has_doc,
brush_object_options
),
cmd!(
"object.expandBrush",
"Expand Brush Strokes",
+169 -1
View File
@@ -1,6 +1,7 @@
use super::{
AppearanceItem, Arc, BTreeSet, Bristle, Brush, BrushKind, Color, Document, EngineError, Node, NodeId, NodeKind, Paint, Result, Session, Value,
anchor, bad, brush, check_numbers, find_command, ids_json, json, name_param, names_param, ok, roots, selection_art, set_unknown, str_param,
switch_or,
};
// ---------- brushes ----------
@@ -57,6 +58,8 @@ pub(crate) fn apply_brush(d: &mut Document, ids: &[NodeId], name: &str, stroke:
st.width = 1.0;
}
st.brush = Some(name.to_string());
// The path's own brush settings (Options of Selected Object) go with the brush they set.
st.brush_options.clear();
}
}
}
@@ -85,6 +88,7 @@ pub(super) fn brush_remove(s: &mut Session, p: &Value) -> Result<Value> {
for it in &mut n.appearance.items {
if let AppearanceItem::Stroke(st) = it {
st.brush = None;
st.brush_options.clear();
}
}
}
@@ -129,13 +133,17 @@ fn merge(base: &mut Value, patch: &Value) {
}
}
/// Sets brush `to` on the strokes in `items` that paint with brush `from`.
/// Sets brush `to` on the strokes in `items` that paint with brush `from`. A renamed brush keeps
/// each stroke's own settings for it; a stroke left without a brush loses them.
fn set_stroke_brush(items: &mut [AppearanceItem], from: &str, to: Option<&str>) {
for it in items {
if let AppearanceItem::Stroke(st) = it
&& st.brush.as_deref() == Some(from)
{
st.brush = to.map(str::to_string);
if to.is_none() {
st.brush_options.clear();
}
}
}
}
@@ -494,6 +502,166 @@ pub(super) fn brush_options(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({ "name": out }))
}
/// Options of Selected Object: set the brush settings of the brushed strokes of the selected paths
/// (or `ids`) on those strokes only, leaving the brush as it is. `params` adds to each stroke's
/// own settings, `reset` clears them; without either, nothing changes and the settings are given.
pub(super) fn brush_object_options(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "brush.objectOptions";
let params = match p.get("params") {
None | Some(Value::Null) => serde_json::Map::new(),
Some(Value::Object(o)) => o.clone(),
Some(_) => {
let key = "params";
return Err(bad(C, format!("`{key}` must be an object")));
}
};
let reset = switch_or(p, "reset", false, C)?;
if reset && !params.is_empty() {
return Err(bad(C, "give `params` or `reset`, not both"));
}
let d = &s.doc()?.doc;
let lib = brush::library(d);
let ids = brush_targets(d, &roots(s, p)?);
// Each brushed stroke: its path, its place in the appearance, its brush and its settings now.
let mut strokes = vec![];
for id in &ids {
let Some(n) = d.node(*id) else { continue };
for (i, it) in n.appearance.items.iter().enumerate() {
let AppearanceItem::Stroke(st) = it else { continue };
if let Some(b) = st.brush.as_deref().and_then(|name| lib.iter().find(|b| b.name == name)) {
strokes.push((*id, i, b, &st.brush_options));
}
}
}
let Some(&(_, _, first, _)) = strokes.first() else { return Err(bad(C, "no path painted with a brush is selected")) };
if strokes.iter().any(|(_, _, b, _)| b.kind.type_id() != first.kind.type_id()) {
return Err(bad(C, "the selected paths are painted with brushes of different types"));
}
// Only a bristle brush has none.
if first.kind.stroke_option_keys().is_empty() {
return Err(bad(C, "a bristle brush has no options of its own on a path"));
}
let out: Vec<NodeId> = ids.iter().copied().filter(|id| strokes.iter().any(|(s, ..)| s == id)).collect();
// Without params or reset the settings are only given: nothing is normalized or changed.
if !reset && params.is_empty() {
let keys = first.kind.stroke_option_keys();
let own: serde_json::Map<String, Value> =
strokes[0].3.iter().filter(|(k, _)| keys.contains(&k.as_str())).map(|(k, v)| (k.clone(), v.clone())).collect();
return Ok(json!({ "ids": ids_json(&out), "changed": [], "options": own }));
}
let mut changes = vec![];
let mut options = None;
for (id, i, b, own) in &strokes {
let next = if reset {
serde_json::Map::new()
} else {
// Settings saved for another type of brush are left out.
let keys = b.kind.stroke_option_keys();
let mut merged: serde_json::Map<String, Value> =
own.iter().filter(|(k, _)| keys.contains(&k.as_str())).map(|(k, v)| (k.clone(), v.clone())).collect();
let was = merged.clone();
// A colorization object changes only the fields it gives, and a null item of an
// array keeps the stroke's own item (else the brush's).
for (k, v) in &params {
let next = match (merged.get(k), v) {
(Some(Value::Object(mine)), Value::Object(fields)) if k == "colorization" => {
let mut c = mine.clone();
c.extend(fields.clone());
Value::Object(c)
}
(Some(mine), _) => brush::keep_items(v, mine),
(None, _) => v.clone(),
};
merged.insert(k.clone(), next);
}
keep_drawn_modes(b, &was, &params, &mut merged);
keep_largest_width(b, &was, &params, &mut merged);
b.stroke_options_that_differ(&merged).map_err(|e| bad(C, e))?
};
options.get_or_insert_with(|| next.clone());
if &next != *own {
changes.push((*id, *i, next));
}
}
let changed: Vec<NodeId> = ids.iter().copied().filter(|id| changes.iter().any(|(c, ..)| c == id)).collect();
if !changes.is_empty() {
s.edit("Options of Selected Object", |d, _| {
for (id, i, next) in changes {
if let Some(AppearanceItem::Stroke(st)) = d.node_mut(id).and_then(|n| n.appearance.items.get_mut(i)) {
st.brush_options = next;
}
}
Ok(())
})?;
}
Ok(json!({ "ids": ids_json(&out), "changed": ids_json(&changed), "options": options.unwrap_or_default() }))
}
/// The modes brush `b` draws with, for a Calligraphic or a Scatter brush.
fn drawn_modes(b: &Brush) -> Option<Vec<Value>> {
let modes = match &b.kind {
BrushKind::Calligraphic(c) => serde_json::to_value(c.modes()),
BrushKind::Scatter(s) => serde_json::to_value(s.modes()),
_ => return None,
};
match modes {
Ok(Value::Array(m)) => Some(m),
_ => None,
}
}
/// Keep each mode a stroke of brush `b` draws with (with its own settings `was`) that `params`
/// does not set (no `modes`, or a `null` item) and that `merged`, its settings with `params`,
/// would change. A mode the stroke leaves to its values follows them, so without this a changed
/// variation or range would also change the mode.
fn keep_drawn_modes(
b: &Brush,
was: &serde_json::Map<String, Value>,
params: &serde_json::Map<String, Value>,
merged: &mut serde_json::Map<String, Value>,
) {
let given = match params.get("modes") {
None | Some(Value::Null) => vec![],
Some(Value::Array(m)) => m.clone(),
// A value of the wrong kind is refused when the settings are checked.
Some(_) => return,
};
let (Some(before), Some(after)) =
(b.with_stroke_options(was).ok().as_ref().and_then(drawn_modes), b.with_stroke_options(merged).ok().as_ref().and_then(drawn_modes))
else {
return;
};
if before == after {
return;
}
let kept = before.into_iter().zip(after).enumerate().map(|(j, (w, a))| if given.get(j).is_some_and(|g| !g.is_null()) { a } else { w }).collect();
merged.insert("modes".into(), Value::Array(kept));
}
/// Keep the largest width a stroke of art brush `b` draws with (with its own settings `was`) when
/// `params` sets `width` and no `width_max`. Without a `width_max` of its own the largest width is
/// the width, so without this a changed width would also change the largest width.
fn keep_largest_width(
b: &Brush,
was: &serde_json::Map<String, Value>,
params: &serde_json::Map<String, Value>,
merged: &mut serde_json::Map<String, Value>,
) {
if params.get("width").is_none_or(Value::is_null) || params.get("width_max").is_some_and(|m| !m.is_null()) {
return;
}
let art = |o: &serde_json::Map<String, Value>| match b.with_stroke_options(o).ok().map(|b| b.kind) {
Some(BrushKind::Art(a)) => Some(a),
_ => None,
};
let (Some(before), Some(after)) = (art(was), art(merged)) else { return };
let follows_pen = |a: &brush::ArtBrush| a.width_mode.is_some_and(|m| m.follows_pen());
// Only a width that followed the pen has a largest width, and only one that still does uses it.
if before.width_max.is_none() && follows_pen(&before) && follows_pen(&after) && after.width != before.width {
merged.insert("width_max".into(), json!(before.width));
}
}
/// The name `brush.placeArt` gives each pattern brush tile it places, by tile, in the order it
/// places them; `brush.replaceArt` reads a group of that name as that tile.
const TILE_NAMES: [&str; 5] = ["Side Tile", "Outer Corner Tile", "Inner Corner Tile", "Start Tile", "End Tile"];
+3 -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)
),
@@ -658,6 +659,7 @@ fn fit_to_edge(row: &mut AppearanceItem, run: Option<(f64, bool, bool, bool)>) {
}
s.profile = None;
s.brush = None;
s.brush_options.clear();
}
if !starts {
s.start_arrow = None;
+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
),
@@ -579,6 +579,11 @@ impl SwatchChoices {
Some(v) => Ok(Self { all: one(v)?, by_name: BTreeMap::new() }),
}
}
/// Add for every conflict: each pasted swatch whose name the document gives another color
/// comes in renamed.
pub(crate) fn add_all() -> Self {
Self { all: SwatchChoice::Add, by_name: BTreeMap::new() }
}
fn of(&self, name: &str) -> SwatchChoice {
self.by_name.get(name).copied().unwrap_or(self.all)
}
+20 -1
View File
@@ -754,10 +754,12 @@ fn map_art_colors(n: &mut vectorcraft_doc::Node, f: &mut dyn FnMut(&Color, proof
}
/// `f` applied to the colors in `n`'s subtree that [`proof::map_node_colors`] does not visit: the
/// effect colors ([`map_effect_colors`]), the series paints and label styles a graph keeps
/// effect colors ([`map_effect_colors`]), the Hue Shift key colors of strokes' own brush settings
/// ([`map_stroke_brush_keys`]), the series paints and label styles a graph keeps
/// ([`map_graph_colors`]) and the art of every opacity mask.
fn map_more_colors(n: &mut vectorcraft_doc::Node, f: &mut dyn FnMut(&Color, proof::Link) -> Color) {
map_effect_colors(&mut n.appearance, f);
map_stroke_brush_keys(&mut n.appearance, f);
if let Some(e) = n.extras_if_any() {
if let Some(g) = e.graph.as_deref_mut() {
map_graph_colors(g, f);
@@ -773,6 +775,23 @@ fn map_more_colors(n: &mut vectorcraft_doc::Node, f: &mut dyn FnMut(&Color, proo
}
}
/// `f` applied to the Hue Shift key color of each stroke's own brush settings in appearance `a`
/// (Options of Selected Object, `colorization.key` of [`StrokeLayer::brush_options`]); a key
/// that does not read is left as it is.
///
/// [`StrokeLayer::brush_options`]: vectorcraft_doc::StrokeLayer::brush_options
fn map_stroke_brush_keys(a: &mut vectorcraft_doc::Appearance, f: &mut dyn FnMut(&Color, proof::Link) -> Color) {
for it in &mut a.items {
let vectorcraft_doc::AppearanceItem::Stroke(st) = it else { continue };
let Some(c) = st.brush_options.get_mut("colorization").and_then(Value::as_object_mut) else { continue };
let Some(key) = c.get("key").and_then(|k| serde_json::from_value::<Color>(k.clone()).ok()) else { continue };
let n = f(&key, None);
if n != key {
c.insert("key".into(), json!(n));
}
}
}
/// Whether art color `c` is the Hue Shift key color `key`, with the tolerance the brush's
/// colorization matches it with.
fn matches_key(c: &Color, key: &Color) -> bool {
+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> {
+179 -5
View File
@@ -18,7 +18,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Document Info",
["Window", "Document Info"],
None,
"{selectionOnly?, category?: document|objects|graphicStyles|brushes|spotColors|patterns|gradients|symbols|fonts|fontDetails|linkedImages|embeddedImages|repeats (only that one in sections and the text), format?: \"text\" (→ {text}: the report Document Info › Save… and Package write)} → {document: {…, units (English), unitId: the units' Preferences › Units id (points, millimeters, feetInches, …), rasterEffectsPpi}, objects: {paths, compoundPaths, groups, …}, pathLength: pt (the paths' total length, compound paths' included, guides left out), fonts (the type in opacity masks and in the art of symbols and patterns included; with selectionOnly: the selected type's), fontDetails: [{font, match: exact|style|missingWithFallback|missing, family, style, file, embedding: allowed|editing|previewPrint|forbidden|null}] (each font of fonts, in order: how it was found, the face shown (null when none), that face's file name (null for a built-in face) and what its license allows), images, imageObjects: [{name, width, height, linked, file}] (the image objects in the order Linked Images and Embedded Images list them; file: what a linked image's row shows, null for an embedded one), swatches, graphicStyleNames (with selectionOnly: the styles the selected objects are linked to), brushNames (the brushes the art's drawn strokes use, each once; with selectionOnly: those the selected objects' strokes use), brushes: [{name, type: calligraphic|scatter|art|pattern|bristle|null}] (those brushes with their types; null: not in the Brushes panel), panelBrushNames (the Brushes panel's brushes), repeatObjects: [{id, name, type: radial|grid|mirror, instances, rows?, cols?}] (the Repeat objects, those in groups and other repeats included; with selectionOnly: those in the selection), spotObjects: [{id, name, spotColors}] (the objects filled or stroked with a spot color swatch, as a solid color or in the stops of a gradient that color a part of it above opacity 0 (a stop at opacity 0 counts only where it mixes with a stop above opacity 0 over a stretch of some width), at a tint above 0, and grayscale images colorized with one, each once, by the rules patternObjects follows, with the spot colors they use; Registration and process colors are not spot colors; objects.spots counts them), spotColorNames and spotColors (the spot colors those objects use), patternObjects: [{id, name, patterns}] (the objects filled or stroked with a pattern, each once, those in groups and type whose drawn characters use one included, hidden fills and strokes, fills and strokes at an opacity of 0, strokes with no width, guides, compound path members' own fills and strokes, images' fills and strokes without a shape and characters that draw nothing left out, with the patterns they use, which objects.patterns counts; with selectionOnly: those in the selection), patternNames (the patterns those objects use), gradientObjects: [{id, name, gradients, kinds}] (the objects filled or stroked with a gradient, by the same rules, with the gradients they use: a linked gradient swatch's name, else its kind's name, such as Linear gradient; kinds gives each one's kind, linear|radial|conic|diamond|freeform, when it is named by its kind, else null; objects.gradients counts them), gradientNames (the gradients those objects use), …, sections: [{id, title, rows: [[label, value]]}] (the panel's categories; fontDetails: each font's file and whether its license lets it be embedded)}. An image linked to a file outside the automation read roots has link null, and its Linked Images row names the file alone. brushNames, brushes, spotObjects, patternObjects and gradientObjects leave out hidden objects, objects at an opacity of 0 and the objects inside a hidden group or layer or one at an opacity of 0 (with selectionOnly too), their characters' paints and colorized images included; objects still counts them as paths, groups and the other kinds",
"{selectionOnly?, category?: document|objects|graphicStyles|brushes|spotColors|patterns|gradients|symbols|fonts|fontDetails|linkedImages|embeddedImages|repeats (only that one in sections and the text), format?: \"text\" (→ {text}: the report Document Info › Save… and Package write)} → {document: {…, units (English), unitId: the units' Preferences › Units id (points, millimeters, feetInches, …), rasterEffectsPpi, transparency: {gridSize: small|medium|large, gridColors: [#rrggbb, #rrggbb], gridColorsName (a preset's name or Custom), simulatePaper, flattenerPreset} (File › Document Setup's transparency settings, which the document category lists), selectedArtboards: [{index, name, width, height, x, y}] (while the Artboard tool is the current tool, the artboards it has selected, in the document's units, x and y those of the top-left corner from the ruler origin of its active artboard, which the document category lists after the artboards; else empty)}, objects: {paths, compoundPaths, groups, …}, pathLength: pt (the paths' total length, compound paths' included, guides left out), fonts (the type in opacity masks and in the art of symbols and patterns included; with selectionOnly: the selected type's), fontDetails: [{font, match: exact|style|missingWithFallback|missing, family, style, file, embedding: allowed|editing|previewPrint|forbidden|null}] (each font of fonts, in order: how it was found, the face shown (null when none), that face's file name (null for a built-in face) and what its license allows), images, imageObjects: [{name, width, height, linked, file}] (the image objects in the order Linked Images and Embedded Images list them; file: what a linked image's row shows, null for an embedded one), swatches, graphicStyleNames (with selectionOnly: the styles the selected objects are linked to), brushNames (the brushes the art's drawn strokes use, each once; with selectionOnly: those the selected objects' strokes use), brushes: [{name, type: calligraphic|scatter|art|pattern|bristle|null}] (those brushes with their types; null: not in the Brushes panel), panelBrushNames (the Brushes panel's brushes), repeatObjects: [{id, name, type: radial|grid|mirror, instances, rows?, cols?}] (the Repeat objects, those in groups and other repeats included; with selectionOnly: those in the selection), spotObjects: [{id, name, spotColors}] (the objects filled or stroked with a spot color swatch, as a solid color or in the stops of a gradient that color a part of it above opacity 0 (a stop at opacity 0 counts only where it mixes with a stop above opacity 0 over a stretch of some width), at a tint above 0, and grayscale images colorized with one, each once, by the rules patternObjects follows, with the spot colors they use; Registration and process colors are not spot colors; objects.spots counts them), spotColorNames and spotColors (the spot colors those objects use), patternObjects: [{id, name, patterns}] (the objects filled or stroked with a pattern, each once, those in groups and type whose drawn characters use one included, hidden fills and strokes, fills and strokes at an opacity of 0, strokes with no width, guides, compound path members' own fills and strokes, images' fills and strokes without a shape and characters that draw nothing left out, with the patterns they use, which objects.patterns counts; with selectionOnly: those in the selection), patternNames (the patterns those objects use), gradientObjects: [{id, name, gradients, kinds}] (the objects filled or stroked with a gradient, by the same rules, with the gradients they use: a linked gradient swatch's name, else its kind's name, such as Linear gradient; kinds gives each one's kind, linear|radial|conic|diamond|freeform, when it is named by its kind, else null; objects.gradients counts them), gradientNames (the gradients those objects use), …, sections: [{id, title, rows: [[label, value]]}] (the panel's categories; fontDetails: each font's file and whether its license lets it be embedded)}. An image linked to a file outside the automation read roots has link null, and its Linked Images row names the file alone. brushNames, brushes, spotObjects, patternObjects and gradientObjects leave out hidden objects, objects at an opacity of 0 and the objects inside a hidden group or layer or one at an opacity of 0 (with selectionOnly too), their characters' paints and colorized images included; objects still counts them as paths, groups and the other kinds",
has_doc,
info
),
@@ -178,14 +178,58 @@ fn repeat_entry(d: &Document, n: &Node, spec: &RepeatSpec) -> (Value, (String, S
(entry, (name, format!("{}, {detail}", kind.label())))
}
/// The artboards the Artboard tool has selected while it is the current tool, in artboard order,
/// with the index of its active artboard; none with another tool or when it has none of the
/// document's artboards selected. Indices the document does not have are left out.
fn artboard_tool_selection(s: &Session) -> Option<(Vec<usize>, usize)> {
if s.tool_id() != "artboard" {
return None;
}
let n = s.active().map_or(0, |d| d.doc.artboards.len());
let t = s.tool_options_of("artboard");
let index = |v: &Value| v.as_u64().and_then(|i| usize::try_from(i).ok()).filter(|i| *i < n);
let mut picked: Vec<usize> = t["selected"].as_array().into_iter().flatten().filter_map(index).collect();
picked.sort_unstable();
picked.dedup();
let first = *picked.first()?;
let active = index(&t["active"]).filter(|a| picked.contains(a)).unwrap_or(first);
Some((picked, active))
}
/// The artboards `picked` as Document Info › Document lists them while the Artboard tool is the
/// current tool: their `selectedArtboards` entries (in the document's units), and for each its
/// rows: its name, width, height and the X and Y of its top-left corner from the ruler origin of
/// artboard `active`.
fn selected_artboard_rows(d: &Document, picked: &[usize], active: usize) -> (Vec<Value>, Vec<(String, String)>) {
let (u, per) = (d.units, d.units.points());
let origin = d.ruler_origin_for(active);
let mut entries = vec![];
let mut rows = vec![];
for &i in picked {
let Some(a) = d.artboards.get(i) else { continue };
let (w, h, x, y) = (a.rect.width(), a.rect.height(), a.rect.x0 - origin.x, a.rect.y0 - origin.y);
entries.push(json!({ "index": i, "name": a.name, "width": w / per, "height": h / per, "x": x / per, "y": y / per }));
rows.extend([
("Artboard".to_string(), a.name.clone()),
("Width".into(), u.format(w)),
("Height".into(), u.format(h)),
("X".into(), u.format(x)),
("Y".into(), u.format(y)),
]);
}
(entries, rows)
}
/// The Document Info categories of `d` (only `category` when given) from `info` (what
/// `document.info` reports), its fonts and their Font Details rows, its image objects, the rows of
/// the brushes its art uses, the rows of its Repeat objects and the rows of its objects filled or
/// stroked with a spot color, with a pattern and with a gradient.
/// `document.info` reports), the rows of the artboards the Artboard tool has selected, its fonts
/// and their Font Details rows, its image objects, the rows of the brushes its art uses, the rows
/// of its Repeat objects and the rows of its objects filled or stroked with a spot color, with a
/// pattern and with a gradient.
#[allow(clippy::too_many_arguments)]
fn sections(
d: &Document,
info: &Value,
selected_artboards: &[(String, String)],
fonts: &BTreeSet<super::fonts::UsedFont>,
font_details: &[(String, String)],
images: &[ImageRow],
@@ -215,7 +259,19 @@ fn sections(
rows.extend(
d.artboards.iter().map(|a| (a.name.clone(), format!("{} × {}", u.format(a.rect.width()), u.format(a.rect.height())))),
);
rows.extend(selected_artboards.iter().cloned());
rows.push(("Raster Effects".into(), format!("{} ppi", d.raster_effects_ppi)));
let setup = &d.setup;
let colors = match setup.grid_colors_name() {
"Custom" => setup.grid_colors.map(|c| c.to_hex()).join(", "),
name => name.to_string(),
};
rows.extend([
("Grid Size".to_string(), setup.grid_size.label().to_string()),
("Grid Colors".into(), colors),
("Simulate Colored Paper".into(), if setup.simulate_paper { "On" } else { "Off" }.into()),
("Flattener Preset".into(), setup.flattener().to_string()),
]);
let counts = [
("Swatches", "swatches"),
("Character Styles", "characterStyles"),
@@ -556,6 +612,7 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
Some("text") => true,
Some(f) => return Err(bad(C, format!("format `{f}`: text or json"))),
};
let artboard_tool = artboard_tool_selection(s);
let st = s.doc()?;
let d = &st.doc;
let selection_only = bool_or(p, "selectionOnly", false);
@@ -787,7 +844,22 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
});
// The document's name: its file's, else its title.
out["document"]["name"] = json!(st.title());
let sections = sections(d, &out, &fonts, &font_rows, &image_rows, &brush_rows, &repeat_rows, &spot_rows, &pattern_rows, &gradient_rows, category);
let (selected_entries, selected_rows) = artboard_tool.map(|(picked, active)| selected_artboard_rows(d, &picked, active)).unwrap_or_default();
out["document"]["selectedArtboards"] = json!(selected_entries);
let sections = sections(
d,
&out,
&selected_rows,
&fonts,
&font_rows,
&image_rows,
&brush_rows,
&repeat_rows,
&spot_rows,
&pattern_rows,
&gradient_rows,
category,
);
if text {
return Ok(json!({ "text": report_text(&st.title(), selection_only, &sections) }));
}
@@ -804,6 +876,13 @@ fn document_summary(d: &Document) -> Value {
"unitId": d.units.key(),
"artboards": d.artboards.iter().map(|a| json!({ "name": a.name, "width": a.rect.width() / u, "height": a.rect.height() / u })).collect::<Vec<_>>(),
"rasterEffectsPpi": d.raster_effects_ppi,
"transparency": {
"gridSize": d.setup.grid_size.id(),
"gridColors": d.setup.grid_colors.map(|c| c.to_hex()),
"gridColorsName": d.setup.grid_colors_name(),
"simulatePaper": d.setup.simulate_paper,
"flattenerPreset": d.setup.flattener(),
},
})
}
@@ -875,6 +954,101 @@ mod tests {
assert!(i["objects"]["textObjects"].is_null() && i["objects"]["paths"] == 1);
}
/// The Document category's rows from `info`, as (label, value) pairs.
fn document_rows(i: &Value) -> Vec<(String, String)> {
let doc = i["sections"].as_array().unwrap().iter().find(|s| s["id"] == "document").unwrap();
doc["rows"].as_array().unwrap().iter().map(|r| (r[0].as_str().unwrap().to_string(), r[1].as_str().unwrap().to_string())).collect()
}
/// Document lists File › Document Setup's transparency settings: the grid's size and colors
/// (a preset's name, else both colors), Simulate Colored Paper and the flattener preset.
#[test]
fn info_lists_the_transparency_settings() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap();
let i = s.execute("document.info", &json!({})).unwrap();
let t = &i["document"]["transparency"];
assert_eq!(
(t["gridSize"].clone(), t["gridColorsName"].clone(), t["simulatePaper"].clone(), t["flattenerPreset"].clone()),
(json!("medium"), json!("Light"), json!(false), json!("Medium Resolution"))
);
let rows = document_rows(&i);
let at = rows.iter().position(|(l, _)| l == "Raster Effects").unwrap();
let expected =
[("Grid Size", "Medium"), ("Grid Colors", "Light"), ("Simulate Colored Paper", "Off"), ("Flattener Preset", "Medium Resolution")];
assert_eq!(rows[at + 1..at + 5], expected.map(|(l, v)| (l.to_string(), v.to_string())), "{rows:?}");
s.execute(
"document.setup",
&json!({"gridSize": "large", "gridColors": ["#ff0000", "#00ff00"], "simulatePaper": true, "flattenerPreset": "High Resolution"}),
)
.unwrap();
let i = s.execute("document.info", &json!({})).unwrap();
assert_eq!(i["document"]["transparency"]["gridColors"], json!(["#ff0000", "#00ff00"]));
assert_eq!(i["document"]["transparency"]["gridColorsName"], "Custom");
let rows = document_rows(&i);
let expected =
[("Grid Size", "Large"), ("Grid Colors", "#ff0000, #00ff00"), ("Simulate Colored Paper", "On"), ("Flattener Preset", "High Resolution")];
assert_eq!(rows[at + 1..at + 5], expected.map(|(l, v)| (l.to_string(), v.to_string())), "{rows:?}");
let report = s.execute("document.info", &json!({"category": "document", "format": "text"})).unwrap()["text"].as_str().unwrap().to_string();
assert!(report.contains("Grid Colors: #ff0000, #00ff00\nSimulate Colored Paper: On\nFlattener Preset: High Resolution\n"), "{report}");
}
/// While the Artboard tool is the current tool, Document lists each artboard it has selected
/// after the artboards: its name, width, height and the X and Y of its top-left corner from the
/// ruler origin of the tool's active artboard. With another tool it lists none.
#[test]
fn info_lists_the_artboards_the_artboard_tool_selected() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
s.execute("artboard.new", &json!({"x": 150, "y": 40, "width": 60, "height": 80})).unwrap();
s.execute("artboard.new", &json!({"x": 400, "y": 10, "width": 100, "height": 50})).unwrap();
s.execute("artboard.setProps", &json!({"index": 2, "name": "Back"})).unwrap();
let before = s.execute("document.info", &json!({})).unwrap();
assert_eq!(before["document"]["selectedArtboards"], json!([]));
s.select_tool("artboard", crate::tooling::ViewInfo::default()).unwrap();
s.set_tool_option("selected", &json!([2, 1, 7]));
let i = s.execute("document.info", &json!({})).unwrap();
// Artboard 2 is active: positions are measured from its top-left corner.
assert_eq!(
i["document"]["selectedArtboards"],
json!([
{"index": 1, "name": "Artboard 2", "width": 60.0, "height": 80.0, "x": -250.0, "y": 30.0},
{"index": 2, "name": "Back", "width": 100.0, "height": 50.0, "x": 0.0, "y": 0.0},
])
);
let rows = document_rows(&i);
let at = rows.iter().position(|(l, _)| l == "Artboards").unwrap() + 4;
let expected = [
("Artboard", "Artboard 2"),
("Width", "60 pt"),
("Height", "80 pt"),
("X", "-250 pt"),
("Y", "30 pt"),
("Artboard", "Back"),
("Width", "100 pt"),
("Height", "50 pt"),
("X", "0 pt"),
("Y", "0 pt"),
("Raster Effects", "72 ppi"),
];
assert_eq!(rows[at..at + 11], expected.map(|(l, v)| (l.to_string(), v.to_string())), "{rows:?}");
// The rows follow the document's units and its ruler origin.
s.execute("document.setup", &json!({"units": "Millimeters"})).unwrap();
s.execute("document.setRulerOrigin", &json!({"x": 390, "y": 0, "artboard": 2})).unwrap();
s.set_tool_option("selected", &json!([2]));
let i = s.execute("document.info", &json!({"category": "document"})).unwrap();
let entry = &i["document"]["selectedArtboards"];
assert_eq!((entry.as_array().unwrap().len(), entry[0]["index"].clone()), (1, json!(2)));
assert!((entry[0]["x"].as_f64().unwrap() - 10.0 * 25.4 / 72.0).abs() < 1e-9, "{entry}");
let rows = document_rows(&i);
assert!(rows.contains(&("X".into(), "3.5278 mm".into())) && rows.contains(&("Y".into(), "3.5278 mm".into())), "{rows:?}");
// Another tool: no artboard rows.
s.select_tool("selection", crate::tooling::ViewInfo::default()).unwrap();
let i = s.execute("document.info", &json!({})).unwrap();
assert_eq!(i["document"]["selectedArtboards"], json!([]));
assert!(!document_rows(&i).iter().any(|(l, _)| l == "X"), "{:?}", document_rows(&i));
}
/// Document Info's fonts include the type in an opacity mask, in a symbol's art and in a
/// pattern swatch that nothing paints with; with `selectionOnly`, only the selected type's.
#[test]
+3 -3
View File
@@ -11,7 +11,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Pencil",
[],
None,
"{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1: the stroke keeps it, for Calligraphic and Scatter brushes with Pressure variation; a point without one presses fully. Pen tilt in degrees, each −90..90, x positive leaning right and y leaning down the page, and barrel rotation in degrees clockwise, 0..360: the stroke keeps how far the pen leaned, which way and how far its barrel turned, for brushes with Tilt, Bearing and Rotation variation; null for what a point lacks. A pressure, tilt or rotation outside its range, or a point array of more than six numbers, is an error), fidelity?: pt (1.5; from 0.000015625 (0.01 / 640) to 100 / 0.0313 (about 3194.89), the Pencil's and the Paintbrush's 0.01 to 100 px Fidelity at the highest and the lowest zoom; a value outside that range is an error. The tools send their Fidelity in pixels divided by the zoom, kept within the range), fit?: bool (true; false: the points are joined by straight segments, as the Pencil previews a stroke with Live curve fitting off), closed?, style?: \"pencil\"|\"brush\", fill?: bool, keepSelected?: bool (true: the drawn or continued path is selected; false: a new path leaves nothing selected, and a continued or redrawn one is deselected while the rest of the selection stays), extend?: {id, end: \"start\"|\"end\"}, connect?: {id, end: \"start\"|\"end\"}, redraw?: {id, within?: pt (12)}} fit a freehand stroke → {id}. extend continues the path from that end, and closes it when `closed` is true (left out, when the stroke ends within four Fidelities of the path's other end, 6 to 400 pt); with connect, the stroke ends on that end of another path's last open subpath and joins it on, in one path with the extended path's appearance (the other path is removed when nothing of it is left); redraw (Edit Selected Paths) replaces the section of the path between where the stroke starts and ends, each within `within` of one subpath (the shorter way round a closed one), and draws a new path when the stroke doesn't end on it",
"{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1: the stroke keeps it, for Calligraphic and Scatter brushes with Pressure variation; a point without one presses fully. Pen tilt in degrees, each −90..90, x positive leaning right and y leaning down the page, and barrel rotation in degrees clockwise, 0..360: the stroke keeps how far the pen leaned, which way and how far its barrel turned, for brushes with Tilt, Bearing and Rotation variation; null for what a point lacks. A pressure, tilt or rotation outside its range, or a point array of more than six numbers, is an error), fidelity?: pt (1.5; from 0.000015625 (0.01 / 640) to 100 / 0.0313 (about 3194.89), the Pencil's and the Paintbrush's 0.01 to 100 px Fidelity at the highest and the lowest zoom; a value outside that range is an error. The tools send their Fidelity in pixels divided by the zoom, kept within the range), fit?: bool (true; false: the points are joined by straight segments, as the Pencil previews a stroke with Live curve fitting off), closed?, style?: \"pencil\" (default) | \"brush\", fill?: bool, keepSelected?: bool (true: the drawn or continued path is selected; false: a new path leaves nothing selected, and a continued or redrawn one is deselected while the rest of the selection stays), extend?: {id, end?: \"end\" (default) | \"start\"}, connect?: {id, end: \"start\"|\"end\"}, redraw?: {id, within?: pt (12)}} fit a freehand stroke → {id}. extend continues the path from that end, and closes it when `closed` is true (left out, when the stroke ends within four Fidelities of the path's other end, 6 to 400 pt); with connect, the stroke ends on that end of another path's last open subpath and joins it on, in one path with the extended path's appearance (the other path is removed when nothing of it is left); redraw (Edit Selected Paths) replaces the section of the path between where the stroke starts and ends, each within `within` of one subpath (the shorter way round a closed one), and draws a new path when the stroke doesn't end on it. Any other style, extend end or connect end is an error, and nothing changes",
has_doc,
freehand
),
@@ -101,7 +101,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Path Eraser",
[],
None,
"{points: [[x,y]…] (pen values after x and y are checked as path.freehand checks them and do not change what is erased), width?: pt (8)} erase the parts of selected paths under the drag → {ids}",
"{points: [[x,y]…] (pen values after x and y are checked as path.freehand checks them and do not change what is erased), width?: pt (8; from 0.001 to 1000)} erase the parts of selected paths under the drag → {ids}. A width outside 0.001 to 1000 is refused with an error, and nothing changes",
has_selection,
erase_segments
),
@@ -128,7 +128,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Blob Brush",
[],
None,
"{points: [[x,y]…] or [[x,y,pressure]…] (pen pressure 0..1; pen values are checked as path.freehand checks them), size?: pt (10; from 0.1 to 1000), sizeMode?: \"fixed\" (default) | \"pressure\" (Blob Brush Tool Options' Size set to Pressure: the brush is size − sizeVariation wide at the lightest pen pressure and size + sizeVariation at the heaviest, at least 0.1 pt; a stroke without pressure keeps the size), sizeVariation?: pt (0; from 0 to 1000, checked with Fixed too), angle?: ° (0, kept within −180–180: the tip's long axis counter-clockwise from horizontal, kept on the page along the stroke), roundness?: % (100, kept within 0–100: the tip's short axis in percent of its long one, 100 round; 0 is drawn as 0.1), fidelity?: pt (0.01–100; the brush follows the stroke fitted at this tolerance as path.freehand fits a Pencil stroke, and a higher value gives a smoother shape; without it the brush follows every point), merge?: true, mergeOnlySelection?: bool (false: merge with any touching same-color blob; true: only with selected ones), keepSelected?: bool (false: the drawn or merged path is not selected, and the rest of the selection stays; true: it is selected)} filled brush shape, merged with the topmost touching same-color blob and the touching ones next to it in stacking order in its group or layer → {id}",
"{points: [[x,y]…] or [[x,y,pressure]…] (pen pressure 0..1; pen values are checked as path.freehand checks them), size?: pt (10; from 0.1 to 1000), sizeMode?: \"fixed\" (default) | \"pressure\" (Blob Brush Tool Options' Size set to Pressure: the brush is size − sizeVariation wide at the lightest pen pressure and size + sizeVariation at the heaviest, at least 0.1 pt; a stroke without pressure keeps the size), sizeVariation?: pt (0; from 0 to 1000, checked with Fixed too), angle?: ° (0, −180–180: the tip's long axis counter-clockwise from horizontal, kept on the page along the stroke), roundness?: % (100, 0–100: the tip's short axis in percent of its long one, 100 round; 0 is drawn as 0.1), fidelity?: pt (0.01–100; the brush follows the stroke fitted at this tolerance as path.freehand fits a Pencil stroke, and a higher value gives a smoother shape; without it the brush follows every point), merge?: true, mergeOnlySelection?: bool (false: merge with any touching same-color blob; true: only with selected ones), keepSelected?: bool (false: the drawn or merged path is not selected, and the rest of the selection stays; true: it is selected)} filled brush shape, merged with the topmost touching same-color blob and the touching ones next to it in stacking order in its group or layer → {id}. An angle, roundness or fidelity outside its range is rejected with an error, and nothing changes",
has_doc,
blob
),
+4 -4
View File
@@ -522,13 +522,13 @@ fn apply_plan(s: &mut Session, label: &str, plan: Vec<(NodeId, Vec<PathData>)>)
Ok(ids_json(&ids))
}
/// The Path Eraser's band width, in points (VectorCraft's own range).
const PATH_ERASER_WIDTHS: (f64, f64) = (0.001, 1000.0);
pub(super) fn erase_segments(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "path.eraseSegments";
let pts = points_param(p, "points", C)?;
let w = number_or(p, "width", 8.0, C)?;
if !(w.is_finite() && w > 0.0) {
return Err(bad(C, "width must be positive"));
}
let w = ranged(p, "width", 8.0, PATH_ERASER_WIDTHS, C)?;
let st = s.doc()?;
let mut plan = vec![];
for id in target_paths(&st.doc, &st.selection, poly_bounds(&pts, w)) {
+30 -14
View File
@@ -174,9 +174,13 @@ fn no_stroke(name: &str) -> EngineError {
bad("brush.freehand", format!("cannot apply brush `{name}`: path has no stroke"))
}
/// Sets brush `name` on the stroke of object `id` of `d`.
/// Sets brush `name` on the stroke of object `id` of `d`. The stroke's own settings for another
/// brush (Options of Selected Object) are cleared.
fn set_brush(d: &mut Document, id: NodeId, name: &str) {
if let Some(st) = d.node_mut(id).and_then(|n| n.appearance.stroke_mut()) {
if st.brush.as_deref() != Some(name) {
st.brush_options.clear();
}
st.brush = Some(name.to_string());
}
}
@@ -200,14 +204,22 @@ pub(crate) fn freehand_brushed(s: &mut Session, p: &Value, brush_name: Option<&s
// The tolerance the stroke is fitted at; with `fit: false` it is not fitted.
let fit_tol = switch_or(p, "fit", true, C)?.then_some(tol);
let closed = switch_or(p, "closed", false, C)?;
let brush = str_param(p, "style") == Some("brush");
let brush = match p.get("style").filter(|v| !v.is_null()).map(Value::as_str) {
None | Some(Some("pencil")) => false,
Some(Some("brush")) => true,
Some(_) => return Err(bad(C, "style must be \"pencil\" or \"brush\"")),
};
// The undo step's name: a stroke painted with a brush is a Paintbrush stroke, whatever its style.
let label = if brush || brush_name.is_some() { "Paintbrush" } else { "Pencil" };
let keep_selected = switch_or(p, "keepSelected", true, C)?;
let filled = switch_or(p, "fill", false, C)?;
if let Some(ext) = p.get("extend").filter(|v| !v.is_null()) {
let id = object_param(ext, "id", C)?.ok_or_else(|| bad(C, "extend needs id"))?;
let at_start = str_param(ext, "end") == Some("start");
let at_start = match ext.get("end").filter(|v| !v.is_null()).map(Value::as_str) {
None | Some(Some("end")) => false,
Some(Some("start")) => true,
Some(_) => return Err(bad(C, "extend end must be \"start\" or \"end\"")),
};
let (pd, _) = path_of(&s.doc()?.doc, id)?;
let si = pd.subpaths.iter().rposition(|s| !s.closed && !s.anchors.is_empty()).ok_or_else(|| bad(C, "path has no open end"))?;
let target = brush_target(&s.doc()?.doc, id);
@@ -488,12 +500,23 @@ pub(super) fn blob(s: &mut Session, p: &Value) -> Result<Value> {
let samples = samples_param(p, "points", C)?;
let size = ranged(p, "size", 10.0, SIZES, C)?;
let angle = number_or(p, "angle", 0.0, C)?;
if !(-180.0..=180.0).contains(&angle) {
return Err(bad(C, "`angle` must be from -180 to 180 degrees"));
}
let roundness = number_or(p, "roundness", 100.0, C)?;
if !angle.is_finite() || !roundness.is_finite() {
return Err(bad(C, "angle and roundness must be finite"));
if !(0.0..=100.0).contains(&roundness) {
return Err(bad(C, "`roundness` must be from 0 to 100%"));
}
// With `fidelity` (pt), the brush follows the stroke fitted by [`fit_freehand`], as a Pencil
// stroke is fitted. Without it, or when the fitted stroke has no length (a short stroke back to
// its start), the brush follows every point.
let fidelity = match p.get("fidelity") {
None | Some(Value::Null) => None,
Some(_) => Some(number_or(p, "fidelity", 0.0, C)?),
};
if fidelity.is_some_and(|f| !(vectorcraft_tools::draw2::MIN_FIDELITY..=100.0).contains(&f)) {
return Err(bad(C, "`fidelity` must be from 0.01 to 100 pt"));
}
let angle = angle.clamp(-180.0, 180.0);
let roundness = roundness.clamp(0.0, 100.0);
let tip = vectorcraft_tools::draw2::blob_tip(angle, roundness);
let squash = tip.inverse();
// Width profiles use distance along the spine, so measure pressure on the same squashed
@@ -515,13 +538,6 @@ pub(super) fn blob(s: &mut Session, p: &Value) -> Result<Value> {
let mapped_pts: Vec<Point> = mapped_samples.into_iter().map(|s| s.pt).collect();
// The widest the brush gets: the area merges look in.
let reach = pressure.as_ref().map_or(size, |(_, v)| size + v);
// With `fidelity` (pt), the brush follows the stroke fitted by [`fit_freehand`], as a Pencil
// stroke is fitted. Without it, or when the fitted stroke has no length (a short stroke back to
// its start), the brush follows every point.
let fidelity = match p.get("fidelity") {
None | Some(Value::Null) => None,
Some(_) => Some(number_or(p, "fidelity", 0.0, C)?.clamp(vectorcraft_tools::draw2::MIN_FIDELITY, 100.0)),
};
let spine = |tol: Option<f64>| {
let path = match tol {
Some(tol) => PathData::single(fit_freehand(&pts, tol, false)),
+12 -6
View File
@@ -1150,21 +1150,27 @@ fn random_brushes_baked<'a>(
std::borrow::Cow::Owned(def)
}
/// Does brush `name` of `brushes` draw different art for different points: a calligraphic or
/// scatter brush with Random variation, or a bristle brush?
fn draws_random_art(brushes: &[vectorcraft_brush::Brush], name: &str) -> bool {
/// Does brush `name` of `brushes`, with the stroke's own brush settings `options`, draw different
/// art for different points: a calligraphic or scatter brush with Random variation, or a bristle
/// brush?
fn draws_random_art(brushes: &[vectorcraft_brush::Brush], name: &str, options: &serde_json::Map<String, Value>) -> bool {
use vectorcraft_brush::{BrushKind, Variation};
brushes.iter().find(|b| b.name == name).is_some_and(|b| match &b.kind {
let Some(brush) = brushes.iter().find(|b| b.name == name) else { return false };
let edited = if options.is_empty() { None } else { brush.with_stroke_options(options).ok() };
let b = edited.as_ref().unwrap_or(brush);
match &b.kind {
BrushKind::Calligraphic(c) => c.modes().contains(&Variation::Random),
BrushKind::Scatter(s) => s.modes().contains(&Variation::Random),
BrushKind::Bristle(_) => true,
BrushKind::Art(_) | BrushKind::Pattern(_) => false,
})
}
}
/// Is `n` a path with a visible stroke whose brush varies at random ([`draws_random_art`])?
fn random_brushed(brushes: &[vectorcraft_brush::Brush], n: &Node) -> bool {
let random = |st: &vectorcraft_doc::appearance::StrokeLayer| st.visible && st.brush.as_deref().is_some_and(|b| draws_random_art(brushes, b));
let random = |st: &vectorcraft_doc::appearance::StrokeLayer| {
st.visible && st.brush.as_deref().is_some_and(|b| draws_random_art(brushes, b, &st.brush_options))
};
matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. })
&& n.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Stroke(st) if random(st)))
}
+6 -4
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;
@@ -131,7 +133,7 @@ mod formats;
#[cfg(not(target_arch = "wasm32"))]
pub(crate) use access::list_dir;
pub(crate) use access::{check_images_in, check_scripts_of};
pub(crate) use access::{check_images_in, check_scripts_of, with_readable_settings_folder};
pub use access::{check_linked_images, check_linked_scripts, write_file_with, write_save_file, write_save_file_with};
#[cfg(all(test, not(target_arch = "wasm32")))]
+41 -5
View File
@@ -171,13 +171,14 @@ pub(crate) fn names_linked_scripts(cmd: &str, format: &str, p: &Value, artboards
}
}
/// The error for an SVG that would name a linked image's file outside the read roots.
/// The error for a file that would name a linked image's file outside the read roots.
pub(crate) const IMAGE_OUTSIDE: &str = "a linked image file is outside the read roots";
/// `cmd` may write `d`, the document an output of `st` writes (all of it, or the objects it
/// exports), in format `format` (a format id) with options `p`: any format but SVG and SVGZ, and
/// those too unless read roots are in force and the file would name a linked image's file outside
/// them (a relative path taken from `st`'s folder; a URL is not checked). An `<image>` names the
/// exports), in format `format` (a format id) with options `p`: always, unless read roots are in
/// force and the file would name a linked image's file outside them (a relative path taken from
/// `st`'s folder; a URL is not checked). In any format but SVG and SVGZ, the file names them when it
/// carries the native document ([`check_native_images`]). An `<image>` names the
/// file with SVG Options › Images set to Link, and with Embed when the document holds no pixels for
/// the image, for the images of the art each file draws (with chosen artboards, the art over each
/// one; hidden layers and objects only with `hiddenLayers`, template layers and the opacity-mask
@@ -193,9 +194,12 @@ pub fn check_linked_images(cmd: &str, format: &str, st: &crate::DocState, d: &ve
/// [`check_linked_images`] for `d`, a document whose links are looked for from `base` (the
/// objects on the clipboard, looked for from the document they came from).
pub(crate) fn check_images_in(cmd: &str, format: &str, d: &vectorcraft_doc::Document, base: crate::cmd::links::LinkBase, p: &Value) -> Result<()> {
if !matches!(format, "svg" | "svgz") || crate::file_access::current().is_none() {
if crate::file_access::current().is_none() {
return Ok(());
}
if !matches!(format, "svg" | "svgz") {
return check_native_images(cmd, format, d, base, p);
}
// Options that don't read as the encoder's choices count as Link, Preserve Editing, hidden
// layers kept and SVG 1.1: the encoder refuses them anyway.
let (link, preserve, hidden, tiny) = match super::svg::options_map(p) {
@@ -222,6 +226,38 @@ pub(crate) fn check_images_in(cmd: &str, format: &str, d: &vectorcraft_doc::Docu
Ok(())
}
/// `cmd` may write `d` in format `format` (a format id other than SVG and SVGZ) with options `p`:
/// always, unless read roots are in force, the file carries the native document (a native file or
/// template, an EPS file, a `.ai` or `.ait` file or a PDF with Preserve Editing, as
/// [`names_linked_scripts`] counts them with `d`'s artboards) and that document names a file
/// outside them ([`crate::cmd::links::names_hidden_file`]: a linked image or placed file, the
/// relative path kept of one taken from `base`, a data set's image, or stored brushes that can't be
/// read). The error names no file or folder.
pub(crate) fn check_native_images(
cmd: &str,
format: &str,
d: &vectorcraft_doc::Document,
base: crate::cmd::links::LinkBase,
p: &Value,
) -> Result<()> {
let carried =
crate::file_access::current().is_some() && !matches!(format, "svg" | "svgz") && names_linked_scripts(cmd, format, p, d.artboards.len());
if carried && crate::cmd::links::names_hidden_file(d, base) { Err(bad(cmd, IMAGE_OUTSIDE)) } else { Ok(()) }
}
/// `doc` as a file written for the request being served carries it: without an Export for Screens
/// `folder` outside the read roots ([`super::screens::leave_out_unreadable_settings_folder`]). The
/// open document keeps it.
pub(crate) fn with_readable_settings_folder(doc: &vectorcraft_doc::Document) -> std::borrow::Cow<'_, vectorcraft_doc::Document> {
let settings = super::screens::leave_out_unreadable_settings_folder(doc.export_settings.clone());
if settings.len() == doc.export_settings.len() {
return std::borrow::Cow::Borrowed(doc);
}
let mut kept = doc.clone();
kept.export_settings = settings;
std::borrow::Cow::Owned(kept)
}
/// `path` checked for writing against the automation roots in force.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn may_write(path: &str) -> Result<()> {
+1 -1
View File
@@ -9,7 +9,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Open Document",
[],
None,
"{path | name | dataBase64 (a file's path, or its name with its bytes), pages?: \"2-3, 5\" (PDF/.ai: 1-based, default all; one artboard each) | page?: n, cropTo?: bounding|art|crop (default)|trim|bleed|media (the box each artboard gets; bounding: the art's bounds; trim: the bleed box round it becomes the document's bleed, and the artboards are 36 pt apart plus that bleed on both sides; a PDF-compatible .ai or a PDF saved with its editing data opens on its trim boxes for crop), password? (encrypted PDFs; see document.pdfInfo), textAs?: text (default: point type per line, lines wrapped in a frame as area type where they lay out the same, in the file's fonts by name; missing ones are listed in warnings) | outlines (glyph paths), layers?: true (default: optional content groups become layers with their visibility, print state and lock — art that is off comes in as a hidden layer; other art goes to a layer per page; a PSD file's layers become layers holding their pixels, with their names, visibility, opacity and blend modes, groups as layers of sublayers, layer masks as opacity masks, clipped layers and layers in blend modes VectorCraft doesn't have merged with the layers below) | false (one layer per page, without the art that is off; Save then asks for a name; a PSD file opens as its merged image), hiddenLayers?: false (a PSD file's hidden layers come in hidden instead of being left out), importSlices?: true (a PSD file's slices become user slices over its canvas, with its layers or its merged image; slices the file generated automatically are left out, and slices that can't be read are left out with a warning), editingData?: true (default: an EPS, .ai or PDF that carries its editor's own copy of the art opens from it, with its layers, hidden objects, guides, artboards and the art outside them; a .ai or PDF whose type shows opens from its PDF part with textAs: outlines) | \"always\" (as true, and a .ai's editing copy is used even where it draws differently from its PDF part, which can be older; the warnings say so) | false (only what its page or PDF part prints, for print pipelines; a .ai saved without PDF compatibility then can't be opened), legacyNameEncoding?: windows-1252 (default) | macintosh | windows-949 (also euc-kr) | shift_jis | gbk | big5 (the code page names in the editing data of a .ai or an EPS are read in when they aren't UTF-8: layers, objects, artboards, colors, gradients, patterns, graphic styles, swatches, brushes, symbols, variables and data sets, and data sets' text values; warnings list the first three such names as read, and count the rest), colorMode?: rgb|cmyk (the mode the document opens in, its colours converted as file.documentColorMode does, through the profiles the document keeps after the color management policies of edit.colorSettings, grays? as there; default: the file's — a PDF keeps CMYK, Gray and spot inks (spot swatches at a tint) and opens in CMYK when painted mostly in CMYK), grays?: as file.documentColorMode, dxf?: {layout?: \"Model\" (default) | a paper layout's name (document.dxfInfo lists them), unit?, scale? (the ratio: 1 unit of the art = scale drawing units; default: the drawing at 1:1 in its own unit), fit?: false (scale to fit an artboard of fitTo?: [612, 792], turned to the art's orientation), scaleLineweights?: false (lineweights scale with the art), center?: true (false: the drawing's origin on the artboard's bottom-left corner; fitted art's bottom-left corner), mergeLayers?: false (all art on one layer)} (DXF), crop?: as cropTo (its older name), linkPages?: false (true: each page `pages` picks of a PDF or PDF-compatible .ai opens as a placed document linked to that page of the file, as file.place with link places one, on an artboard of its cropTo box (bounding: its art's bounds; a blank page: its crop box; a PDF-compatible .ai: its trim box for crop; on its trim box a page shows its bleed box round the artboard and gives the document its bleed), in a row 36 pt apart (on trim boxes, plus the bleed on both sides), and a layer named after the page; links.embed makes a page editable art; refused for any other file, without a path, with a password or with textAs: outlines; Save then asks for a name), importer?: \"plugin.<id>\" (an importer plug-in's format id, see document.formats: it opens the file, which must have an extension it lists, also one a built-in format reads), params?: {…} (the importer's own parameters, see plugin.info)} → {index, title, format, warnings, restored, missingLinks, modifiedLinks, updatedLinks: [{name, path, ids}]}; the color management policies of edit.colorSettings keep, take off or convert from the profiles the file is tagged with, their notes go to warnings, and a document they changed opens with unsaved changes; any readable format (see document.formats): .vectorcraft/.drawcraft, .svg/.svgz, .pdf/.ai, .ait, ASCII .dxf (each DXF layer with art a layer; blocks symbols; what can't come in is listed in warnings), PNG Line truncated
"{path | name | dataBase64 (a file's path, or its name with its bytes), pages?: \"2-3, 5\" (PDF/.ai: 1-based, default all; one artboard each) | page?: n, cropTo?: bounding|art|crop (default)|trim|bleed|media (the box each artboard gets; bounding: the art's bounds; trim: the bleed box round it becomes the document's bleed, and the artboards are 36 pt apart plus that bleed on both sides; a PDF-compatible .ai or a PDF saved with its editing data opens on its trim boxes for crop), password? (encrypted PDFs; see document.pdfInfo), textAs?: text (default: point type per line, lines wrapped in a frame as area type where they lay out the same, in the file's fonts by name; missing ones are listed in warnings) | outlines (glyph paths), layers?: true (default: optional content groups become layers with their visibility, print state and lock — art that is off comes in as a hidden layer; other art goes to a layer per page; a PSD file's layers become layers holding their pixels, with their names, visibility, opacity and blend modes, groups as layers of sublayers, layer masks as opacity masks, clipped layers and layers in blend modes VectorCraft doesn't have merged with the layers below) | false (one layer per page, without the art that is off; Save then asks for a name; a PSD file opens as its merged image), hiddenLayers?: false (a PSD file's hidden layers come in hidden instead of being left out), importSlices?: true (a PSD file's slices become user slices over its canvas, with its layers or its merged image; slices the file generated automatically are left out, and slices that can't be read are left out with a warning), editingData?: true (default: an EPS, .ai or PDF that carries its editor's own copy of the art opens from it, with its layers, hidden objects, guides, artboards and the art outside them; a .ai or PDF whose type shows opens from its PDF part with textAs: outlines) | \"always\" (as true, and a .ai's editing copy is used even where it draws differently from its PDF part, which can be older; the warnings say so) | false (only what its page or PDF part prints, for print pipelines; a .ai saved without PDF compatibility then can't be opened), legacyNameEncoding?: windows-1252 (default) | macintosh | windows-949 (also euc-kr) | shift_jis | gbk | big5 (the code page names in the editing data of a .ai or an EPS are read in when they aren't UTF-8: layers, objects, artboards, colors, gradients, patterns, graphic styles, swatches, brushes, symbols, variables and data sets, and data sets' text values; warnings list the first three such names as read, and count the rest), colorMode?: rgb|cmyk (the mode the document opens in, its colours converted as file.documentColorMode does, through the profiles the document keeps after the color management policies of edit.colorSettings, grays? as there; default: the file's — a PDF keeps CMYK, Gray and spot inks (spot swatches at a tint) and opens in CMYK when painted mostly in CMYK), grays?: as file.documentColorMode, dxf?: {layout?: \"Model\" (default) | a paper layout's name (document.dxfInfo lists them), unit?, scale? (the ratio: 1 unit of the art = scale drawing units; default: the drawing at 1:1 in its own unit), fit?: false (scale to fit an artboard of fitTo?: [612, 792], turned to the art's orientation), scaleLineweights?: false (lineweights scale with the art), center?: true (false: the drawing's origin on the artboard's bottom-left corner; fitted art's bottom-left corner), mergeLayers?: false (all art on one layer)} (DXF), crop?: as cropTo (its older name), linkPages?: false (true: each page `pages` picks of a PDF or PDF-compatible .ai opens as a placed document linked to that page of the file, as file.place with link places one, on an artboard of its cropTo box (bounding: its art's bounds; a blank page: its crop box; a PDF-compatible .ai: its trim box for crop; on its trim box a page shows its bleed box round the artboard and gives the document its bleed), in a row 36 pt apart (on trim boxes, plus the bleed on both sides), and a layer named after the page; links.embed makes a page editable art; refused for any other file, without a path, with a password or with textAs: outlines; Save then asks for a name), importer?: \"plugin.<id>\" (an importer plug-in's format id, see document.formats: it opens the file, which must have an extension it lists, also one a built-in format reads), params?: {…} (the importer's own parameters, see plugin.info)} → {index, title, format, warnings, restored, missingLinks, modifiedLinks, updatedLinks: [{name, path, ids}]}; the color management policies of edit.colorSettings keep, take off or convert from the profiles the file is tagged with, their notes go to warnings, and a document they changed opens with unsaved changes; any readable format (see document.formats): .vectorcraft/.drawcraft, .svg/.svgz, .pdf/.ai, .ait, ASCII .dxf (each DXF layer with art a layer; blocks symbols; what can't come in is listed in warnings), PNG Line truncated
always,
load::open
),
+3 -1
View File
@@ -280,8 +280,10 @@ fn thumbnail_of(preview: &Rendered, rect: Rect) -> Result<Raster> {
}
/// What the file carries to reopen: `doc` (with only artboard `board` when the file is one of
/// several artboards), with linked images whole when `include_linked`.
/// several artboards), with linked images whole when `include_linked`, and without an Export for
/// Screens folder outside the read roots ([`super::access::with_readable_settings_folder`]).
fn native(doc: &Document, board: Option<usize>, include_linked: bool) -> Vec<u8> {
let doc = &*super::access::with_readable_settings_folder(doc);
let several = board.filter(|_| doc.artboards.len() > 1);
if several.is_none() && !include_linked {
return vectorcraft_format::save(doc, false);
+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
}
+2 -2
View File
@@ -838,13 +838,13 @@ fn other_open_filters() -> impl Iterator<Item = (&'static str, &'static [&'stati
/// Open-dialog filters for Swatch Libraries and Graphic Style Libraries Other Library… and Locate
/// Library…. The library formats come first so Linux file portals (which grey out files that don't
/// match the default filter) still list `.ase` and the other library extensions; then the same
/// filters as [`builtin_open_filters`], without a second copy of the library filter, so a document
/// filters as [`builtin_open_filters`], without a second filter of that label, so a document
/// can be picked for its swatches or graphic styles.
pub fn library_open_filters(
library_label: &'static str,
library_exts: &'static [&'static str],
) -> impl Iterator<Item = (&'static str, &'static [&'static str])> {
std::iter::once((library_label, library_exts)).chain(builtin_open_filters().filter(move |f| *f != (library_label, library_exts)))
std::iter::once((library_label, library_exts)).chain(builtin_open_filters().filter(move |f| f.0 != library_label))
}
/// File → Place dialog filters: "All placeable files", then one per placeable format, then text,
+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");
}
+4
View File
@@ -231,6 +231,8 @@ pub(super) fn encode_to(cmd: &str, f: &Format, doc: &Document, p: &Value, w: imp
}
other => other,
};
// Without an Export for Screens folder outside the read roots.
let native = super::access::with_readable_settings_folder(&native);
so.pretty = so.pretty_fits(&native);
vectorcraft_format::save_to(&native, &so, w).map_err(|e| bad(cmd, e.to_string()))
}
@@ -308,6 +310,8 @@ pub(super) fn ai_native(cmd: &str, doc: &Document, so: &SaveOptions) -> Result<V
} else {
Cow::Borrowed(doc)
};
// Without an Export for Screens folder outside the read roots.
let native = super::access::with_readable_settings_folder(&native);
vectorcraft_format::save_with(&native, so).map_err(|e| bad(cmd, e.to_string()))
}
+14 -7
View File
@@ -338,7 +338,9 @@ pub(super) fn encode_at(cmd: &str, doc: &Document, p: &Value, modified: Option<i
// Keep the editable object tree independent of preview fallbacks used by the drawn pages.
let (full, placed) = crate::cmd::place::document::full_documents(doc);
let mut notes: Vec<Note> = placed.into_iter().map(Note::loss).collect();
let (bytes, drawn) = encode_carrying_at(cmd, &full, p, modified, || Ok(vectorcraft_format::save(doc, false)), || Ok(None))?;
// The editing data leaves out an Export for Screens folder outside the read roots.
let native = || Ok(vectorcraft_format::save(&super::access::with_readable_settings_folder(doc), false));
let (bytes, drawn) = encode_carrying_at(cmd, &full, p, modified, native, || Ok(None))?;
notes.extend(drawn);
if notes.iter().any(|n| n.text.ends_with(SHOWN_SMALLER)) && options(cmd, &full, p)?.settings.standard == Standard::None {
for n in notes.iter_mut().filter(|n| n.text.ends_with(SHOWN_SMALLER)) {
@@ -417,9 +419,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 +444,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 +462,8 @@ fn flatten_for(cmd: &str, doc: &Document, set: &PdfSettings, p: &Value) -> Resul
// its art: it is clipped to its regions (opaque inside them).
o.clip_complex_regions = true;
Ok(match flatten_document(shown.as_ref().unwrap_or(doc), &o)? {
Some(flat) => (Some(flat), true),
None => (shown, false),
Some(flat) => (Some(flat), Some(o)),
None => (shown, None),
})
}
@@ -500,6 +506,7 @@ fn export_pdf(s: &mut Session, p: &Value) -> Result<Value> {
let p = &*expanded;
let st = s.doc()?;
super::check_linked_scripts(C, "pdf", st, p)?;
super::check_linked_images(C, "pdf", st, &st.doc, p)?;
let display_doc_title = super::has_own_title(&st.doc);
let titled = super::titled_for_export(&st.doc, st.path.as_deref(), "pdf");
let mut q = p.clone();
+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.
+5 -1
View File
@@ -896,7 +896,10 @@ fn job_for_stamped(s: &Session, st: &DocState, plan: SavePlan, stamped: Option<i
params.entry("hiddenLayers").or_insert(Value::Bool(true));
}
let params = Value::Object(params);
super::check_linked_images(cmd, plan.format.id, st, &own, &params)?;
// Other formats are checked below, with the options the encoder reads.
if is_svg(plan.format) {
super::check_linked_images(cmd, plan.format.id, st, &own, &params)?;
}
// The file the document is saved as (else its own) titles it if New's name is all it has.
let file = plan.path.as_deref().filter(|_| plan.retargets()).or(st.path.as_deref());
if let Some(d) = super::titled_for_export(&own, file, plan.format.id) {
@@ -941,6 +944,7 @@ fn job_for_stamped(s: &Session, st: &DocState, plan: SavePlan, stamped: Option<i
_ => std::borrow::Cow::Borrowed(&params),
};
super::check_linked_scripts(cmd, plan.format.id, st, &checked)?;
super::access::check_native_images(cmd, plan.format.id, &st.doc, crate::cmd::links::LinkBase::of(st), &checked)?;
Ok(SaveJob { plan, doc, params, snapshot, source: st.doc.clone(), stamped, boards })
}
+43 -15
View File
@@ -1129,6 +1129,28 @@ fn names_scripts(item: &Item, r: &Row, single: Option<&[usize]>) -> bool {
super::access::names_linked_scripts(C, "pdf", &options, doc.artboards.len())
}
/// The document the file of `item` that row `r` writes carries when it carries one
/// ([`names_scripts`]): Full Document's PDF of every artboard, the item's artboard alone for a
/// native, `.ai` or EPS row ([`board_document`]), else the item's document.
fn carried_document<'a>(item: &'a Item, r: &Row, single: Option<&[usize]>) -> std::borrow::Cow<'a, Document> {
match (&item.every_artboard, r.format.id, single) {
(Some(all), "pdf", None) => std::borrow::Cow::Borrowed(&**all),
_ if r.whole_document() && item.artboard.is_some() => std::borrow::Cow::Owned(board_document(item)),
_ => std::borrow::Cow::Borrowed(&*item.doc),
}
}
/// The document a native, `.ai` or EPS row writes for `item`'s artboard: that artboard alone, with
/// its background color and the art on it, as Save's separateArtboards writes it (#3868).
fn board_document(item: &Item) -> Document {
let mut d = single_artboard(&item.doc, item.region, &item.name);
if let (Some(a), Some(from)) = (d.artboards.first_mut(), item.doc.artboards.get(item.artboard.unwrap_or(0))) {
a.color = from.color;
}
super::save::keep_art_on(&mut d, item.region);
d
}
/// Every chosen artboard (asset, layer, selected object) in every format row, one file each (a PDF
/// holds its artboard alone), or with `fullDocument` one file per row (a PDF of every artboard,
/// else the bounds of all art). Items that share a name get `-2`, `-3`… instead of overwriting, and
@@ -1177,6 +1199,23 @@ pub(crate) fn export(s: &mut Session, p: &Value, asked: &Value) -> Result<Value>
super::check_images_in(C, r.format.id, &item.doc, base, &r.options_for(item.region, item.artboard)?)?;
}
}
// The native document the files of the other rows carry, each document looked through once.
if crate::file_access::current().is_some() {
let mut looked: HashSet<(usize, bool, Option<usize>)> = HashSet::new();
for r in rows.iter().filter(|r| !matches!(r.format.id, "svg" | "svgz")) {
// A single-file PDF carries the first item's document alone, as the writer writes it.
let carried = items.iter().enumerate().filter(|(index, _)| !(single.is_some() && r.format.id == "pdf" && *index > 0));
for (_, item) in carried.filter(|(_, i)| names_scripts(i, r, single.as_deref())) {
let all = item.every_artboard.is_some() && r.format.id == "pdf" && single.is_none();
let board = item.artboard.filter(|_| !all && r.whole_document());
if looked.insert((Arc::as_ptr(&item.doc) as usize, all, board))
&& crate::cmd::links::names_hidden_file(&carried_document(item, r, single.as_deref()), base)
{
return Err(bad(C, super::access::IMAGE_OUTSIDE));
}
}
}
}
// Appearance of Black › Printing / Exporting for RGB raster rows.
// Include Artboard Fill off: the encoders leave the background colors out.
let fill = if o.include_artboard_fill == Some(false) { json!({ "includeArtboardFill": false }) } else { json!({}) };
@@ -1318,8 +1357,9 @@ fn encode_and_write(export: ScreenExport, writer: &mut dyn FnMut(&str, &[u8]) ->
}
Ok(bytes)
};
// A whole-document copy of an artboard, for the formats that write documents to edit.
let mut board_docs: std::collections::HashMap<usize, Arc<Document>> = std::collections::HashMap::new();
// A whole-document copy of an artboard of an item's document, for the formats that write
// documents to edit.
let mut board_docs: std::collections::HashMap<(usize, usize), Arc<Document>> = std::collections::HashMap::new();
let mut files = 0u64;
// One step per item and row, the files a name collision skips included.
let steps = (items.len() * rows.len()) as u64;
@@ -1358,19 +1398,7 @@ fn encode_and_write(export: ScreenExport, writer: &mut dyn FnMut(&str, &[u8]) ->
write(pdf_doc.unwrap_or(all), "pdf", &options)?
} else if r.whole_document() && item.artboard.is_some() {
let b = item.artboard.unwrap_or(0);
// That artboard alone, as Save's separateArtboards writes it: its art, not the others' (#3868).
let d = board_docs
.entry(b)
.or_insert_with(|| {
let mut d = single_artboard(&item.doc, item.region, &item.name);
// It keeps its background color.
if let (Some(a), Some(from)) = (d.artboards.first_mut(), item.doc.artboards.get(b)) {
a.color = from.color;
}
super::save::keep_art_on(&mut d, item.region);
Arc::new(d)
})
.clone();
let d = board_docs.entry((Arc::as_ptr(&item.doc) as usize, b)).or_insert_with(|| Arc::new(board_document(item))).clone();
let mut options = r.options_for(item.region, None)?;
// An EPS page is the artboard, not its art's bounds: an artboard without art still writes.
if r.format.id == "eps" {
+1 -7
View File
@@ -183,13 +183,7 @@ pub(super) fn lost_artboards_warning(doc: &Document, p: &Value, label: &str) ->
/// The native document Preserve Editing embeds: `doc`, without an Export for Screens `folder`
/// outside the read roots of the request being served (the open document keeps it).
fn native_attachment(doc: &Document) -> Vec<u8> {
let settings = super::screens::leave_out_unreadable_settings_folder(doc.export_settings.clone());
if settings.len() == doc.export_settings.len() {
return vectorcraft_format::save(doc, false);
}
let mut kept = doc.clone();
kept.export_settings = settings;
vectorcraft_format::save(&kept, false)
vectorcraft_format::save(&super::access::with_readable_settings_folder(doc), false)
}
/// Encode `doc` as SVG (or gzipped, SVGZ): one file per chosen artboard, with the images they
+13
View File
@@ -492,6 +492,19 @@ fn library_open_filters_list_library_formats_first() {
}
}
/// Other Library…'s Swatch Libraries filter lists the `.ai` and `.eps` documents whose swatches load
/// as a library, and it is the only filter of that label.
#[test]
fn the_swatch_library_filter_lists_ai_and_eps_files() {
let filters: Vec<_> = library_open_filters("Swatch libraries", crate::cmd::swatchlib::LIBRARY_PICK_EXTS).collect();
for ext in ["ai", "ait", "eps", "epsf", "ase", "gpl", "acb", "vcswatches"] {
assert!(filters[0].1.contains(&ext), "{ext}: {:?}", filters[0]);
}
assert_eq!(filters.iter().filter(|f| f.0 == "Swatch libraries").count(), 1, "{filters:?}");
// File › Open still opens a `.ai` as a document, not as a swatch library.
assert!(!crate::cmd::swatchlib::LIBRARY_EXTS.contains(&"ai") && !opens_as_other("ai"));
}
/// The extensions usage texts list for export: one per writable format, each picking that format
/// (`.png` picks PNG; PNG-8 is asked for by `format`).
#[test]
@@ -413,6 +413,114 @@ fn a_swatch_library_in_a_ai_file_without_layers_loads_its_palette() {
assert!(matches!(sky, Some(vectorcraft_color::Paint::Gradient(_))), "{sky:?}");
}
/// A `.ai` swatch library (a palette and no layers) holding White, the gradient Sky and, in the
/// color group Textures, the swatch Tiles of the 4 pt pattern Dots, whose square is painted with
/// `square` (a color operator), a color the palette doesn't list.
fn textures_library(square: &str) -> Vec<u8> {
let dots = format!("%AI3_BeginPattern: (Dots)\n(Dots) 0 0 4 4\n%_{square}\n%_1 1 m\n%_3 1 L\n%_3 3 L\n%_1 3 L\n%_f\nE\n%AI3_EndPattern\n");
let gradient =
"%AI5_BeginGradient: (Sky)\n(Sky) 0 2 Bd\n[\n%_0 0 0 0 1 1 1 2 1 6 50 0 Bs\n%_0 0 0 1 0 0 0 2 0.5 6 50 100 Bs\nBD\n%AI5_EndGradient\n";
let palette = "%AI5_BeginPalette\n0 0 Pb\n0 0 0 0 1 1 1 Xa\n(White)\nPc\nBb\n2 (Sky) 0 0 0 1 1 0 0 1 0 0 1 Bg\n0 BB\n(Sky)\nPc\n\
1 (Textures) 1 Pg\n(Dots) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n(Tiles)\nPc\nPB\n%AI5_EndPalette\n";
let data = ai::editing_data(200.0, 100.0, &format!("{dots}{gradient}{palette}"));
ai::ai(&compressed(data.as_bytes()), "1 0 0 rg 10 50 30 40 re f")
}
/// `swatch.library.load` of `file` named `name` → its library id.
fn load_library(s: &mut Session, name: &str, file: &[u8]) -> Value {
let p = json!({"dataBase64": vectorcraft_format::base64_encode(file), "name": name});
s.execute("swatch.library.load", &p).unwrap()["library"].clone()
}
/// Other Library… on a `.ai` swatch library lists its colors, gradients and pattern swatches in its
/// order and color groups, and adding the pattern swatch makes a pattern swatch with the pattern's
/// tile and art in the document, in the library's color group, not the pattern's colors.
#[test]
fn a_swatch_library_in_a_ai_file_lists_and_adds_its_pattern_swatches() {
let mut s = Session::new();
let id = load_library(&mut s, "textures.ai", &textures_library("0 0 0 1 k"));
let lib = s.execute("swatch.library.get", &json!({"library": id})).unwrap();
let kinds: Vec<(&str, &str, Option<&str>)> =
lib["swatches"].as_array().unwrap().iter().map(|w| (w["name"].as_str().unwrap(), w["kind"].as_str().unwrap(), w["group"].as_str())).collect();
assert_eq!(kinds, [("White", "color", None), ("Sky", "gradient", None), ("Tiles", "pattern", Some("Textures"))], "{lib}");
assert_eq!(lib["swatches"][2]["pattern"], json!("Dots"), "{lib}");
// The library panel draws the pattern from the file it came from; a copy of the swatch isn't its own.
let (_, library) = crate::cmd::swatchlib::library(&s, id.as_str().unwrap()).unwrap();
let tiles = library.iter().find(|w| w.name == "Tiles").unwrap();
assert!(crate::cmd::swatchlib::pattern_source(&s, tiles).is_some_and(|d| d.pattern("Dots").is_some()));
assert!(crate::cmd::swatchlib::pattern_source(&s, &tiles.clone()).is_none());
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
let r = s.execute("swatch.library.add", &json!({"library": id, "names": ["Textures"]})).unwrap();
assert_eq!(r["added"], json!(["Tiles"]), "{r}");
let doc = &s.doc().unwrap().doc;
let dots = doc.pattern("Dots").expect("the pattern comes with its swatch");
assert_eq!((dots.tile.width(), dots.tile.height()), (4.0, 4.0));
assert_eq!(dots.art.len(), 1, "{:?}", dots.art);
let textures = doc.swatch_groups.iter().find(|g| g.name == "Textures").expect("the color group comes too");
let tiles: Vec<_> = textures.swatches.iter().map(|w| (w.name.as_str(), &w.paint)).collect();
assert!(matches!(tiles[..], [("Tiles", vectorcraft_color::Paint::Pattern { pattern, .. })] if pattern == "Dots"), "{tiles:?}");
// Added again, the swatch the document has is used.
let again = s.execute("swatch.library.add", &json!({"library": id, "names": ["Tiles"]})).unwrap();
assert_eq!((again["added"].clone(), again["existing"].clone()), (json!([]), json!(["Tiles"])), "{again}");
}
/// A pattern swatch of a `.ai` library whose pattern paints with a color the library doesn't list
/// still comes in with that color in its art.
#[test]
fn a_pattern_from_a_ai_library_keeps_a_color_the_library_lacks() {
let mut s = Session::new();
let id = load_library(&mut s, "textures.ai", &textures_library("0 0.5 1 0 k"));
let lib = s.execute("swatch.library.get", &json!({"library": id})).unwrap();
let names: Vec<&str> = lib["swatches"].as_array().unwrap().iter().map(|w| w["name"].as_str().unwrap()).collect();
assert_eq!(names, ["White", "Sky", "Tiles"], "the pattern's color isn't listed: {lib}");
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
s.execute("swatch.library.add", &json!({"library": id, "names": ["Tiles"]})).unwrap();
let doc = &s.doc().unwrap().doc;
let art = &doc.pattern("Dots").unwrap().art;
let fill = art.first().and_then(|n| n.appearance.fill()).map(|f| f.paint.color());
assert_eq!(fill, Some(Some(vectorcraft_color::Color::cmyk(0.0, 0.5, 1.0, 0.0))), "{art:?}");
// Copy to User Defined would write a .vcswatches file, which can't hold the pattern swatch: it is
// refused, writes nothing and leaves the library loaded.
let dir = std::env::temp_dir().join(format!("vc-pattern-copy-{}", std::process::id()));
s.swatch_libraries.set_user_dir(Some(dir.to_string_lossy().to_string()));
let e = s.execute("swatch.library.copyToUser", &json!({"library": id})).unwrap_err().to_string();
assert!(e.contains("`textures` has pattern swatches"), "{e}");
assert!(!dir.exists() || std::fs::read_dir(&dir).unwrap().next().is_none(), "nothing written");
assert!(s.execute("swatch.library.get", &json!({"library": id})).is_ok());
std::fs::remove_dir_all(&dir).ok();
}
/// A `.ai` file without a palette of its own, and a document with no swatches, are refused as
/// swatch libraries with a message, not listed as the default swatches or as an empty library. A
/// damaged `.ai` is refused with the reader's error, and none of them is listed. A library file
/// with no swatches loads as an empty library.
#[test]
fn swatch_library_documents_without_swatches_or_damaged_are_refused() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
s.edit("Clear", |d, _| {
d.swatches.clear();
d.swatch_groups.clear();
Ok(())
})
.unwrap();
let b64 = s.execute("document.serialize", &json!({})).unwrap()["dataBase64"].as_str().unwrap().to_string();
let e = s.execute("swatch.library.load", &json!({"dataBase64": b64, "name": "Bare.vectorcraft"})).unwrap_err().to_string();
assert!(e.contains("`Bare.vectorcraft` has no swatches of its own"), "{e}");
let data = ai::editing_data(200.0, 100.0, &ai::layer("Art", &format!("0 0 0 1 k\n{}f\n", ai::rect(10.0, 50.0, 40.0, 90.0))));
let p = json!({"dataBase64": vectorcraft_format::base64_encode(&ai::ai(&compressed(data.as_bytes()), "1 0 0 rg 10 50 30 40 re f")), "name": "art.ai"});
let e = s.execute("swatch.library.load", &p).unwrap_err().to_string();
assert!(e.contains("`art.ai` has no swatches of its own"), "{e}");
let damaged = json!({"data": "%PDF-1.4\n%damaged\n", "name": "damaged.ai"});
assert!(s.execute("swatch.library.load", &damaged).is_err());
let list = s.execute("swatch.library.list", &json!({})).unwrap();
assert!(list["libraries"].as_array().unwrap().iter().all(|l| l["category"] != "loaded"), "{list}");
// A library file without swatches still loads, as an empty library.
let r = s.execute("swatch.library.load", &json!({"data": "GIMP Palette\nName: Empty\n#\n", "name": "Empty.gpl"})).unwrap();
assert_eq!(r["count"], json!(0), "{r}");
}
/// Other Library… on a `.ai` graphic style library (art styles, their list and no layers) gives the
/// library the styles of its list, in the list's order, not the default styles; the file opens with
/// them too.
@@ -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.
@@ -1461,3 +1461,25 @@ fn an_export_preset_adds_no_notes() {
let r = export(&mut s, json!({"exportPreset": "Mixed"}));
assert!(unused(&r).is_empty(), "{r}");
}
/// Assets, layers and selected objects each write a native, `.ai` or EPS file of their own art:
/// every piece's file holds its own artboard, named after it, not the first piece's.
#[test]
fn each_piece_writes_its_own_native_document() {
let mut s = session(1);
s.execute("shape.ellipse", &json!({"x": 2, "y": 2, "width": 10, "height": 10})).unwrap();
let ids: Vec<u64> = s.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|n| n.id.0).collect();
let mut assets = vec![];
for (id, name) in ids.iter().zip(["Square", "Circle"]) {
assets.push(s.execute("assets.add", &json!({"ids": [id], "name": name})).unwrap()["assets"][0].as_u64().unwrap());
}
let r = export(&mut s, json!({"assets": assets, "formats": [{"format": "vectorcraft"}, {"format": "eps"}]}));
let written = files(&r);
assert_eq!(written.len(), 4, "{r}");
for (name, bytes) in written {
let native = if name.ends_with(".eps") { vectorcraft_eps::native(&bytes).expect("native document") } else { bytes };
let doc = vectorcraft_format::load(&native).unwrap();
let board = doc.artboards[0].name.clone();
assert!(name.contains(&board), "{name} holds the artboard {board}");
}
}
+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());
}
}
+6 -1
View File
@@ -769,6 +769,7 @@ fn give_item(a: &AppearanceItem, b: &AppearanceItem, m: &AppearanceItem, n: &mut
arrow_scale,
profile,
brush,
brush_options,
opacity,
blend,
visible,
@@ -781,7 +782,11 @@ fn give_item(a: &AppearanceItem, b: &AppearanceItem, m: &AppearanceItem, n: &mut
bearing: _,
rotation: _,
} = m;
give_fields!(a, b, n: paint, width, cap, join, miter_limit, align, dash, start_arrow, end_arrow, arrow_scale, profile, brush, opacity, blend, visible, effects, arrow_align, overprint, gradient_mode);
give_fields!(a, b, n: paint, width, cap, join, miter_limit, align, dash, start_arrow, end_arrow, arrow_scale, profile, brush, brush_options, opacity, blend, visible, effects, arrow_align, overprint, gradient_mode);
// A stroke's own brush settings go with the brush they set: a new brush takes the model's.
if a.brush != b.brush {
n.brush_options = brush_options.clone();
}
}
_ => {}
}
+2 -1
View File
@@ -37,7 +37,8 @@ use axis::{nice_axis, tick_values};
#[cfg(test)]
use columns::{fill_totals, total_text};
pub use commands::specs;
pub(crate) use data::{apply_csv, parse_csv};
pub use data::{MAX_GRAPH_DATA_FILE, graph_cell_text, graph_data_from_grid, graph_data_text, graph_grid_from_text};
pub(crate) use data::{apply_csv, graph_csv_from_file, parse_csv};
#[cfg(test)]
use data::{fmt_value, to_csv};
pub use edit::{GraphTypeSubject, graph_type_subject};
+101
View File
@@ -91,6 +91,102 @@ pub(super) fn to_csv(g: &GraphSpec) -> String {
g.to_csv()
}
// ---------- graph data files ----------
/// The largest graph data file that Graph Data's Import Data and Import Data Sets' `%` columns
/// read, 1 MB (1,048,576 bytes).
pub const MAX_GRAPH_DATA_FILE: usize = 1 << 20;
/// A graph data sheet's size: a row of labels over a graph's categories, a column of labels
/// before its series; a cell's longest text.
const SHEET_ROWS: usize = vectorcraft_doc::MAX_GRAPH_CATEGORIES + 1;
const SHEET_COLS: usize = vectorcraft_doc::MAX_GRAPH_SERIES + 1;
const SHEET_CELL: usize = 256;
/// A graph data file's bytes as text: UTF-16 with its byte-order mark (spreadsheets' "Unicode
/// Text"), else UTF-16 without one when the bytes hold NUL bytes and Import Data Sets' rule gives
/// them a byte order ([`crate::cmd::utf16_order_without_mark`]), else UTF-8 with or without one.
/// UTF-16 is read as it is after a byte-order mark: an odd last byte is left out, and an unpaired
/// surrogate reads as U+FFFD.
pub fn graph_data_text(bytes: &[u8]) -> String {
let utf16 = |rest: &[u8], le: bool| {
let units: Vec<u16> = rest.as_chunks::<2>().0.iter().map(|p| if le { u16::from_le_bytes(*p) } else { u16::from_be_bytes(*p) }).collect();
String::from_utf16_lossy(&units)
};
match bytes {
[0xFF, 0xFE, rest @ ..] => utf16(rest, true),
[0xFE, 0xFF, rest @ ..] => utf16(rest, false),
[0xEF, 0xBB, 0xBF, rest @ ..] => String::from_utf8_lossy(rest).into_owned(),
_ => match bytes.contains(&0).then(|| crate::cmd::utf16_order_without_mark(bytes)).flatten() {
Some(le) => utf16(bytes, le),
None => String::from_utf8_lossy(bytes).into_owned(),
},
}
}
/// A graph data sheet cell's text: one line (tabs and line breaks become spaces), at most 256
/// characters.
pub fn graph_cell_text(s: &str) -> String {
s.chars().map(|c| if matches!(c, '\t' | '\r' | '\n') { ' ' } else { c }).take(SHEET_CELL).collect()
}
/// Text from a file or the clipboard as graph data sheet cells: tab-separated when any line holds
/// a tab, else comma-separated (decided once, so a label with a comma in a tab-separated file
/// stays whole), at most a graph's rows and columns.
pub fn graph_grid_from_text(text: &str) -> Vec<Vec<String>> {
let sep = if text.contains('\t') { '\t' } else { ',' };
text.lines().take(SHEET_ROWS).map(|l| l.trim_end_matches('\r').split(sep).take(SHEET_COLS).map(|c| graph_cell_text(c.trim())).collect()).collect()
}
/// A graph data sheet as `graph.setData` takes it: the first row holds the series labels, the
/// first column the category labels (none when all are blank), and the other cells the values (a
/// blank cell, or text that isn't a number, has none), without the empty rows and columns past
/// the data.
pub fn graph_data_from_grid(grid: &[Vec<String>]) -> Value {
let cell = |r: usize, c: usize| grid.get(r).and_then(|row| row.get(c)).cloned().unwrap_or_default();
let filled = |s: &String| !s.trim().is_empty();
// At most a graph's rows and columns, as a file gives (`graph_grid_from_text`): a grid sent by
// automation is any size, and the values are their product.
let grid = &grid[..grid.len().min(SHEET_ROWS)];
let rows = grid.iter().rposition(|r| r.iter().take(SHEET_COLS).any(filled)).map_or(1, |i| i + 1).max(1);
let cols = grid.iter().take(rows).filter_map(|r| r.iter().take(SHEET_COLS).rposition(filled)).max().map_or(1, |i| i + 1).max(1);
let label = |s: &str| {
let s = s.trim();
// A label typed in straight quotes (as the CSV form takes a number as a label) is the text inside.
s.strip_prefix('"').and_then(|t| t.strip_suffix('"')).unwrap_or(s).to_string()
};
// Series labels up to the last one given (none when all are blank).
let mut series: Vec<String> = (1..cols).map(|c| label(&cell(0, c))).collect();
while series.last().is_some_and(String::is_empty) {
series.pop();
}
let mut categories: Vec<String> = (1..rows).map(|r| label(&cell(r, 0))).collect();
if categories.iter().all(String::is_empty) {
categories.clear();
}
let values: Vec<Vec<Value>> = (1..rows)
.map(|r| {
(1..cols)
.map(|c| {
let t = cell(r, c);
t.trim().parse::<f64>().ok().filter(|v| v.is_finite() && !t.trim().starts_with('"')).map_or(Value::Null, |v| json!(v))
})
.collect()
})
.collect();
json!({ "series": series, "categories": categories, "rows": values })
}
/// The graph value (the CSV form [`apply_csv`] reads) of a graph data file's bytes, read as Graph
/// Data's Import Data reads the file into its sheet and Apply sends the sheet: so applying the
/// value gives a graph the data that Import Data and Apply give it.
pub(crate) fn graph_csv_from_file(bytes: &[u8]) -> Result<String> {
let data = graph_data_from_grid(&graph_grid_from_text(&graph_data_text(bytes)));
let mut spec = GraphSpec::default();
apply_data(&mut spec, &data, "dataset.import")?;
Ok(spec.to_csv())
}
/// Apply CSV graph data to the graph root `id` and rebuild its art (Variables data merge), as `graph.setData` with
/// `csv` does. Data the graph already holds leaves the graph as it is.
pub(crate) fn apply_csv(d: &mut Document, id: NodeId, csv: &str) -> Result<()> {
@@ -149,6 +245,11 @@ pub(super) fn apply_data(g: &mut GraphSpec, p: &Value, cmd: &str) -> Result<bool
if let Some(csv) = csv {
let (s, c, r) = parse_csv(csv);
g.series = s;
// Series labels up to the last one given, as Graph Data's sheet keeps them
// ([`graph_data_from_grid`]): `to_csv` writes a blank label for each series without one.
while g.series.last().is_some_and(String::is_empty) {
g.series.pop();
}
g.categories = c;
g.set_cells(r);
changed = true;
+22 -13
View File
@@ -47,18 +47,22 @@ fn insert_inline(s: &mut Session, p: &Value) -> Result<Value> {
};
let len = edit::runs_len(&t.runs);
let from_tool = editing == Some(id);
let (a, b) = match p.get("at") {
None | Some(Value::Null) if from_tool => {
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"));
(x.min(y), x.max(y))
}
None | Some(Value::Null) => (len, len),
Some(v) => {
let at = v.as_u64().ok_or_else(|| bad(C, "`at` must be a byte offset"))?.min(len as u64) as usize;
(at, at)
}
// Where the graphic goes in text `len` bytes long.
let range = |len: usize| -> Result<(usize, usize)> {
Ok(match p.get("at") {
None | Some(Value::Null) if from_tool => {
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"));
(x.min(y), x.max(y))
}
None | Some(Value::Null) => (len, len),
Some(v) => {
let at = v.as_u64().ok_or_else(|| bad(C, "`at` must be a byte offset"))?.min(len as u64) as usize;
(at, at)
}
})
};
let (mut a, mut b) = range(len)?;
let symbol = match str_param(p, "symbol") {
Some(n) if doc.symbols.iter().any(|s| s.name == n) => n.to_string(),
Some(n) => return Err(bad(C, format!("no symbol named `{n}`"))),
@@ -76,11 +80,16 @@ fn insert_inline(s: &mut Session, p: &Value) -> Result<Value> {
None | Some(Value::Null) => 0.0,
Some(v) => v.as_f64().filter(|k| k.is_finite() && k.abs() <= 1e5).ok_or_else(|| bad(C, "`shift` must be a number of points"))?,
};
// A typing session ends first: the insertion is a step of its own.
// A typing session ends first: the insertion is a step of its own. Typing that Real-time
// Drawing off left unapplied is applied first, and the caret is read in the typed text.
let typing = tool.get("typing").and_then(Value::as_bool) == Some(true);
if typing && from_tool {
s.set_tool_option("commitTyping", &Value::Bool(true));
s.commit_interaction()?;
super::settle_interaction(s)?;
let NodeKind::Text(t) = &s.doc()?.doc.node(id).ok_or(EngineError::NoNode(id))?.kind else {
return Err(bad(C, format!("node {} is not text", id.0)));
};
(a, b) = range(edit::runs_len(&t.runs))?;
}
let caret = s.edit("Insert Inline Symbol", |d, _| {
let mut art = InlineArt { scale, baseline_shift: shift, ..InlineArt::new(symbol.clone()) };
+195 -8
View File
@@ -36,7 +36,7 @@ use vectorcraft_doc::{
use vectorcraft_geom::{Affine, FillRule, PathData, Rect, shapes};
use super::fileio::{self, RasterImage, absolute_path, file_created, file_stamp, read_file, write_file};
use super::{CommandSpec, EngineError, Result, Session, bad, bool_or, cmd, has_doc, ids_param, object_param, str_param, switch_or};
use super::{CommandSpec, EngineError, Result, Session, bad, bool_or, cmd, has_doc, ids_param, object_param, str_param, switch_or, text_param};
pub fn specs() -> Vec<CommandSpec> {
vec![
@@ -108,7 +108,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Unembed",
[],
None,
"{id?: an embedded image (default: the one selected), path?} write the image's pixels to the file at path (PNG, JPEG, GIF or WebP as stored, other images as PNG; a path ending in .png/.jpg/.jpeg/.gif/.webp/.tif/.tiff/.bmp converts them) and link the image to it, keeping its bounds. One undo step → {id, path}; no path → {name, dataBase64} (nothing changes: there is no file to link to)",
"{id?: an embedded image (default: the one selected), path?, ids?: [image ids] (instead of id; one id is the same as id), folder?} write the image's pixels to the file at path (PNG, JPEG, GIF or WebP as stored, other images as PNG; a path ending in .png/.jpg/.jpeg/.gif/.webp/.tif/.tiff/.bmp converts them) and link the image to it, keeping its bounds. One undo step → {id, path}; no path → {name, dataBase64} (nothing changes: there is no file to link to). With folder: write each embedded image of ids or id (default: the selected embedded images) to a new file in folder, as stored (as PNG when that format is not one of VectorCraft's raster file formats), named after the image (characters a file name can't hold become _; Image when nothing is left), with Name 2 … Name 99 when the name is taken; a file already there is never replaced. Linked images among ids are left as they are. Each image links to its file and keeps its bounds. One undo step (undo does not remove the files); when a file can't be written, the files this call wrote are removed and nothing changes → {unembedded: [{id, path}], skipped: [ids of linked images]}; id with ids, path with folder, and ids of more or fewer than one image without folder are errors",
has_doc,
unembed
),
@@ -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.
@@ -2686,11 +2686,35 @@ fn convert_image(bytes: &[u8], ext: &str) -> std::result::Result<Vec<u8>, String
craft_image_codecs::encode(&raw, format, &craft_image_codecs::EncodeOptions::default()).map_err(|e| e.to_string())
}
/// The extension of the format embedded image `blob` is stored in (PNG for one Unembed doesn't
/// name).
fn stored_extension(blob: &vectorcraft_doc::ImageBlob) -> &'static str {
fileio::FORMATS.iter().find(|f| f.raster && f.mime == blob.mime).map_or("png", |f| f.extensions.first().copied().unwrap_or("png"))
}
/// The bytes of embedded image `blob` in the format of extension `ext`: its own bytes when it is
/// stored in that format, else converted.
fn unembed_bytes(blob: &vectorcraft_doc::ImageBlob, ext: &str) -> std::result::Result<Vec<u8>, String> {
let same = fileio::format(ext).is_some_and(|f| f.mime == blob.mime);
if same { Ok(blob.bytes.to_vec()) } else { convert_image(&blob.bytes, ext) }
}
fn unembed(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "links.unembed";
let given = |k: &str| p.get(k).is_some_and(|v| !v.is_null());
// `id` with `ids`, and `path` with `folder`, are refused, in a replayed step too.
super::params::check_exclusive_keys(C, p)?;
let ids = ids_param(p, "ids", C)?;
if given("folder") || ids.as_ref().is_some_and(|ids| ids.len() != 1) {
return unembed_to_folder(s, p, ids);
}
let st = s.doc()?;
let doc = with_brush_art(&st.doc);
let id = image_param(st, &doc, p, C)?;
// `ids` of one image is `id`.
let id = match ids.as_deref() {
Some(&[id]) => id,
_ => image_param(st, &doc, p, C)?,
};
let n = stored(&doc, id).ok_or(crate::EngineError::NoNode(id))?;
let im = image_of(&doc, id).ok_or_else(|| bad(C, format!("object {} is not an image", id.0)))?;
if im.link.is_some() {
@@ -2698,15 +2722,14 @@ fn unembed(s: &mut Session, p: &Value) -> Result<Value> {
}
let blob = st.doc.images.get(&im.key).filter(|b| !b.is_proxy()).ok_or_else(|| bad(C, "the image's pixels aren't in the document"))?;
// As stored (PNG, JPEG, GIF, WebP), unless the path names another format.
let stored = fileio::FORMATS.iter().find(|f| f.raster && f.mime == blob.mime).map_or("png", |f| f.extensions.first().copied().unwrap_or("png"));
let stored = stored_extension(blob);
let path = str_param(p, "path");
let ext = match path.map(fileio::extension) {
Some(e) if UNEMBED_EXTS.contains(&e.as_str()) => e,
Some(e) if !e.is_empty() => return Err(bad(C, format!("can't write .{e} images: use .png, .jpg, .gif, .webp, .tif or .bmp"))),
_ => stored.to_string(),
};
let same = fileio::format(&ext).is_some_and(|f| f.mime == blob.mime);
let bytes = if same { blob.bytes.to_vec() } else { convert_image(&blob.bytes, &ext).map_err(|e| bad(C, e))? };
let bytes = unembed_bytes(blob, &ext).map_err(|e| bad(C, e))?;
let Some(path) = path else {
let name = n.display_name();
let stem = Path::new(&name).file_stem().map_or_else(|| name.clone(), |s| s.to_string_lossy().into_owned());
@@ -2722,6 +2745,146 @@ fn unembed(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({ "id": id.0, "path": path }))
}
/// `links.unembed {ids?, folder}`: each embedded image of `ids` (`id` as `ids` of one; default: the
/// selected embedded images) written to a new file in `folder` as stored (as PNG when that format is not one of
/// VectorCraft's raster file formats) and linked to it, in one undo step. Linked images are skipped. When any image fails, the files written before it
/// are removed and the document does not change.
fn unembed_to_folder(s: &mut Session, p: &Value, ids: Option<Vec<NodeId>>) -> Result<Value> {
const C: &str = "links.unembed";
let folder = text_param(p, "folder", C)?.filter(|f| !f.is_empty()).ok_or_else(|| bad(C, "missing `folder`"))?;
let ids = match ids {
Some(ids) => Some(ids),
None => object_param(p, "id", C)?.map(|id| vec![id]),
};
let st = s.doc()?;
let doc = with_brush_art(&st.doc);
let ids = ids.unwrap_or_else(|| selected_images(st, |im| im.link.is_none()));
let mut seen = BTreeSet::new();
if !ids.iter().all(|id| seen.insert(id.0)) {
return Err(bad(C, "`ids` names an object twice"));
}
let (mut embedded, mut skipped) = (vec![], vec![]);
for &id in &ids {
let n = stored(&doc, id).ok_or(crate::EngineError::NoNode(id))?;
let im = image_of(&doc, id).ok_or_else(|| bad(C, format!("object {} is not an image", id.0)))?;
if im.link.is_some() {
skipped.push(id);
continue;
}
let blob = st.doc.images.get(&im.key).filter(|b| !b.is_proxy()).ok_or_else(|| bad(C, "the image's pixels aren't in the document"))?;
embedded.push((id, n.display_name(), blob));
}
match (embedded.is_empty(), skipped.first()) {
(true, Some(id)) => return Err(bad(C, format!("image {} is linked already", id.0))),
(true, None) => return Err(bad(C, "select an image")),
_ => {}
}
let dir = absolute_path(folder);
writable_folder(&dir)?;
// One image at a time: its bytes are read before its file is written, so pixels that can't be
// read leave no file behind.
let mut written: Vec<String> = vec![];
let mut reads = Vec::with_capacity(embedded.len());
let wrote = embedded.iter().try_for_each(|(id, name, blob)| {
vectorcraft_doc::cancel::check()?;
let ext = stored_extension(blob);
let bytes = unembed_bytes(blob, ext).map_err(|e| bad(C, e))?;
let name = format!("{}.{ext}", unembed_stem(name));
let img = linked_image(&bytes, Some(Path::new(&dir).join(&name).to_string_lossy().as_ref()))?;
let path = write_numbered(&dir, &name, &bytes)?;
written.push(path.clone());
reads.push((*id, (link_info(&path, &bytes), img)));
Ok(())
});
let remove_written = |written: &[String]| {
for path in written {
let _ = std::fs::remove_file(path);
}
};
if let Err(e) = wrote {
remove_written(&written);
return Err(e);
}
drop(doc);
let done: Vec<Value> = reads.iter().map(|(id, (l, _))| json!({ "id": id.0, "path": l.path })).collect();
let edited = s.edit("Unembed", |d, _| {
editing_brush_art(d, |d| reads.into_iter().try_for_each(|(id, read)| install(d, &[id], read, Some(Preserve::Bounds), None)))
});
if let Err(e) = edited {
remove_written(&written);
return Err(e);
}
Ok(json!({ "unembedded": done, "skipped": ids_json(&skipped) }))
}
/// The name Unembed gives image `name`'s file in a folder, before its extension: the name without
/// a folder part or extension, each character a file name can't hold on some system
/// (`/ \ : * ? " < > |` and control characters) as `_`, without leading spaces or trailing dots and
/// spaces, at most 150 bytes long, and `Image` when nothing is left. A name Windows keeps for a
/// device (`CON`, `NUL`, `COM1` …) gets `_` after it.
fn unembed_stem(name: &str) -> String {
let base = name.rsplit(['/', '\\']).next().unwrap_or_default();
let stem = match base.rfind('.') {
Some(i) if i > 0 => &base[..i],
_ => base,
};
let mut clean = String::new();
for c in stem.chars().map(|c| if c.is_control() || "/\\:*?\"<>|".contains(c) { '_' } else { c }) {
if clean.len() + c.len_utf8() > 150 {
break;
}
clean.push(c);
}
let clean = clean.trim_start_matches(' ').trim_end_matches(['.', ' ']);
if clean.is_empty() {
return "Image".to_string();
}
let device = clean.split('.').next().unwrap_or_default().trim_end().to_ascii_uppercase();
let numbered = |prefix: &str| device.strip_prefix(prefix).is_some_and(|d| d.len() == 1 && matches!(d.as_bytes().first(), Some(b'1'..=b'9')));
if matches!(device.as_str(), "CON" | "PRN" | "AUX" | "NUL") || numbered("COM") || numbered("LPT") {
format!("{clean}_")
} else {
clean.to_string()
}
}
/// Folder `path` may take Unembed's files: inside the automation write roots, and a folder.
#[cfg(not(target_arch = "wasm32"))]
fn writable_folder(path: &str) -> Result<()> {
crate::file_access::check_write(path).map_err(EngineError::Other)?;
if !std::fs::metadata(path).is_ok_and(|m| m.is_dir()) {
return Err(EngineError::Other(format!("{path} is not a folder")));
}
Ok(())
}
/// Write `bytes` to a new file named `name` in folder `dir`, never replacing a file there: `Name.ext`,
/// else `Name 2.ext` up to `Name 99.ext`, as [`fileio::copy_new`] names them → its path.
#[cfg(not(target_arch = "wasm32"))]
fn write_numbered(dir: &str, name: &str, bytes: &[u8]) -> Result<String> {
use std::io::Write as _;
let create = |to: &Path| {
crate::file_access::check_write(&to.to_string_lossy()).map_err(|e| std::io::Error::new(std::io::ErrorKind::PermissionDenied, e))?;
vectorcraft_format::write_new_with(to, |f| f.write_all(bytes))
};
match fileio::copy_new(Path::new(name), Path::new(dir), create, |_, _| false) {
Ok(Some(fileio::Placed::Copied(to) | fileio::Placed::Kept(to))) => Ok(to.to_string_lossy().into_owned()),
Ok(None) => Err(EngineError::Other(format!("every numbered name for {name} is taken in that folder"))),
Err(e) => Err(EngineError::Other(format!("{dir}: {e}"))),
}
}
/// The web has no folders to write to.
#[cfg(target_arch = "wasm32")]
fn writable_folder(_: &str) -> Result<()> {
Err(EngineError::Other("no file system here".into()))
}
#[cfg(target_arch = "wasm32")]
fn write_numbered(_: &str, _: &str, _: &[u8]) -> Result<String> {
Err(EngineError::Other("no file system here".into()))
}
/// Placement Options as `{preserve, align, clip}`.
fn placement_json(o: PlacementOptions) -> Value {
json!({ "preserve": o.preserve.id(), "align": o.align.id(), "clip": o.clip })
@@ -2901,4 +3064,28 @@ mod tests {
let c = read();
assert!(!Arc::ptr_eq(&a.blob.bytes, &c.blob.bytes));
}
#[test]
fn unembed_names_a_file_after_the_image_with_only_characters_a_file_name_holds() {
for (name, stem) in [
("photo.png", "photo"),
("Image", "Image"),
("../../etc/passwd", "passwd"),
("C:\\art\\logo.tif", "logo"),
("a:b*c?d\"e<f>g|h", "a_b_c_d_e_f_g_h"),
("tab\there", "tab_here"),
(" name. .png", "name"),
("..", "Image"),
("", "Image"),
(".hidden", ".hidden"),
("CON.png", "CON_"),
("lpt1", "lpt1_"),
("COM0", "COM0"),
("console", "console"),
] {
assert_eq!(unembed_stem(name), stem, "{name:?}");
}
let long = unembed_stem(&"é".repeat(200));
assert!(long.len() <= 150 && long.chars().all(|c| c == 'é'), "{}", long.len());
}
}
+79 -6
View File
@@ -1,6 +1,6 @@
//! Object menu long tail: Lock/Hide All Artwork Above & Other Layers, Transform Each, Reset
//! Bounding Box, Rasterize, Crop Image, Mask (an image), Create Trim Marks, Convert to Shape and
//! Artboards → Convert / Rearrange. (Live blends are in `live.rs`.)
//! Bounding Box, Rotate Bounding Box, Rasterize, Crop Image, Mask (an image), Create Trim Marks,
//! Convert to Shape and Artboards → Convert / Rearrange. (Live blends are in `live.rs`.)
use std::collections::{BTreeMap, BTreeSet, HashSet};
use std::sync::Arc;
@@ -15,8 +15,8 @@ use vectorcraft_render::encode::{RasterExportOptions, RasterFormat};
use super::edit::{duplicate_in, selected_roots, selected_roots_to_transform};
use super::{
CommandSpec, EngineError, Result, Session, bad, check_numbers, check_switches, cmd, f64_or, fileio, find_command, has_doc, has_selected_member,
has_selection, switch_or,
CommandSpec, EngineError, Result, Session, bad, check_numbers, check_switches, cmd, f64_or, f64_req, fileio, find_command, has_doc,
has_selected_member, has_selection, switch_or,
};
/// Session-level (not saved) state owned by the menu commands.
@@ -110,6 +110,15 @@ pub fn specs() -> Vec<CommandSpec> {
has_selection,
reset_bounding_box
),
cmd!(
"object.rotateBoundingBox",
"Rotate Bounding Box…",
["Object", "Transform"],
None,
"{angle: degrees (counter-clockwise), absolute?: bool (true: turn the box to angle; default false: turn it by angle from the angle the selected objects share, 0 when theirs differ)} turn the bounding box of the selected objects to one angle without moving their art; the objects inside them (the children of groups, compound paths, clip groups, blends, envelopes, repeats and intertwines, and the art of linked opacity masks) turn with them and keep their angle relative to them; a path of a compound path selected on its own turns only its own box; one undo step, none when every box is already at the angle; object.resetBoundingBox squares the boxes again; a missing or non-numeric angle is an error → {angle: the new angle of the boxes, in (-180, 180], changed: objects whose box turned, the objects inside the selected ones included}",
has_selection,
rotate_bounding_box
),
cmd!(
"object.rasterize",
"Rasterize…",
@@ -225,9 +234,10 @@ pub(crate) fn squash(s: &mut Session, from: usize, label: &str) {
// ---------- Reset Bounding Box ----------
/// Squares each selected object and every object inside it: the children of groups, compound paths,
/// clip groups, blends, envelopes, repeats and intertwines, and the art of linked opacity masks.
/// clip groups, blends, envelopes, repeats and intertwines, and the art of linked opacity masks. A
/// path of a compound path selected on its own is squared alone, as the transforms move it alone.
fn reset_bounding_box(s: &mut Session, _: &Value) -> Result<Value> {
let ids = selected_roots(s)?;
let ids = selected_roots_to_transform(s)?;
let d = &s.doc()?.doc;
let mut changed = 0;
let squared: Vec<(NodeId, Node)> = ids
@@ -251,6 +261,69 @@ fn reset_bounding_box(s: &mut Session, _: &Value) -> Result<Value> {
Ok(json!({ "changed": changed }))
}
// ---------- Rotate Bounding Box ----------
/// Turns the bounding box of the selected objects to one angle without moving their art: by `angle`
/// from the angle they share (0 when it differs), or to `angle` with `absolute`. Each object's box
/// turns by what takes it there, and so do the boxes of the objects inside it (the children of
/// groups and the art of linked opacity masks), which keep their angle relative to it.
fn rotate_bounding_box(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "object.rotateBoundingBox";
// A JSON number is always finite.
let angle = f64_req(p, "angle", C)?;
let absolute = switch_or(p, "absolute", false, C)?;
// The same objects the transforms move: a path of a compound path selected on its own turns
// its own box. Layers are left out, as they have no box.
let owners = selected_roots_to_transform(s)?;
let d = &s.doc()?.doc;
let start = if absolute { 0.0 } else { d.bbox_angle(&owners) };
// An angle within the tolerance of 0 is stored as 0, as `Node::turn_boxes` stores it.
let target = match vectorcraft_geom::normalize_deg(start + angle) {
a if a.abs() <= BOX_EPS_DEG => 0.0,
a => a,
};
let mut changed = 0;
let turned: Vec<(NodeId, Node)> = owners
.iter()
.filter_map(|id| {
let n = d.node(*id)?;
let by = vectorcraft_geom::normalize_deg(target - n.bbox_angle);
(by.abs() > BOX_EPS_DEG).then(|| {
let mut c = n.clone();
c.turn_boxes(by);
// The selected object's box is set to the target itself, so repeated turns add no
// rounding error to it.
c.bbox_angle = target;
changed += boxes(&c);
(*id, c)
})
})
.collect();
if !turned.is_empty() {
s.edit("Rotate Bounding Box", |d, _| {
for (id, n) in turned {
if let Some(slot) = d.node_mut(id) {
*slot = n;
}
}
Ok(())
})?;
}
Ok(json!({ "angle": target, "changed": changed }))
}
/// Angles closer than this (degrees) are the same, as `vectorcraft_doc::orient` compares them.
const BOX_EPS_DEG: f64 = 1e-6;
/// The number of objects in `n`'s subtree whose box [`Node::turn_boxes`] turns: `n`, its children
/// and the art of a linked opacity mask, layers left out.
fn boxes(n: &Node) -> usize {
let own = usize::from(!n.is_layer());
let children: usize = n.children().into_iter().flatten().map(|c| boxes(c)).sum();
let mask = n.extras().mask.as_ref().filter(|m| m.linked).map_or(0, |m| boxes(&m.art));
own + children + mask
}
/// A copy of `n` with the angle of every object in its subtree set to 0, or `None` when no box in
/// it stands at an angle, and the number of objects squared. The subtree takes in children and the
/// art of linked opacity masks (an unlinked mask's art turns on its own); layers have no box. Only
+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
),
+22
View File
@@ -137,6 +137,24 @@ fn check_carried_scripts(name: &str, bytes: &[u8], path: &str) -> Result<()> {
}
}
/// The error for a linked file the package would copy with an Export for Screens folder outside
/// the read roots in the native document it is or carries.
const FOLDER_OUTSIDE: &str = "a linked file's export folder is outside the read roots";
/// Under read roots, the linked file `name` (`bytes`, as the package writes it) is copied only when
/// the native document it is or carries ([`carried_document`]) keeps no Export for Screens folder
/// outside them: a file copied as it is, a PDF, `.ai` or EPS file or a native document not
/// rewritten, would name it. The error names no file or folder.
fn check_carried_folder(name: &str, bytes: &[u8]) -> Result<()> {
if crate::file_access::current().is_none() {
return Ok(());
}
match carried_document(name, bytes) {
Some(carried) if matches!(super::fileio::with_readable_settings_folder(&carried), std::borrow::Cow::Owned(_)) => Err(bad(C, FOLDER_OUTSIDE)),
_ => Ok(()),
}
}
/// The fonts of the type on `pages` of the PDF or `.ai` file `name` (`bytes`, found at `path`);
/// none for other files.
fn page_fonts(name: &str, bytes: &[u8], path: &str, pages: &PlacedPages) -> BTreeSet<super::fonts::UsedFont> {
@@ -363,6 +381,7 @@ impl<'a> Collector<'a> {
options.profiles = saved.profiles;
options.compress = compressed;
options.include_linked = include_linked;
let nested = super::fileio::with_readable_settings_folder(&nested);
match vectorcraft_format::save_with(&nested, &options) {
Ok(rewritten) => bytes = rewritten,
Err(e) => self.warn(
@@ -381,6 +400,7 @@ impl<'a> Collector<'a> {
}
}
}
check_carried_folder(&file.name, &bytes)?;
let copy = Copied { name: destination_file.clone(), size: Some(bytes.len() as u64), hash: Some(hash_bytes(&bytes)) };
self.copies.insert(found_path.to_string(), copy.clone());
local.insert(file.path.clone(), copy);
@@ -520,7 +540,9 @@ fn prepare(s: &mut Session, p: &Value) -> Result<Package> {
}
let root = folder.map(|f| Path::new(f).join(&name));
let info = if o.report { Some(super::docinfo::report(s, false)?) } else { None };
// The package's document leaves out an Export for Screens folder outside the read roots.
let doc = s.doc()?.doc.clone();
let doc = if let std::borrow::Cow::Owned(kept) = super::fileio::with_readable_settings_folder(&doc) { std::sync::Arc::new(kept) } else { doc };
let links_from = s.doc()?.links_from.clone().unwrap_or_else(|| doc_path.clone());
Ok(Package { o, doc_path, links_from, stem, name, root, info, doc })
}
+106 -4
View File
@@ -67,14 +67,14 @@ pub fn specs() -> Vec<CommandSpec> {
"Character / Paragraph",
[],
None,
"{ids?|id?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg counter-clockwise (0: upright), underline?, strikethrough?, allCaps?, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), antiAlias?: \"none\"|\"sharp\"|\"crisp\"|\"strong\" (Character panel › Anti-aliasing Method, how the type's edges are drawn as pixels; it sets each targeted type object, with or without a range; each frame of a thread keeps its own method; graph labels keep it for every label of their kind when the graph is drawn again; new type: \"sharp\"), leftIndent?, rightIndent?, firstLineIndent?, spaceBefore?, spaceAfter?: pt (±1296), list?: \"none\"|\"bullet\"|\"number\", bullet?: \"none\"|\"dot\"|\"dash\"|\"circle\"|\"square\", number?: \"none\"|\"arabic\"|\"upperLetters\"|\"lowerLetters\"|\"upperRoman\"|\"lowerRoman\"|\"twoDigits\"|\"threeDigits\", listAlign?: \"left\"|\"right\", listLevel?: 1..9 (Paragraph panel › Bullets and Numbered List: each paragraph of a list starts with its marker, drawn in the font, size and color of the paragraph's first character, and its text starts at the next tab stop after the marker, the left indent counting as a stop; a bulleted list's marker is its bullet, and a numbered list's is the paragraph's number and a period: 1, 2, 3; A to Z, then AA, BB; a to z, then aa, bb; I, II, III; i, ii, iii; 01 to 99, then 100; 001 to 999, then 1000; letters and roman numerals past 3999 in Arabic digits; the numbers count the story's numbered paragraphs, its threaded frames included, from 1 after a paragraph in no list, and an empty or bulleted paragraph is not counted; list \"bullet\" keeps a list's bullet, else a dot, and list \"number\" keeps a numbered list's style, else arabic; without list, a number style makes a numbered list and a bullet makes a bulleted one; \"none\" in any of the three turns the list off; a paragraph that joins a list with left and first-line indents of 0 gets 18 and -18 unless the call sets an indent; a horizontal right-to-left list paragraph has its indents mirrored, measured from the right; listAlign \"right\" (Bullets and Numbering…'s Alignment) puts the marker against the text, and \"left\" (the default) puts it at the first line's start, the text starting at the same place with either; it sets the paragraphs that are in a list or that the call puts in one, and a list keeps it when it changes between bullets and numbers; listLevel (Tab and Shift+Tab at the start of a list paragraph, Bullets and Numbering…'s Level) is a whole number from 1 to 9 that sets the paragraphs in a list or that the call puts in one, a list keeping it when it changes between bullets and numbers, and a list turned on without listLevel starting at level 1; each level past the first sets the paragraph 18 pt further in than its left indent, and each level counts its own numbers: a list paragraph with text sets the counts of the levels deeper than its own back to 0, so a deeper numbered paragraph after it counts from 1, and a paragraph back at a shallower level goes on with that level's count), hyphenate?: bool, wordsLongerThan?: letters 1..25 (5), afterFirst?, beforeLast?: letters 1..15 (3), hyphenLimit?: lines 0..25 (0: no limit), hyphenationZone?: pt 0..1296 (0; Single-line Composer only), hyphenateCapitalized?: bool (true) (Paragraph panel menu › Hyphenation…: only words longer than wordsLongerThan break, keeping afterFirst letters before the hyphen and beforeLast after it; at most hyphenLimit lines in a row end with a hyphen; a line whose text already ends within hyphenationZone of its right edge breaks before the next word instead of hyphenating it; the counts are rounded, and every value is clamped to its range), wordSpacing?: % 0..1000 (80, 100, 133), letterSpacing?: % of a word space -100..500 (0, 0, 0), glyphScaling?: % 50..200 (100, 100, 100): each [min, desired, max] or {min?, desired?, max?} (Paragraph panel menu › Justification…: Desired applies to every line, Minimum and Maximum bound what justified lines may use; values are clamped to their range, and Minimum ≤ Desired ≤ Maximum must hold afterwards or nothing changes), autoLeading?: % of the size 0..500 (120; the leading of characters whose leading is Auto), singleWordJustification?: \"fullJustify\"|\"alignLeft\"|\"alignCenter\"|\"alignRight\" (a justified line holding one word), mojikumi?: \"none\"|\"yakumonoHankaku\"|\"gyomatsuYakumonoHankaku\"|\"gyomatsuYakumonoZenkaku\"|\"yakumonoZenkaku\"|\"lineEndHalf\" (Mojikumi Set: Japanese punctuation spacing), kinsoku?: \"none\"|\"hard\"|\"soft\" (Kinsoku Set: Soft lets 々, ー and small kana start a line), kinsokuType?: \"pushInFirst\"|\"pushOutFirst\"|\"pushOutOnly\" (Paragraph panel menu › Kinsoku Shori Type: how area type keeps those characters off a line's ends; pushInFirst sets them on the line when its gaps next to CJK characters can close up enough, by at most a tent Line truncated
"{ids?|id?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg counter-clockwise (0: upright), underline?, strikethrough?, allCaps?, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), antiAlias?: \"none\"|\"sharp\"|\"crisp\"|\"strong\" (Character panel › Anti-aliasing Method, how the type's edges are drawn as pixels; it sets each targeted type object, with or without a range; each frame of a thread keeps its own method; graph labels keep it for every label of their kind when the graph is drawn again; new type: \"sharp\"), leftIndent?, rightIndent?, firstLineIndent?, spaceBefore?, spaceAfter?: pt (±1296), list?: \"none\"|\"bullet\"|\"number\", bullet?: \"none\"|\"dot\"|\"dash\"|\"circle\"|\"square\", number?: \"none\"|\"arabic\"|\"upperLetters\"|\"lowerLetters\"|\"upperRoman\"|\"lowerRoman\"|\"twoDigits\"|\"threeDigits\", listAlign?: \"left\"|\"right\", listLevel?: 1..9 (Paragraph panel › Bullets and Numbered List: each paragraph of a list starts with its marker, drawn in the font, size and color of the paragraph's first character, and its text starts at the next tab stop after the marker, the left indent counting as a stop; a bulleted list's marker is its bullet, and a numbered list's is the paragraph's number and a period: 1, 2, 3; A to Z, then AA, BB; a to z, then aa, bb; I, II, III; i, ii, iii; 01 to 99, then 100; 001 to 999, then 1000; letters and roman numerals past 3999 in Arabic digits; the numbers count the story's numbered paragraphs, its threaded frames included, from 1 after a paragraph in no list, and an empty or bulleted paragraph is not counted; list \"bullet\" keeps a list's bullet, else a dot, and list \"number\" keeps a numbered list's style, else arabic; without list, a number style makes a numbered list and a bullet makes a bulleted one; \"none\" in any of the three turns the list off; a paragraph that joins a list with left and first-line indents of 0 gets 18 and -18 unless the call sets an indent; a horizontal right-to-left list paragraph has its indents mirrored, measured from the right; listAlign \"right\" (Bullets and Numbering…'s Alignment) puts the marker against the text, and \"left\" (the default) puts it at the first line's start, the text starting at the same place with either; it sets the paragraphs that are in a list or that the call puts in one, and a list keeps it when it changes between bullets and numbers; listLevel (Tab and Shift+Tab at the start of a list paragraph, Bullets and Numbering…'s Level) is a whole number from 1 to 9 that sets the paragraphs in a list or that the call puts in one, a list keeping it when it changes between bullets and numbers, and a list turned on without listLevel starting at level 1; each level past the first sets the paragraph 18 pt further in than its left indent, and each level counts its own numbers: a list paragraph with text sets the counts of the levels deeper than its own back to 0, so a deeper numbered paragraph after it counts from 1, and a paragraph back at a shallower level goes on with that level's count), startNumber?: 1..999999999, restartNumbering?: bool (Bullets and Numbering…'s Start At, VectorCraft's own: startNumber gives the first numbered paragraph the call touches, the first that holds text or else the first, taking the type objects in the order of `ids` and passing over a threaded frame's first paragraph when it continues from the frame before, that number, and the numbered paragraphs after it at its level count on from it, through the story's threaded frames; restartNumbering true gives it 1, and false takes the number away from every paragraph the call touches but such a continued first paragraph, which then count on from the paragraph before; giving both fails the call, and when the call touches no numbered paragraph nothing changes; a paragraph made with Return does not take the number, a paragraph made bulleted keeps none, and a paragraph style made from the paragraph does not keep it, nor does a graph label when the graph is drawn again), hyphenate?: bool, wordsLongerThan?: letters 1..25 (5), afterFirst?, beforeLast?: letters 1..15 (3), hyphenLimit?: lines 0..25 (0: no limit), hyphenationZone?: pt 0..1296 (0; Single-line Composer only), hyphenateCapitalized?: bool (true) (Paragraph panel menu › Hyphenation…: only words longer than wordsLongerThan break, keeping afterFirst letters before the hyphen and beforeLast after it; at most hyphenLimit lines in a row end with a hyphen; a line whose text already ends within hyphenationZone of its right edge breaks before the next word instead of hyphenating it; the counts are rounded, and every value is clamped to its range), wordSpacing?: % 0..1000 (80, 100, 133), letterSpacing?: % of a word space -100..500 (0, 0, 0), glyphScaling?: % 50..200 (100, 100, 100): each [min, desired, max] or {min?, desired?, max?} (Paragraph panel menu › Justification Line truncated
has_doc,
set_format
),
cmd!(
"text.convertListToText",
"Convert to Text",
[],
["Type"],
None,
"{ids?|id?, start?: byte, end?: byte} (Type › Bullets and Numbering › Convert to Text: the paragraphs of the selected type, or of `ids`, or those a start/end range touches; after Select All in a frame of threaded text, without `ids`, `id` or a range, every paragraph of every frame of the story, locked and hidden frames included) the marker of each list paragraph becomes characters of its text: the bullet, or the number and its period as the paragraph showed it, then a tab, at the start of the paragraph in the marker's font, size and color; the list is turned off. When the marker's tab went to the left indent, the paragraph gets a left-aligned tab stop without a leader there, in place of any stop there, which keeps the text after the tab where it started; when it went to a tab stop and a stop there or past it has a leader or is not left-aligned, or a right, center or decimal stop lies between the marker and that place, the paragraph gets a left-aligned stop without a leader where the marker's tab ended, in place of any stop there and of those right, center and decimal stops before it (past the left indent only in a paragraph with no tab of its own). In threaded type the numbers are those counted through the story's frames, and a paragraph that continues into a later frame is converted where its text starts. An empty list paragraph has no marker and only leaves the list. A paragraph with no direction set gets the direction it ran in when the characters would change it (a letter or roman numeral before right-to-left text). With the Every-line Composer, a paragraph with a tab is broken line by line, so a converted paragraph can break its lines at other places. While the Type tool edits, its typing ends first and its anchor and caret move past the characters inserted at or before them (a whole story that Select All selected stays selected when the call converts all of it); in threaded type, when the caret's character moved to another frame, the tool edits that frame, which becomes the selection when it was not selected. One undo step → {ids, converted: paragraphs, inserted: [{id, at: byte before the change, length: bytes}]}",
has_doc,
@@ -482,6 +482,66 @@ fn list_level_param(p: &Value, cmd: &str) -> Result<Option<u8>> {
}
}
/// The number a numbered paragraph is given, from `startNumber` (a whole number from 1 to
/// [`vectorcraft_doc::text::MAX_LIST_START`]) or `restartNumbering` (true: 1): `Some(Some(n))`,
/// or `Some(None)` for `restartNumbering` false, which numbers paragraphs on from the one before.
/// None without either; giving both is an error.
fn list_start_param(p: &Value, cmd: &str) -> Result<Option<Option<u32>>> {
let (key, other) = ("startNumber", "restartNumbering");
let start = p.get(key).filter(|v| !v.is_null());
let restart = p.get(other).filter(|v| !v.is_null());
if start.is_some() && restart.is_some() {
return Err(bad(cmd, format!("give `{key}` or `{other}`, not both")));
}
if let Some(v) = start {
let (min, max) = (1, vectorcraft_doc::text::MAX_LIST_START);
return match v.as_f64() {
Some(x) if x.fract() == 0.0 && (f64::from(min)..=f64::from(max)).contains(&x) => Ok(Some(Some(x as u32))),
Some(x) => Err(bad(cmd, format!("`{key}` must be a whole number between {min} and {max} (got {x})"))),
None => Err(bad(cmd, format!("`{key}` must be a whole number"))),
};
}
// `check_switches` has already refused a value that is not true or false.
Ok(restart.and_then(Value::as_bool).map(|on| on.then_some(1)))
}
/// Take the number its list gives a paragraph away from paragraphs `paras` of `t` (indices;
/// None: every paragraph), so they count on from the paragraph before. A first paragraph that
/// continues from the frame before ([`TextObject::first_para_continues`]) keeps its number: its
/// item begins in that frame.
///
/// [`TextObject::first_para_continues`]: vectorcraft_doc::text::TextObject::first_para_continues
fn clear_list_start(t: &mut vectorcraft_doc::text::TextObject, paras: Option<std::ops::Range<usize>>) {
let mut paras = paras.unwrap_or(0..t.paragraph_count());
if paras.start == 0 && t.first_para_continues {
paras.start = 1;
}
if paras.is_empty() {
return;
}
t.edit_paras(Some(paras), |p| {
if let Some(l) = p.list.as_mut() {
l.start = None;
}
});
}
/// Among paragraphs `paras` of `t` (indices; None: every paragraph), the first numbered paragraph
/// that holds text and the first numbered paragraph: where a number from [`list_start_param`] can go.
/// A first paragraph that continues from the frame before ([`TextObject::first_para_continues`]) is
/// skipped: its item begins in that frame.
///
/// [`TextObject::first_para_continues`]: vectorcraft_doc::text::TextObject::first_para_continues
fn list_start_candidates(t: &vectorcraft_doc::text::TextObject, paras: Option<std::ops::Range<usize>>) -> (Option<usize>, Option<usize>) {
let paras = paras.unwrap_or(0..t.paragraph_count());
let text = t.plain_text();
let pieces: Vec<&str> = text.split('\n').collect();
let mut numbered = paras.filter(|&i| !(i == 0 && t.first_para_continues) && t.para_at(i).list.is_some_and(|l| l.number.is_some())).peekable();
let first = numbered.peek().copied();
let with_text = numbered.find(|&i| pieces.get(i).is_some_and(|s| !s.is_empty()));
(with_text, first)
}
/// Set the Warichu and Warichu Settings of `st` that are given: Warichu on or off, Lines, Line Gap
/// (in the type's own units), Scale and Alignment.
fn set_warichu(
@@ -523,6 +583,7 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> {
"koreanLineBreakAnywhere",
"bunriKinshi",
"kurikaeshiMojiShori",
"restartNumbering",
],
C,
)?;
@@ -582,6 +643,8 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> {
"number",
"listAlign",
"listLevel",
"startNumber",
"restartNumbering",
"hyphenate",
"wordsLongerThan",
"afterFirst",
@@ -762,6 +825,8 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> {
.map(|a| if a == "right" { vectorcraft_doc::text::ListAlign::Right } else { vectorcraft_doc::text::ListAlign::Left });
// …and `listLevel` the level of every list paragraph, 1 to 9.
let list_level = list_level_param(p, C)?;
// …and `startNumber` or `restartNumbering` the number of the first numbered paragraph.
let list_start = list_start_param(p, C)?;
let indents_given = num("leftIndent").is_some() || num("firstLineIndent").is_some();
let spacing = |k: &str| spacing_param(p, k, C);
let (word_spacing, letter_spacing, glyph_scaling) = (spacing("wordSpacing")?, spacing("letterSpacing")?, spacing("glyphScaling")?);
@@ -885,9 +950,11 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> {
// A numbered list for list "number", or without `list` for a number style.
let numbered = list == Some("number") || (list.is_none() && number.is_some());
// The list's other settings (the marker's alignment) stay as they were.
// A paragraph made bulleted keeps no number of its own.
para.list = on.then(|| vectorcraft_doc::text::ParaList {
bullet: bullet.flatten().or(had.map(|l| l.bullet)).unwrap_or_default(),
number: numbered.then(|| number.flatten().or(had.and_then(|l| l.number)).unwrap_or_default()),
start: had.and_then(|l| l.start).filter(|_| numbered),
..had.unwrap_or_default()
});
// A paragraph that joins a list with no left or first-line indent gets a
@@ -912,6 +979,9 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> {
let d = &mut doc;
// The paragraph change, for the graph labels to keep.
let mut para_change = None;
// Where the number `startNumber` or `restartNumbering` gives goes: the first numbered
// paragraph with text the call touches, through every target, else the first numbered one.
let (mut start_with_text, mut start_first) = (None, None);
let out_of_order_error = |name: &str| bad(C, format!("`{name}`: Minimum must not exceed Desired, nor Desired Maximum"));
for id in &ids {
let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) else { continue };
@@ -1021,14 +1091,36 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> {
para.composer = v;
}
};
t.edit_paras(span, |para| paras(para, &mut out_of_order));
t.edit_paras(span.clone(), |para| paras(para, &mut out_of_order));
if let Some(name) = out_of_order {
return Err(out_of_order_error(name));
}
match list_start {
Some(None) => clear_list_start(t, span),
Some(Some(_)) if start_with_text.is_none() => {
let (with_text, first) = list_start_candidates(t, span);
start_with_text = with_text.map(|i| (*id, i));
start_first = start_first.or(first.map(|i| (*id, i)));
}
_ => {}
}
super::typecmd::refresh_bounds(t);
changed |= *t != before;
para_change = Some(paras);
}
if let Some(Some(n)) = list_start
&& let Some((id, i)) = start_with_text.or(start_first)
&& let Some(NodeKind::Text(t)) = d.node_mut(id).map(|node| &mut node.kind)
{
let before = t.clone();
t.edit_paras(Some(i..i + 1), |p| {
if let Some(l) = p.list.as_mut() {
l.start = Some(n);
}
});
super::typecmd::refresh_bounds(t);
changed |= *t != before;
}
// Graph labels keep a change made to all of their text through the graph being drawn again.
if range.is_none() {
let shift = num("baselineShift").map(|v| v.clamp(-1296.0, 1296.0));
@@ -1276,7 +1368,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 +1406,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)) };
+38 -22
View File
@@ -258,11 +258,16 @@ pub fn check_keys(id: &str, doc: &'static str, params: &Value) -> Result<()> {
/// Parameters a command takes instead of one another: (command, key, other key). Giving both,
/// neither null, is a parameter error ([`check_exclusive_keys`]).
const EXCLUSIVE_KEYS: &[(&str, &str, &str)] = &[("addon.pathtools.cornerSet", "items", "ids"), ("addon.pathtools.cornerRemove", "items", "ids")];
const EXCLUSIVE_KEYS: &[(&str, &str, &str)] = &[
("addon.pathtools.cornerSet", "items", "ids"),
("addon.pathtools.cornerRemove", "items", "ids"),
("links.unembed", "id", "ids"),
("links.unembed", "path", "folder"),
];
/// `params` of command `id` give at most one of each pair in [`EXCLUSIVE_KEYS`], or the parameter
/// error naming the pair.
fn check_exclusive_keys(id: &str, params: &Value) -> Result<()> {
pub(crate) fn check_exclusive_keys(id: &str, params: &Value) -> Result<()> {
let given = |key: &str| params.get(key).filter(|v| !v.is_null());
for (_, key, other) in EXCLUSIVE_KEYS.iter().filter(|(c, ..)| *c == id) {
if given(key).is_some() && given(other).is_some() {
@@ -649,6 +654,7 @@ pub const UNCHECKED: &[&str] = &[
"transparency.setOpacityMask",
"transparency.unlinkOpacityMask",
"type.pathOptions",
"webExport.optimizeToFileSize",
"webExport.presets.save",
"webExport.settings",
];
@@ -663,18 +669,28 @@ fn pdf_option_tree() -> Value {
tree
}
/// The parameter error of command `id` for `key`, a key with the objects it is in (`marks.ofset`),
/// when a key those objects take is near it: `near`, written the same way (`marks.offset`). Each
/// is one value of the message, so a catalog can match the message and translate it.
fn misspelled(id: &str, key: &str, near: &str) -> crate::EngineError {
bad(id, format!("unknown parameter `{key}`; did you mean `{near}`?"))
}
/// `given`, the object at `within` (`marks.`), has only keys of `schema`, the objects inside it too.
fn check_option_tree(id: &str, within: &str, given: &serde_json::Map<String, Value>, schema: &serde_json::Map<String, Value>) -> Result<()> {
for (key, value) in given {
match (schema.get(key), value) {
(None, _) => {
let keys: Vec<&str> = schema.keys().map(String::as_str).collect();
let why = match nearest(key, &keys) {
Some(near) => format!("did you mean `{within}{near}`?"),
None => format!("`{}` takes: {}", within.trim_end_matches('.'), keys.join(", ")),
};
let key = shown_key(key);
return Err(bad(id, format!("unknown parameter `{within}{key}`; {why}")));
let near = nearest(key, &keys);
let key = format!("{within}{}", shown_key(key));
return Err(match near {
Some(near) => misspelled(id, &key, &format!("{within}{near}")),
None => {
let (object, keys) = (within.trim_end_matches('.'), keys.join(", "));
bad(id, format!("unknown parameter `{key}`; `{object}` takes: {keys}"))
}
});
}
(Some(Value::Object(inner)), Value::Object(value)) => check_option_tree(id, &format!("{within}{key}."), value, inner)?,
_ => {}
@@ -691,14 +707,11 @@ fn check_option_keys(id: &str, within: &str, given: &serde_json::Map<String, Val
for (key, value) in given {
if !keys.contains(&key.as_str()) {
let near = nearest(key, keys);
let key = shown_key(key);
return Err(bad(
id,
match near {
Some(near) => format!("unknown parameter `{within}{key}`; did you mean `{within}{near}`?"),
None => format!("unknown parameter `{within}{key}`; {why_not}"),
},
));
let key = format!("{within}{}", shown_key(key));
return Err(match near {
Some(near) => misspelled(id, &key, &format!("{within}{near}")),
None => bad(id, format!("unknown parameter `{key}`; {why_not}")),
});
}
if let (Some(Value::Object(schema)), Value::Object(value)) = (trees.get(key), value) {
check_option_tree(id, &format!("{within}{key}."), value, schema)?;
@@ -797,12 +810,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)?;
+61 -8
View File
@@ -27,7 +27,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Unite",
["Window", "Pathfinder"],
None,
"{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids}",
"{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids, warning?: when a selected object is or holds a line or another open path that encloses no area once closed, and so does not change the result's shape (when such a path leaves the result empty, as in Intersect, the error says so)}",
has_selection,
|s, p| run_pf(s, p, PathfinderOp::Unite)
),
@@ -36,7 +36,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Minus Front",
["Window", "Pathfinder"],
None,
"{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids}",
"{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids, warning?: when a selected object is or holds a line or another open path that encloses no area once closed, and so does not change the result's shape (when such a path leaves the result empty, as in Intersect, the error says so)}",
has_selection,
|s, p| run_pf(s, p, PathfinderOp::MinusFront)
),
@@ -45,7 +45,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Intersect",
["Window", "Pathfinder"],
None,
"{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids}",
"{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids, warning?: when a selected object is or holds a line or another open path that encloses no area once closed, and so does not change the result's shape (when such a path leaves the result empty, as in Intersect, the error says so)}",
has_selection,
|s, p| run_pf(s, p, PathfinderOp::Intersect)
),
@@ -54,7 +54,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Exclude",
["Window", "Pathfinder"],
None,
"{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids}",
"{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids, warning?: when a selected object is or holds a line or another open path that encloses no area once closed, and so does not change the result's shape (when such a path leaves the result empty, as in Intersect, the error says so)}",
has_selection,
|s, p| run_pf(s, p, PathfinderOp::Exclude)
),
@@ -108,7 +108,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Minus Back",
["Window", "Pathfinder"],
None,
"{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids}",
"{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids, warning?: when a selected object is or holds a line or another open path that encloses no area once closed, and so does not change the result's shape (when such a path leaves the result empty, as in Intersect, the error says so)}",
has_selection,
|s, p| run_pf(s, p, PathfinderOp::MinusBack)
),
@@ -285,6 +285,37 @@ impl Style {
}
}
/// The Shape Mode commands' warning, which the status bar shows, when a selected object is or holds
/// a line or another open path that encloses no area once closed, and so does not change the result's
/// shape (the result still takes its paint from the frontmost object, as without the warning).
pub const SHAPE_MODE_OPEN_PATH_NO_AREA: &str = "a line or other open path that encloses no area does not change the result's shape; to include it, apply Object › Path › Outline Stroke to it first";
/// `path` has an open subpath that encloses no area once closed (a straight line, or an evenodd
/// contour traced twice), by the area its fill rule gives, so a self-crossing path whose signed
/// area is zero (a bow tie) still counts as enclosing area, as Divide measures it.
fn has_open_subpath_without_area(path: &PathData, rule: FillRule) -> bool {
path.subpaths.iter().filter(|sp| !sp.closed).any(|sp| {
// A point or a straight two-anchor line needs no area measurement.
if sp.anchors.len() < 2 || (sp.anchors.len() == 2 && sp.anchors.iter().all(|a| a.h_in == a.p && a.h_out == a.p)) {
return true;
}
let mut closed = sp.clone();
closed.closed = true;
// The signed-area test alone only holds for nonzero: evenodd can fill nothing where the
// signed area is not zero (a contour traced twice).
!(rule == FillRule::NonZero && po::encloses_area(sp)) && po::area(&PathData::single(closed), rule) <= 0.0
})
}
/// The area `path` fills with its open subpaths closed, as the Shape Modes fill it.
fn closed_area(path: &PathData, rule: FillRule) -> f64 {
let mut closed = path.clone();
for sp in &mut closed.subpaths {
sp.closed = true;
}
po::area(&closed, rule)
}
/// All subpaths of a path or compound path node, in document coordinates, with its fill rule.
pub(crate) fn node_path(n: &Node) -> Option<(PathData, FillRule)> {
match &n.kind {
@@ -685,8 +716,9 @@ fn run_pf(s: &mut Session, p: &Value, op: PathfinderOp) -> Result<Value> {
let keeps_hidden = matches!(op, PathfinderOp::Intersect | PathfinderOp::MinusFront | PathfinderOp::MinusBack | PathfinderOp::Crop);
let label = pf_label(op);
let options = pf_options(s, p, &format!("object.pathfinder.{}", pf_id(op)))?;
let ids = s.edit(label, |d, sel| {
let (ids, no_area) = s.edit(label, |d, sel| {
// Build the stack (back → front); names are separate from paint/style identity.
let mut no_area = false;
let mut styles: Vec<Style> = vec![];
let mut shapes: Vec<po::Shape> = vec![];
let mut names: Vec<Option<String>> = vec![];
@@ -759,6 +791,7 @@ fn run_pf(s: &mut Session, p: &Value, op: PathfinderOp) -> Result<Value> {
continue;
};
let top = *top;
no_area = no_area || parts.iter().any(|(_, p, r)| has_open_subpath_without_area(p, *r));
let refs: Vec<(&PathData, FillRule)> = parts.iter().map(|(_, p, r)| (p, *r)).collect();
push(
po::try_unite_all_with(&refs, options.precision).map_err(|e| EngineError::Other(e.to_string()))?,
@@ -771,6 +804,7 @@ fn run_pf(s: &mut Session, p: &Value, op: PathfinderOp) -> Result<Value> {
} else {
for (l, clip) in &lv {
if let Some((p, r)) = node_path(l) {
no_area = no_area || (shape_mode && has_open_subpath_without_area(&p, r));
push(p, r, style_of(l), n.name.clone().or_else(|| l.name.clone()), clip.as_deref(), clip.is_some())?;
}
}
@@ -798,6 +832,21 @@ fn run_pf(s: &mut Session, p: &Value, op: PathfinderOp) -> Result<Value> {
}
}
if results.iter().all(|r| r.path.is_empty()) {
// The lines left the result empty when the other shapes give a result without them, or
// when nothing else is selected. A closed shape without area stays among the others.
let lines_emptied = no_area && {
let kept: Vec<po::Shape> = shapes
.iter()
.filter(|s| closed_area(&s.path, s.rule) > 0.0 || !has_open_subpath_without_area(&s.path, s.rule))
.cloned()
.collect();
kept.is_empty() || po::pathfinder_with(op, &kept, options.precision).iter().any(|r| !r.path.is_empty())
};
if lines_emptied {
return Err(EngineError::Other(format!(
"{label} produced an empty result: a line or other open path encloses no area; to include it, apply Object › Path › Outline Stroke to it first"
)));
}
return Err(EngineError::Other(format!("{label} produced an empty result")));
}
let new_node = if shape_mode {
@@ -833,9 +882,13 @@ fn run_pf(s: &mut Session, p: &Value, op: PathfinderOp) -> Result<Value> {
};
let nid = d.wrap(&roots, |_| new_node)?;
sel.set([nid]);
Ok(vec![nid])
Ok((vec![nid], no_area))
})?;
Ok(ids_json(&ids))
let mut out = ids_json(&ids);
if no_area {
out["warning"] = json!(SHAPE_MODE_OPEN_PATH_NO_AREA);
}
Ok(out)
}
// ---------- Trap ----------
+60 -5
View File
@@ -12,7 +12,7 @@ use vectorcraft_geom::{PathData, Point, Rect, SubPath, shapes};
use super::Result;
use super::clipboard::Clipboard;
use super::clipboard::resources::SwatchChoices;
use super::clipboard::resources::{Imported, SwatchChoices};
use super::swatchlib::LibraryInfo;
/// A built-in pattern library: a stable id, its menu name and the function that adds its patterns.
@@ -87,12 +87,67 @@ pub fn swatch_source(w: &Swatch) -> Option<Arc<Document>> {
/// Add pattern `name` of library `lib` to `d` with the resources its art uses, as pasting art
/// painted with it does: the same pattern there already is used, and a name another pattern or
/// swatch has gets a number → the pattern's name in `d`.
pub(crate) fn import(d: &mut Document, lib: &Document, name: &str) -> Result<String> {
/// swatch has gets a number → the pattern's name in `d`, and the swatches the import added for
/// the pattern's art: (the swatch's name in `lib`, its name in `d`), pattern swatches left out.
/// A global or spot color whose name `d` gives another color comes in under a free name, as Add
/// to Swatches adds such a color, so that the pattern keeps the library's colors.
pub(crate) fn import(d: &mut Document, lib: &Document, name: &str) -> Result<(String, Vec<(String, String)>)> {
let had: std::collections::HashSet<String> = d.swatches_iter().map(|w| w.name.clone()).collect();
let imported = gather(lib, name).import_into(d, &SwatchChoices::add_all(), false)?;
let from = |to: &str| {
let renamed = imported.renamed.iter().find(|r| r["kind"] == "swatch" && r["to"] == to).and_then(|r| r["from"].as_str());
renamed.unwrap_or(to).to_string()
};
let added = d
.swatches_iter()
.filter(|w| !had.contains(&w.name) && !matches!(w.paint, Paint::Pattern { .. }))
.map(|w| (from(&w.name), w.name.clone()))
.collect();
Ok((imported_name(&imported, name), added))
}
/// Pattern `name` of `lib` with the resources its art uses, as an object painted with it is copied.
fn gather(lib: &Document, name: &str) -> Clipboard {
let user = Node::path(NodeId(0), shapes::rectangle(Rect::new(0.0, 0.0, 1.0, 1.0)), Appearance::basic(pattern_paint(name), Paint::None, 0.0));
let imported = Clipboard::gather(lib, vec![user]).import_into(d, &SwatchChoices::default(), false)?;
Clipboard::gather(lib, vec![user])
}
/// The name pattern `name` has in the document `imported` went into.
fn imported_name(imported: &Imported, name: &str) -> String {
let renamed = imported.renamed.iter().find(|r| r["kind"] == "pattern" && r["from"] == name).and_then(|r| r["to"].as_str());
Ok(renamed.unwrap_or(name).to_string())
renamed.unwrap_or(name).to_string()
}
/// The pattern of `d` that [`import`] of pattern `name` of library `lib` would use without adding
/// anything to `d` → its name in `d`. A pattern whose art uses no other resource is compared as
/// [`existing_pattern`] does. One whose art uses other resources, such as a pattern it is painted
/// with, is imported into a copy of `d`, so that those resources are compared too.
pub(crate) fn present_pattern(d: &Document, lib: &Document, name: &str) -> Option<String> {
let gathered = gather(lib, name);
let only_pattern = gathered.patterns.len() == 1
&& gathered.symbols.is_empty()
&& gathered.swatches.is_empty()
&& gathered.graphic_styles.is_empty()
&& gathered.char_styles.is_empty()
&& gathered.para_styles.is_empty()
&& gathered.brushes.is_empty()
&& gathered.images.is_empty();
if only_pattern {
return existing_pattern(d, lib, name);
}
// Importing reuses only a pattern under that name or a numbered copy of it with the same tile
// options and as many art objects; without one, the document is not copied.
let def = lib.pattern(name)?;
let bare = |p: &PatternDef| PatternDef { name: String::new(), art: vec![], ..p.clone() };
let copy = |n: &str| {
n == name || n.strip_prefix(name).and_then(|r| r.strip_prefix(' ')).is_some_and(|r| !r.is_empty() && r.bytes().all(|b| b.is_ascii_digit()))
};
if !d.patterns.iter().any(|p| copy(&p.name) && p.art.len() == def.art.len() && bare(p) == bare(def)) {
return None;
}
let mut probe = d.clone();
let imported = gathered.import_into(&mut probe, &SwatchChoices::add_all(), false).ok()?;
(imported.added == 0).then(|| imported_name(&imported, name))
}
/// The pattern of `d` that is pattern `name` of library `lib`: the same tile options and art under
+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
),
@@ -84,6 +84,8 @@ pub(super) const ALLOWED: &[&str] = &[
"addon.shapes.star",
"addon.type.releasePath",
"addon.type.textTweaker",
"addon.units.convert",
"addon.units.selectionSize",
"appearance.addEffect",
"appearance.addFill",
"appearance.addStroke",
@@ -124,6 +126,7 @@ pub(super) const ALLOWED: &[&str] = &[
"brush.list",
"brush.move",
"brush.new",
"brush.objectOptions",
"brush.options",
"brush.placeArt",
"brush.remove",
@@ -366,6 +369,7 @@ pub(super) const ALLOWED: &[&str] = &[
"object.repeat.release",
"object.resetBoundingBox",
"object.rotate",
"object.rotateBoundingBox",
"object.scale",
"object.setBounds",
"object.setLiveShape",
+2
View File
@@ -368,6 +368,8 @@ pub const PREF_SPECS: &[PrefSpec] = &[
p!("gpuPerformance", "Performance", "GPU Performance", "GPU Performance", bool),
p!("animatedZoom", "Performance", "GPU Performance", "Animated Zoom", bool),
p!("gpuPreference", "Performance", "GPU Performance", "Graphics Processor", choice(GPU_PREFERENCES)),
// Read by the desktop app at startup: the window presents without vsync, capped at 240 fps (#6013).
p!("lowLatencyDrawing", "Performance", "GPU Performance", "Low-Latency Drawing", bool),
p!("historyStates", "Performance", "", "History States", int(5, 1000)),
p!("realTimeDrawing", "Performance", "", "Real-time Drawing and Editing", bool),
p!("renderThreads", "Performance", "", "Render Threads (-1 = Automatic)", int(-1, 64)),
+2 -2
View File
@@ -23,7 +23,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Print Setup",
[],
None,
"{preset?: name ([Default] or a saved print preset, any case: print.presets.list; its settings replace the document's, as choosing it in the Print dialog does), settings?: {copies: 1 (1–999), collate: true, reverse, artboards: all|range|ignore (all the art as one page), range: \"1-3, 5\" (1-based, with artboards: range), skipBlank (leave out artboards with no art that prints), media: letter|legal|tabloid|a3|a4|a5|a6|b4|b5|b4 (jis)|b5 (jis)|b6 (jis)|japanese postcard|japanese double postcard|japanese envelope #3|japanese envelope #4|kaku #2|kaku #3|yonroku-ban|custom (a paper is named by its id or its dialog label, any case and spacing, so `B5 (JIS)` works; b4 and b5 stay the ISO 216 sizes, 250 × 353 and 176 × 250 mm, and the JIS sizes are b4 (jis) 257 × 364 mm, b5 (jis) 182 × 257 mm and b6 (jis) 128 × 182 mm), width, height (custom paper, 72–14400 pt), orientation: portrait|landscape|portraitFlipped|landscapeFlipped, autoRotate: true (turn the paper to each artboard; orientation ignored), transverse (the page a quarter turn on the paper), printLayers: visiblePrintable|visible|all (template layers never print), placement: {origin: topLeft|top|topRight|left|center|right|bottomLeft|bottom|bottomRight (the point of the printed area, the artboard with its bleed and marks, on the same point of the imageable area), x, y (pt, right and down)}, scaling: none|fit|custom|tileFull|tileImageable, scale: {width: 100, height: 100 (1–1000 % with custom and tiling), linked: true (width and height stay equal: give one and the other follows, and turning it on sets the height to the width; a different width and height without linked turn it off, and with linked: true, or linked: null over a linked scale, are an error; a saved scale without linked reads it as false)}, overlap: 0 (pt between tiles), tileRange: \"\" (1-based tiles across then down; empty: all), copiesPerSheet: false (not with tiling: as many copies of each artboard, with its bleed and marks, as fit the imageable area, across then down, not turned; the placement places the grid; an artboard that doesn't fit prints one copy per sheet, with a warning), gutter: 0 (pt between copies, 0–720), margin: 0 (pt the device can't print around the paper: the imageable area is inside it), marks: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25, offset: 6} (as document.exportPdf, at the paper's scale; page information adds the tile and the ink), bleed: {useDocument: true (the document's bleed, document.setup), top, bottom, left, right} (pt), output: {mode: composite|separations (one gray page per ink that prints), emulsion: up|down (down mirrors), image: positive|negative, spotsToProcess, overprintBlack: false (separations: solid 100% K or 100% gray fills, strokes and characters, to within half a percent, overprint in the printed copy, gradients when every stop is (every point of a freeform one); rich, RGB, spot-linked and lighter blacks knock out; composite ignores it), inks: [{name: \"Cyan\"|…|a spot swatch, print: true, frequency (lpi, default 60), angle (screen angle, degrees counter-clockwise as PostScript setscreen takes it; default C 15, M 75, Y 0, K 45, spots 45)}]}, graphics: {autoFlatness: true, flatness: 1 (0.2–100), fonts: none|subset|complete}, color: {intent: perceptual|relativeColorimetric|saturation|absoluteColorimetric, preserveNumbers: true (CMYK colors keep their values), profile: \"\" (the printer profile, an RGB or CMYK one: composite PDF colors are converted to it with the intent, separations separate with a CMYK one; empty: as they are)}, advanced: {printAsBitmap (composite pages print as one image each, at the document's raster effects resolution, or lower for a page larger than 64 Mpx or 32,768 px a side), overprints: preserve|discard|simulate (composite output; preserve writes them to overprint (/OP), simulate prints them as Overprint Preview shows them; separations always keep them), flattenerPreset: \"\" (a flattener preset, built-in or saved: transparency is flattened before printing; empty: it prints live; PostScript defaults to medium)}, tileOrigin: {placed: false, x, y} (where the Print Tiling tool put the pages: print.tiling.set)}} store the print settings with the document, over the ones it has or the preset's (null keeps a value), as one undo step; no settings or preset → {settings} (the current ones, defaults if never set up)",
"{preset?: name ([Default] or a saved print preset, any case: print.presets.list; its settings replace the document's, as choosing it in the Print dialog does), settings?: {copies: 1 (1–999), collate: true, reverse, artboards: all|range|ignore (all the art as one page), range: \"1-3, 5\" (1-based, with artboards: range), skipBlank (leave out artboards with no art that prints), media: letter|legal|tabloid|a3|a4|a5|a6|b4|b5|b4 (jis)|b5 (jis)|b6 (jis)|japanese postcard|japanese double postcard|japanese envelope #3|japanese envelope #4|kaku #2|kaku #3|yonroku-ban|custom (a paper is named by its id or its dialog label, any case and spacing, so `B5 (JIS)` works; b4 and b5 stay the ISO 216 sizes, 250 × 353 and 176 × 250 mm, and the JIS sizes are b4 (jis) 257 × 364 mm, b5 (jis) 182 × 257 mm and b6 (jis) 128 × 182 mm), width, height (custom paper, 72–14400 pt), orientation: portrait|landscape|portraitFlipped|landscapeFlipped, autoRotate: true (turn the paper to each artboard; orientation ignored), transverse (the page a quarter turn on the paper), printLayers: visiblePrintable|visible|all (template layers never print), placement: {origin: topLeft|top|topRight|left|center|right|bottomLeft|bottom|bottomRight (the point of the printed area, the artboard with its bleed and marks, on the same point of the imageable area), x, y (pt, right and down)}, scaling: none|fit|custom|tileFull|tileImageable, scale: {width: 100, height: 100 (1–1000 % with custom and tiling), linked: true (width and height stay equal: give one and the other follows, and turning it on sets the height to the width; a different width and height without linked turn it off, and with linked: true, or linked: null over a linked scale, are an error; a saved scale without linked reads it as false)}, overlap: 0 (pt between tiles), tileRange: \"\" (1-based tiles across then down; empty: all), copiesPerSheet: false (not with tiling: as many copies of each artboard, with its bleed and marks, as fit the imageable area, across then down, not turned; the placement places the grid; an artboard that doesn't fit prints one copy per sheet, with a warning), gutter: 0 (pt between copies, 0–720), margin: 0 (pt the device can't print around the paper: the imageable area is inside it), marks: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25, offset: 6} (as document.exportPdf, at the paper's scale; page information adds the tile and the ink), bleed: {useDocument: true (the document's bleed, document.setup), top, bottom, left, right} (pt), output: {mode: composite|separations (one gray page per ink that prints), emulsion: up|down (down mirrors), image: positive|negative, spotsToProcess, overprintBlack: false (separations: solid 100% K or 100% gray fills, strokes and characters, to within half a percent, overprint in the printed copy, gradients when every stop is (every point of a freeform one); rich, RGB, spot-linked and lighter blacks are not marked, and paints already set to overprint keep it; composite ignores it), inks: [{name: \"Cyan\"|…|a spot swatch, print: true, frequency (lpi, default 60), angle (screen angle, degrees counter-clockwise as PostScript setscreen takes it; default C 15, M 75, Y 0, K 45, spots 45), convertToProcess: false (a spot ink only: it prints on the process plates, with no plate of its own, and its print, frequency and angle are kept for when it prints as a spot ink again; spotsToProcess converts every spot ink whatever it says)}]}, graphics: {autoFlatness: true, flatness: 1 (0.2–100), fonts: none|subset|complete}, color: {intent: perceptual|relativeColorimetric|saturation|absoluteColorimetric, preserveNumbers: true (CMYK colors keep their values), profile: \"\" (the printer profile, an RGB or CMYK one: composite PDF colors are converted to it with the intent, separations separate with a CMYK one; empty: as they are)}, advanced: {printAsBitmap (composite pages print as one image each, at the document's raster effects resolution, or lower for a page larger than 64 Mpx or 32,768 px a side), overprints: preserve|discard|simulate (composite output; preserve writes them to overprint (/OP), simulate prints them as Overprint Preview shows them; separations always keep them), flattenerPreset: \"\" (a flattener preset, built-in or saved: transparency is flattened before printing; empty: it prints live; PostScript defaults to medium)}, tileOrigin: {placed: false, x, y} (where the Print Tiling tool put the pages: print.tiling.set)}} store the print settings with the document, over the ones it has or the preset's (null keeps a value), as one undo step; no settings or preset → {settings} (the current ones, defaults if never set up)",
has_doc,
setup
),
@@ -32,7 +32,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Print Preview",
[],
None,
"{preset?: name (as print.setup's: its settings instead of the document's), settings?: {…settings of print.setup} (over the document's or the preset's)} → {pages (copies included), sheets: [{artboard (0-based; null with artboards ignored), tile? (1-based), ink? (separations), width, height (pt, the page), orientation, scale: [width %, height %], transform: [a, b, c, d, e, f] (document space → the page, pt, y down), area: [x0, y0, x1, y1] (the document region the page prints), trim: [x0, y0, x1, y1] (the artboard on the page; with copies per sheet, the box around every copy's), copies?: [[x0, y0, x1, y1]…] (copies per sheet: each copy's artboard on the page, across then down)}] (one copy, in order), tiles: [{artboard, columns, rows, printed: [1-based tiles], tiles: [[x0, y0, x1, y1]…] (document space)}], inks: [{name, spot, print, frequency, angle}] (separations), warnings (art larger than the imageable area, type that prints in the fallback font, type that doesn't fit its frame, options not applied yet…), settings} without printing",
"{preset?: name (as print.setup's: its settings instead of the document's), settings?: {…settings of print.setup} (over the document's or the preset's)} → {pages (copies included), sheets: [{artboard (0-based; null with artboards ignored), tile? (1-based), ink? (separations), width, height (pt, the page), orientation, scale: [width %, height %], transform: [a, b, c, d, e, f] (document space → the page, pt, y down), area: [x0, y0, x1, y1] (the document region the page prints), trim: [x0, y0, x1, y1] (the artboard on the page; with copies per sheet, the box around every copy's), copies?: [[x0, y0, x1, y1]…] (copies per sheet: each copy's artboard on the page, across then down)}] (one copy, in order), tiles: [{artboard, columns, rows, printed: [1-based tiles], tiles: [[x0, y0, x1, y1]…] (document space)}], inks: [{name, spot, print, frequency, angle}] (separations: the plates), documentInks: [{name, spot, print, frequency, angle, convertToProcess?: true (a spot ink printing as process, with no plate)}] (separations: every ink of the document), warnings (art larger than the imageable area, type that prints in the fallback font, type that doesn't fit its frame, options not applied yet…), settings} without printing",
has_doc,
preview
),
+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",
]
);
}
}
+17 -3
View File
@@ -34,7 +34,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Recolor Artwork",
["Edit", "Edit Colors"],
None,
"{map: rows [{from: [colour keys (recolor.colors) or \"#rrggbb\" (every colour shown as that hex); may be empty: an empty row recolours nothing, adds no library swatch and gives `group` no colour unless `added`], to: colour (hex, key, {c,m,y,k} or {l,a,b}) | null (in from, to and groupColors, #rrggbbaa and #rgba are refused), exclude?: false (the row's colours are kept), tint?: 100 (percent; with limitTo, art linked to the global or spot swatch the new color is takes this share of its tint), added?: false (an empty row's new color is a color added to `group`)}] | {\"key or #rrggbb\": colour, …} (one row per colour), method?: \"exact\" (default)|\"preserveTints\"|\"scaleTints\"|\"tintsShades\"|\"hueShift\" (how a row's colours take its new colour, relative to the row's darkest, average or most saturated colour), limitTo?: swatch library id or name; or \"document\" (the document's swatches): new colours snap to its nearest colour, group?: colour group to rewrite, groupColors?: [colour | null] (what `group` is rewritten with, a null removing the group's swatch at its place; default: the new colors of the rows with current colors, in order, then those of the empty rows with `added`, excluded rows left out), rename?: the group's new name, includeImages?: true, includePatterns?: true, globalAdjust?: {saturation?: 0, brightness?: 0, temperature?: 0, luminosity?: 0} (Global Adjust: percent from -100 to 100, 0 changes nothing; every colour a row that isn't excluded recolours, and the group's new colours, take the same change after the row's new colour: saturation scales HSB saturation by 1 + saturation/100, brightness moves HSB brightness that share of the way to full or to black, temperature adds 0.2 × temperature/100 to red and takes it from blue, luminosity moves Lab lightness that share of the way to 100 or 0 keeping a and b; with limitTo each row's new colour takes the change before it snaps to the library)} recolour the selection (gradients, text, meshes, image pixels and pattern tiles included; each new colour keeps the model of the one it replaces (model?: \"keep\" default | \"new\" (the new colour's own model, so a CMYK colour replacing RGB art gives CMYK art) | \"document\" (the document's colour mode)), except a library swatch's with limitTo: art takes the swatch itself, linked to a global or spot colour at its tints, and the swatch joins the document's swatches; art linked to a global swatch of `group` that is rewritten with its row's new color stays linked to it, at its tint, unless the row converts the color into the art's model; other recolored art, and art in a row linked to a global swatch of `group` that is rewritten with another color, keeps its row's new color and loses its swatch link) and the group, as one undo step (none when nothing changes). On a path directly in a graph series, the graph also stores the new paint of the topmost visible fill and stroke, and on a graph label the new paint of its characters and rows for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md) → {changed, swatches: [names added to the document's swatches], relinked?: with group, the other paints linked to its global swatches that took their new colors, note?: set when a colour kept a model other than its new colour's (see model), notChanged: {locked, hidden} (as edit.colors.invert), warning?: set when notChanged counts any object}",
"{map: rows [{from: [colour keys (recolor.colors) or \"#rrggbb\" (every colour shown as that hex); may be empty: an empty row recolours nothing, adds no library swatch and gives `group` no colour unless `added`], to: colour (hex, key, {c,m,y,k} or {l,a,b}) | null (in from, to and groupColors, #rrggbbaa and #rgba are refused), exclude?: false (the row's colours are kept), tint?: 100 (percent; with limitTo, art linked to the global or spot swatch the new color is takes this share of its tint), added?: false (an empty row's new color is a color added to `group`)}] | {\"key or #rrggbb\": colour, …} (one row per colour), method?: \"exact\" (default)|\"preserveTints\"|\"scaleTints\"|\"tintsShades\"|\"hueShift\" (how a row's colours take its new colour, relative to the row's darkest, average or most saturated colour), limitTo?: swatch library id or name; or \"document\" (the document's swatches): new colours snap to its nearest colour, group?: colour group to rewrite, groupColors?: [colour | null | \"keep\"] (what `group` is rewritten with, a null removing the group's swatch at its place and \"keep\" leaving that swatch its colour, without the Global Adjust (past the swatches it adds nothing; refused for a swatch that is not a colour); default: the new colors of the rows with current colors, in order, then those of the empty rows with `added`, excluded rows left out), rename?: the group's new name, includeImages?: true, includePatterns?: true, globalAdjust?: {saturation?: 0, brightness?: 0, temperature?: 0, luminosity?: 0} (Global Adjust: percent from -100 to 100, 0 changes nothing; every colour a row that isn't excluded recolours, and the group's new colours, take the same change after the row's new colour: saturation scales HSB saturation by 1 + saturation/100, brightness moves HSB brightness that share of the way to full or to black, temperature adds 0.2 × temperature/100 to red and takes it from blue, luminosity moves Lab lightness that share of the way to 100 or 0 keeping a and b; with limitTo each row's new colour takes the change before it snaps to the library)} recolour the selection (gradients, text, meshes, image pixels and pattern tiles included; each new colour keeps the model of the one it replaces (model?: \"keep\" default | \"new\" (the new colour's own model, so a CMYK colour replacing RGB art gives CMYK art) | \"document\" (the document's colour mode)), except a library swatch's with limitTo: art takes the swatch itself, linked to a global or spot colour at its tints, and the swatch joins the document's swatches; art linked to a global swatch of `group` that is rewritten with its row's new color stays linked to it, at its tint, unless the row converts the color into the art's model; other recolored art, and art in a row linked to a global swatch of `group` that is rewritten with another color, keeps its row's new color and loses its swatch link) and the group, as one undo step (none when nothing changes). On a path directly in a graph series, the graph also stores the new paint of the topmost visible fill and stroke, and on a graph label the new paint of its characters and rows for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md) → {changed, swatches: [names added to the document's swatches], relinked?: with group, the other paints linked to its global swatches that took their new colors, note?: set when a colour kept a model other than its new colour's (see model), notChanged: {locked, hidden} (as edit.colors.invert), warning?: set when notChanged counts any object}",
has_doc,
apply
),
@@ -1680,12 +1680,26 @@ fn apply(s: &mut Session, p: &Value) -> Result<Value> {
Some(Value::Array(cs)) => Some(cs),
Some(_) => return Err(bad(C, "`groupColors` must be an array")),
};
// A null in groupColors removes the group's swatch at its place.
// A null in groupColors removes the group's swatch at its place, and "keep" leaves the swatch
// at its place its color, without the Global Adjust.
let own: Vec<Option<Color>> = match group {
Some(g) => {
s.doc()?.doc.swatch_groups.iter().find(|x| x.name == g).map(|g| g.swatches.iter().map(|w| w.paint.color()).collect()).unwrap_or_default()
}
None => vec![],
};
let new: Vec<Option<Color>> = match group_colors {
Some(cs) => cs
.iter()
.map(|v| match v {
.enumerate()
.map(|(i, v)| match v {
Value::Null => Ok(None),
// Past the group's swatches it adds nothing.
Value::String(k) if k == "keep" => match own.get(i) {
Some(Some(c)) => Ok(Some(*c)),
Some(None) => Err(bad(C, format!("the swatch at place {i} of groupColors is not a colour to keep"))),
None => Ok(None),
},
v => color_value(v)
.map(|c| adjust.apply(c))
.map(|c| Some(in_doc_model(palette.as_ref().map_or(c, |pl| pl.nearest(c)))))
+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)
}
Loaded 100 of 454 files, more files were not shown because too many files have changed in this diff. Show more