mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-19 08:52:45 +01:00
Merge main into feat/palette-synonyms
This commit is contained in:
commit
186874f736
624 files changed
+60203
-4740
No files matched your search
Generated
+101
-125
@@ -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",
|
||||
@@ -1203,10 +1166,20 @@ dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-mime"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"craft-codepage",
|
||||
"encoding_rs",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-pdf"
|
||||
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 = [
|
||||
"hayro-interpret",
|
||||
"hayro-syntax",
|
||||
@@ -1214,10 +1187,18 @@ dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-plotter"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=a7fb55eaf9a15c21e8ce0b13cf605dc54fd15f57#a7fb55eaf9a15c21e8ce0b13cf605dc54fd15f57"
|
||||
dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[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",
|
||||
@@ -1231,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",
|
||||
@@ -1239,10 +1220,19 @@ dependencies = [
|
||||
"unicode-normalization",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-ps"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"kurbo 0.13.1",
|
||||
]
|
||||
|
||||
[[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",
|
||||
@@ -1253,7 +1243,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-stream-codecs"
|
||||
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 = [
|
||||
"fax",
|
||||
"hayro-ccitt",
|
||||
@@ -1264,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",
|
||||
@@ -1283,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",
|
||||
@@ -1301,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",
|
||||
@@ -1322,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",
|
||||
@@ -1349,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",
|
||||
@@ -1360,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",
|
||||
@@ -1371,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",
|
||||
@@ -1390,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",
|
||||
@@ -2507,7 +2478,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a"
|
||||
[[package]]
|
||||
name = "hayro-cmap"
|
||||
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 = [
|
||||
"brotli",
|
||||
"hayro-postscript",
|
||||
@@ -2516,7 +2487,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "hayro-interpret"
|
||||
version = "0.7.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"hayro-cmap",
|
||||
@@ -2534,7 +2505,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "hayro-jbig2"
|
||||
version = "0.3.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
|
||||
dependencies = [
|
||||
"fearless_simd",
|
||||
"hayro-ccitt",
|
||||
@@ -2552,12 +2523,12 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "hayro-postscript"
|
||||
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 = "hayro-syntax"
|
||||
version = "0.7.2"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"hayro-ccitt",
|
||||
@@ -3357,7 +3328,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "krilla"
|
||||
version = "0.8.2"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"bumpalo",
|
||||
@@ -3466,7 +3437,7 @@ checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4"
|
||||
[[package]]
|
||||
name = "linesweeper"
|
||||
version = "0.5.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
|
||||
dependencies = [
|
||||
"arrayvec",
|
||||
"kurbo 0.13.1",
|
||||
@@ -6671,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",
|
||||
]
|
||||
@@ -6700,7 +6671,8 @@ 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",
|
||||
"serde_json",
|
||||
@@ -6753,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",
|
||||
@@ -6773,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",
|
||||
@@ -6797,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",
|
||||
@@ -6854,8 +6826,9 @@ 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",
|
||||
"encoding_rs",
|
||||
"fax",
|
||||
@@ -6933,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",
|
||||
@@ -6953,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",
|
||||
@@ -6994,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",
|
||||
@@ -7028,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",
|
||||
@@ -7048,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",
|
||||
@@ -7087,7 +7060,8 @@ 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",
|
||||
"flate2",
|
||||
@@ -7116,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",
|
||||
@@ -7134,6 +7108,7 @@ dependencies = [
|
||||
name = "vectorcraft-text"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"craft-proof",
|
||||
"harfrust 0.13.3",
|
||||
"icu_segmenter",
|
||||
"kurbo 0.13.1",
|
||||
@@ -7142,6 +7117,7 @@ dependencies = [
|
||||
"subsetter",
|
||||
"unicode-bidi",
|
||||
"unicode-general-category",
|
||||
"unicode-normalization",
|
||||
"unicode-script",
|
||||
"unicode-segmentation",
|
||||
"vectorcraft-doc",
|
||||
@@ -7164,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",
|
||||
@@ -7181,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",
|
||||
@@ -7196,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
-29
@@ -11,37 +11,40 @@ rust-version = "1.95"
|
||||
repository = "https://github.com/storytold/vectorcraft"
|
||||
|
||||
[workspace.dependencies]
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd", 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-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-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-psd = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
|
||||
craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
|
||||
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" }
|
||||
@@ -181,13 +184,13 @@ lto = "thin"
|
||||
codegen-units = 1
|
||||
|
||||
[patch.crates-io]
|
||||
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
|
||||
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
|
||||
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
|
||||
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
|
||||
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
|
||||
krilla = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
|
||||
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
|
||||
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" }
|
||||
|
||||
@@ -128,15 +128,18 @@ 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.
|
||||
- 2026-11-02: Mouse wheel over a closed font-family field in Character, Properties or Control changes selected text through the family list using saved font filters (excluding search text), one undo step per notch, stopping at the ends (#5253). Scores and estimates unchanged.
|
||||
- 2026-11-15: Circle through three points: three Shift-clicks with the Ellipse tool, or `shape.circleThroughPoints` with three points or three selected anchor points, draw the circle whose edge passes through them, with the current paint, in one undo step; after two points the tool previews the circle through the pointer, and two points that are the same or three on one line are refused with a message. Scores and estimates unchanged.
|
||||
- 2026-10-31: Pattern libraries: Window › Swatch Libraries › Patterns and the Swatches panel's library menu open Geometric Patterns, a built-in library of eleven pattern swatches (dots, stripes, checks, a grid and shapes); clicking one adds its pattern and swatch to the document, once, and applies it to the active fill or stroke (`swatch.library.add`).
|
||||
- 2026-11-11: Pattern libraries: Patterns › Grit Textures, a second built-in pattern library, holds eight seamless black textures (Fine Grain, Coarse Grit, Sand, Speckle, Stipple, Scratches, Sparse Flecks and Dense Flecks) on tiles of 18 to 36 pt, each drawn the same way every time; marks that reach past a tile edge continue on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged.
|
||||
- 2026-11-11: Pattern libraries: Patterns › Optical Effects, a third built-in pattern library, of VectorCraft's own designs, holds eight black wave, moiré and op-art tiles (Sine Bands, Ripple Lines, Interference Rings, Offset Rings, Warped Checks, Pinched Stripes, Chevron Pulse and Radiating Lenses) of 32 to 48 pt, each drawn the same way every time; each tile is one period of its design, and art that reaches past a tile edge continues on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged.
|
||||
|
||||
@@ -238,10 +238,12 @@ fn main() -> ExitCode {
|
||||
/// A headless session that remembers what the user keeps between runs: the PDF presets saved, the
|
||||
/// ICC profiles loaded, the plug-ins installed (#2168, #2174, #2541), the custom dictionary's words (#4936) and the Color Settings (#6335), in the folders
|
||||
/// and files next to the preferences that the desktop app uses too, and lists the scripts of the Scripts folder there
|
||||
/// (`script.listInstalled`), keeps File Info's metadata templates there and starts new documents from the New Document profiles there. `VECTORCRAFT_NO_PREFS` and
|
||||
/// (`script.listInstalled`), keeps each script's `Folder.userData` in the Script Data folder there, keeps File Info's
|
||||
/// metadata templates there and starts new documents from the New Document profiles there. `VECTORCRAFT_NO_PREFS` and
|
||||
/// `VECTORCRAFT_CONFIG_DIR` apply as they do there.
|
||||
fn with_stores(mut h: Headless) -> Headless {
|
||||
prefs_dir::attach_scripts_dir(&mut h.session);
|
||||
prefs_dir::attach_script_data(&mut h.session);
|
||||
prefs_dir::attach_metadata_templates_dir(&mut h.session);
|
||||
prefs_dir::attach_new_doc_profiles(&mut h.session);
|
||||
prefs_dir::attach_profile_store(&mut h.session);
|
||||
|
||||
@@ -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 }
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
|
||||
use super::portal_save;
|
||||
#[cfg(windows)]
|
||||
use super::windows_screen_color;
|
||||
#[cfg(all(windows, not(target_vendor = "win7")))]
|
||||
use super::windows_stylus;
|
||||
use super::{ClipboardProbeFactory, FilePick, PickRequest, Services, clipboard, cursor_theme, fileio, printing};
|
||||
@@ -71,7 +73,7 @@ fn open_extensions(exts: &[impl AsRef<str>], any_case: bool) -> Vec<String> {
|
||||
/// `d` set up for `request`: its title, file types, folder and suggested name.
|
||||
fn dialog_for<D: DialogSettings>(d: D, request: &PickRequest) -> D {
|
||||
let pick = match request {
|
||||
PickRequest::Open(pick) | PickRequest::Save(pick) => pick,
|
||||
PickRequest::Open(pick) | PickRequest::Save(pick) | PickRequest::OpenFiles(pick) => pick,
|
||||
PickRequest::OpenMany => {
|
||||
return fileio::place_filters().fold(d.title(vectorcraft_ui_egui::i18n::t("Place")), |d, (name, exts)| {
|
||||
d.filter(
|
||||
@@ -81,8 +83,9 @@ fn dialog_for<D: DialogSettings>(d: D, request: &PickRequest) -> D {
|
||||
});
|
||||
}
|
||||
PickRequest::Folder => return d,
|
||||
PickRequest::FolderAt(folder) => return d.folder(folder),
|
||||
};
|
||||
let any_case = CASE_SENSITIVE_FILTERS && matches!(request, PickRequest::Open(_));
|
||||
let any_case = CASE_SENSITIVE_FILTERS && matches!(request, PickRequest::Open(_) | PickRequest::OpenFiles(_));
|
||||
let d = pick.filters.iter().fold(d, |d, (name, exts)| {
|
||||
d.filter(
|
||||
vectorcraft_ui_egui::i18n::tr_ctx(vectorcraft_ui_egui::i18n::current(), "file-filter", name.as_str()),
|
||||
@@ -96,6 +99,37 @@ fn dialog_for<D: DialogSettings>(d: D, request: &PickRequest) -> D {
|
||||
if pick.name.is_empty() { d } else { d.file_name(&pick.name) }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[test]
|
||||
fn a_folder_picker_asked_for_a_folder_starts_there() {
|
||||
/// The settings a dialog was given, by name.
|
||||
#[derive(Default)]
|
||||
struct Recorded(Vec<String>);
|
||||
impl DialogSettings for Recorded {
|
||||
fn parent(self, _: &winit::window::Window) -> Self {
|
||||
self
|
||||
}
|
||||
fn title(mut self, title: &str) -> Self {
|
||||
self.0.push(format!("title {title}"));
|
||||
self
|
||||
}
|
||||
fn filter(mut self, name: &str, _: &[impl ToString]) -> Self {
|
||||
self.0.push(format!("filter {name}"));
|
||||
self
|
||||
}
|
||||
fn folder(mut self, folder: &str) -> Self {
|
||||
self.0.push(format!("folder {folder}"));
|
||||
self
|
||||
}
|
||||
fn file_name(mut self, name: &str) -> Self {
|
||||
self.0.push(format!("name {name}"));
|
||||
self
|
||||
}
|
||||
}
|
||||
assert_eq!(dialog_for(Recorded::default(), &PickRequest::FolderAt("/a/b".into())).0, ["folder /a/b"]);
|
||||
assert!(dialog_for(Recorded::default(), &PickRequest::Folder).0.is_empty());
|
||||
}
|
||||
|
||||
/// A native file dialog for `request` over `parent` (on Linux the portal then shows it over the
|
||||
/// window and keeps it in front).
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
@@ -128,9 +162,9 @@ fn show_dialog(dialog: rfd::FileDialog, request: &PickRequest, parent: &Parent)
|
||||
}
|
||||
let paths = match request {
|
||||
PickRequest::Open(_) => dialog.pick_file().into_iter().collect(),
|
||||
PickRequest::OpenMany => dialog.pick_files().unwrap_or_default(),
|
||||
PickRequest::OpenMany | PickRequest::OpenFiles(_) => dialog.pick_files().unwrap_or_default(),
|
||||
PickRequest::Save(_) => dialog.save_file().into_iter().collect(),
|
||||
PickRequest::Folder => dialog.pick_folder().into_iter().collect(),
|
||||
PickRequest::Folder | PickRequest::FolderAt(_) => dialog.pick_folder().into_iter().collect(),
|
||||
};
|
||||
paths.into_iter().map(|p| p.to_string_lossy().to_string()).collect()
|
||||
}
|
||||
@@ -313,7 +347,7 @@ fn start_pick(request: PickRequest, parent: &Parent, ui: &egui::Context) -> Opti
|
||||
let picked = dialog.pick_file();
|
||||
Box::pin(async move { picked.await.iter().map(path).collect() })
|
||||
}
|
||||
PickRequest::OpenMany => {
|
||||
PickRequest::OpenMany | PickRequest::OpenFiles(_) => {
|
||||
let picked = dialog.pick_files();
|
||||
Box::pin(async move { picked.await.unwrap_or_default().iter().map(path).collect() })
|
||||
}
|
||||
@@ -332,7 +366,7 @@ fn start_pick(request: PickRequest, parent: &Parent, ui: &egui::Context) -> Opti
|
||||
// on that nil; treat the pick as cancelled instead (#5980).
|
||||
Err(()) => Box::pin(async move { Vec::new() }),
|
||||
},
|
||||
PickRequest::Folder => {
|
||||
PickRequest::Folder | PickRequest::FolderAt(_) => {
|
||||
let picked = dialog.pick_folder();
|
||||
Box::pin(async move { picked.await.iter().map(path).collect() })
|
||||
}
|
||||
@@ -353,14 +387,15 @@ pub(crate) fn services(parent: Parent, ui: egui::Context) -> Services {
|
||||
.and_then(|w| w.window_handle().ok())
|
||||
.is_some_and(|h| matches!(h.as_raw(), RawWindowHandle::Xlib(_) | RawWindowHandle::Xcb(_)));
|
||||
let (clip, clip_probe) = (parent.clone(), parent.clone());
|
||||
let (p1, p2, p3, p4, p5) = (parent.clone(), parent.clone(), parent.clone(), parent.clone(), parent);
|
||||
#[cfg(any(target_os = "macos", target_os = "linux"))]
|
||||
let (p1, p2, p3, p4, p5, p6, p7) = (parent.clone(), parent.clone(), parent.clone(), parent.clone(), parent.clone(), parent.clone(), parent);
|
||||
#[cfg(any(target_os = "macos", target_os = "linux", windows))]
|
||||
let sampled_ui = ui.clone();
|
||||
#[cfg(target_os = "linux")]
|
||||
let sampled_parent = p1.clone();
|
||||
Services {
|
||||
pick_open: Some(Box::new(move |pick: &FilePick| pick_now(PickRequest::Open(pick.clone()), &p1).into_iter().next())),
|
||||
pick_open_multi: Some(Box::new(move || pick_now(PickRequest::OpenMany, &p2))),
|
||||
pick_open_files: Some(Box::new(move |pick: &FilePick| pick_now(PickRequest::OpenFiles(pick.clone()), &p6))),
|
||||
pick_save: Some(Box::new(move |pick: &FilePick| pick_now(PickRequest::Save(pick.clone()), &p3).into_iter().next())),
|
||||
// Linux shows dialogs on a thread of their own (#592), macOS as sheets (#867); Windows
|
||||
// dialogs run the window's events while they are open.
|
||||
@@ -408,11 +443,14 @@ pub(crate) fn services(parent: Parent, ui: egui::Context) -> Services {
|
||||
// Edit Original of a raster image with Use System Defaults for Edit Original off (#5236).
|
||||
open_in_photocraft: Some(Box::new(open_in_photocraft)),
|
||||
pick_folder: Some(Box::new(move || pick_now(PickRequest::Folder, &p4).into_iter().next())),
|
||||
pick_folder_at: Some(Box::new(move |start: &str| pick_now(PickRequest::FolderAt(start.to_string()), &p7).into_iter().next())),
|
||||
// Sample Color from Screen: the system's color sampler.
|
||||
#[cfg(target_os = "macos")]
|
||||
screen_color: Some(mac_screen_color::sampler(sampled_ui)),
|
||||
#[cfg(target_os = "linux")]
|
||||
screen_color: Some(linux_screen_color::sampler(sampled_ui, sampled_parent)),
|
||||
#[cfg(windows)]
|
||||
screen_color: Some(windows_screen_color::sampler(sampled_ui)),
|
||||
// File → Print: the system's printers and print queue.
|
||||
print: Some(Box::new(printing::SystemPrint)),
|
||||
..Default::default()
|
||||
|
||||
@@ -77,6 +77,7 @@ mod window_frame;
|
||||
mod windows_alt_codes;
|
||||
#[cfg(windows)]
|
||||
mod windows_cores;
|
||||
mod windows_screen_color;
|
||||
mod windows_stylus;
|
||||
mod xwayland;
|
||||
|
||||
@@ -141,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.
|
||||
@@ -364,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")]
|
||||
@@ -457,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()));
|
||||
@@ -507,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")]
|
||||
@@ -538,6 +554,7 @@ fn main() -> std::process::ExitCode {
|
||||
// File Info's metadata templates live in their own folder next to the preferences.
|
||||
prefs_dir::attach_metadata_templates_dir(&mut session);
|
||||
prefs_dir::attach_new_doc_profiles(&mut session);
|
||||
prefs_dir::attach_script_data(&mut session);
|
||||
let mut app = VectorcraftApp::new(session, services(cc.winit_window().cloned(), cc.egui_ctx.clone()));
|
||||
app.set_startup_update_check(true);
|
||||
load_prefs(&mut app, saved);
|
||||
@@ -590,14 +607,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!(
|
||||
@@ -692,6 +710,8 @@ fn main() -> std::process::ExitCode {
|
||||
monitors_listed: None,
|
||||
display_profile: Default::default(),
|
||||
frame_start: None,
|
||||
min_frame,
|
||||
last_frame_began: None,
|
||||
}))
|
||||
}),
|
||||
)
|
||||
|
||||
@@ -81,6 +81,15 @@ pub fn attach_new_doc_profiles(session: &mut vectorcraft_engine::Session) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Keep each script's `Folder.userData` in the `Script Data` folder, and the file access people
|
||||
/// allow scripts with Always in `Script Grants.json` beside it. Both are made when a script first
|
||||
/// needs them.
|
||||
pub fn attach_script_data(session: &mut vectorcraft_engine::Session) {
|
||||
if let Some(dir) = store_dir("Script Data") {
|
||||
session.attach_script_data(dir);
|
||||
}
|
||||
}
|
||||
|
||||
/// Take the saved PDF presets from the `PDF Presets` folder (#2168), and keep the ones saved from
|
||||
/// now on there. After the preferences were restored: the folder is the one place the presets live.
|
||||
pub fn attach_pdf_preset_store(session: &mut vectorcraft_engine::Session) {
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
}
|
||||
@@ -9,9 +9,8 @@ impl PrintService for SystemPrint {
|
||||
system::printers()
|
||||
}
|
||||
fn print(&mut self, job: &PrintJob) -> Result<String, String> {
|
||||
let result = system::print(job);
|
||||
let to = job.printer.unwrap_or("the default printer");
|
||||
result.map(|note| format!("Sent “{}” to {to}{note}", job.title))
|
||||
let note = system::print(job)?;
|
||||
Ok(sent(job.title, job.printer, ¬e))
|
||||
}
|
||||
fn shared_print(&self) -> Option<vectorcraft_ui_egui::print::SharedPrintFn> {
|
||||
Some(std::sync::Arc::new(|job| SystemPrint.print(job)))
|
||||
@@ -29,6 +28,15 @@ impl PrintService for SystemPrint {
|
||||
}
|
||||
}
|
||||
|
||||
/// The status after the job `title` went to `printer` (the default one without a name), with the
|
||||
/// spooler's `note` when it gave one. Each message has text between its values, so a catalog can
|
||||
/// match it and translate it. The note follows as its own sentence: a printer name can end in
|
||||
/// parentheses ("HP LaserJet (Copy 1)"), and a note in parentheses would match that name.
|
||||
fn sent(title: &str, printer: Option<&str>, note: &str) -> String {
|
||||
let to = printer.unwrap_or("the default printer");
|
||||
if note.is_empty() { format!("Sent “{title}” to {to}") } else { format!("Sent “{title}” to {to}. The spooler replied: {note}") }
|
||||
}
|
||||
|
||||
mod system {
|
||||
use super::{Command, PrintJob, Printer};
|
||||
pub fn printers() -> Vec<Printer> {
|
||||
@@ -38,7 +46,7 @@ mod system {
|
||||
// Copies, layout, marks and colour management are already in the PDF. Preserve its
|
||||
// physical sheet size and the queue's duplex default without printing copies twice.
|
||||
let settings = craft_print::Job { printer: job.printer.map(str::to_string), title: job.title.into(), ..Default::default() };
|
||||
craft_print::submit(job.pdf, &settings).map(|note| if note.is_empty() { note } else { format!(" ({note})") }).map_err(|e| e.to_string())
|
||||
craft_print::submit(job.pdf, &settings).map_err(|e| e.to_string())
|
||||
}
|
||||
#[cfg(windows)]
|
||||
pub(crate) fn setup_command(printer: Option<&str>, default_printer: Option<&str>) -> Command {
|
||||
@@ -127,9 +135,28 @@ mod tests {
|
||||
|
||||
#[cfg(test)]
|
||||
mod turn_tests {
|
||||
use super::SystemPrint;
|
||||
use super::{SystemPrint, sent};
|
||||
use vectorcraft_ui_egui::print::PrintService;
|
||||
|
||||
#[test]
|
||||
fn the_sent_status_names_the_job_the_printer_and_the_note() {
|
||||
assert_eq!(sent("Poster", None, ""), "Sent “Poster” to the default printer");
|
||||
assert_eq!(sent("Poster", Some("Office Laser"), ""), "Sent “Poster” to Office Laser");
|
||||
assert_eq!(sent("Poster", Some("Office Laser"), "job 12"), "Sent “Poster” to Office Laser. The spooler replied: job 12");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_printer_name_ending_in_parentheses_stays_whole_in_a_translation() {
|
||||
use vectorcraft_ui_egui::i18n::{Lang, message};
|
||||
let Some(de) = Lang::from_code("de") else { panic!("no German catalog") };
|
||||
let printer = Some("HP LaserJet (Copy 1)");
|
||||
assert_eq!(message(de, &sent("Poster", printer, "")), "“Poster” an HP LaserJet (Copy 1) gesendet");
|
||||
assert_eq!(
|
||||
message(de, &sent("Poster", printer, "job 12")),
|
||||
"“Poster” an HP LaserJet (Copy 1) gesendet. Antwort der Druckwarteschlange: job 12"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_macos_queues_need_landscape_pages_turned() {
|
||||
assert_eq!(SystemPrint.turns_landscape(), !cfg!(target_os = "macos"));
|
||||
|
||||
@@ -78,7 +78,7 @@ impl Monitor {
|
||||
let scale = self.scale * zoom;
|
||||
let [x, y] = self.pos;
|
||||
let [w, h] = self.size;
|
||||
DockMonitor { name, rect: [x, y, w, h].map(|v| v as f32 / scale), scale }
|
||||
DockMonitor { name, rect: [x, y, w, h].map(|v| v as f32 / scale), scale, work_area: None }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -248,13 +248,13 @@ mod tests {
|
||||
fn floating_panels_get_monitors_in_the_points_a_window_on_them_reports() {
|
||||
let dock = |m: Monitor, zoom| m.docking(Some("m".into()), zoom);
|
||||
let plain = dock(monitor(1920, 0, 1920, 1080, 1.0), 1.0);
|
||||
assert_eq!(plain, DockMonitor { name: Some("m".into()), rect: [1920.0, 0.0, 1920.0, 1080.0], scale: 1.0 });
|
||||
assert_eq!(plain, DockMonitor { name: Some("m".into()), rect: [1920.0, 0.0, 1920.0, 1080.0], scale: 1.0, work_area: None });
|
||||
// A window at (3000, 200) on this monitor reports (1500, 100).
|
||||
let scaled = dock(monitor(1920, -200, 3840, 2160, 2.0), 1.0);
|
||||
assert_eq!(scaled, DockMonitor { name: Some("m".into()), rect: [960.0, -100.0, 1920.0, 1080.0], scale: 2.0 });
|
||||
assert_eq!(scaled, DockMonitor { name: Some("m".into()), rect: [960.0, -100.0, 1920.0, 1080.0], scale: 2.0, work_area: None });
|
||||
// The UI zoom divides what egui reports as well.
|
||||
let zoomed = dock(monitor(-2560, 0, 2560, 1440, 1.0), 1.25);
|
||||
assert_eq!(zoomed, DockMonitor { name: Some("m".into()), rect: [-2048.0, 0.0, 2048.0, 1152.0], scale: 1.25 });
|
||||
assert_eq!(zoomed, DockMonitor { name: Some("m".into()), rect: [-2048.0, 0.0, 2048.0, 1152.0], scale: 1.25, work_area: None });
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -0,0 +1,655 @@
|
||||
//! Windows: Sample Color from Screen (`vectorcraft_ui_egui::screen_color`). Windows has no system
|
||||
//! color sampler, so a thread of its own copies the virtual screen, the bounding rectangle of all
|
||||
//! the monitors (<https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getsystemmetrics>),
|
||||
//! into a bitmap with `BitBlt` from the screen's device context
|
||||
//! (<https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getdc>), then covers
|
||||
//! the virtual screen with a borderless topmost window that shows that copy under a crosshair
|
||||
//! cursor. The window has its own message loop on that thread, so the UI keeps drawing.
|
||||
//!
|
||||
//! A left click answers the copied pixel under the pointer as sRGB; Escape, a click of any other
|
||||
//! button, closing the window, and the window losing the keyboard focus or the mouse capture answer
|
||||
//! `None`. Each
|
||||
//! click is answered when its button is released, so the release does not reach the window
|
||||
//! underneath. The color comes from the copy taken before the window was shown, so the window
|
||||
//! never samples itself, and moving content shows the frame it had when the copy was taken.
|
||||
//!
|
||||
//! The pixels are 8-bit GDI colors, read as sRGB: GDI content is taken to be sRGB when the display
|
||||
//! does not use Advanced Color
|
||||
//! (<https://learn.microsoft.com/en-us/windows/win32/wcs/advanced-color-icc-profiles>). The colors
|
||||
//! of HDR and wide-gamut displays are not converted.
|
||||
//!
|
||||
//! winit makes the process per-monitor DPI aware, so the virtual screen, the pointer and the copy
|
||||
//! are in physical pixels on every monitor, whatever its scale, and a monitor left of or above the
|
||||
//! main one has negative coordinates
|
||||
//! (<https://learn.microsoft.com/en-us/windows/win32/hidpi/high-dpi-desktop-application-development-on-windows>).
|
||||
//!
|
||||
//! The Win32 calls have no safe binding; [`overlay`] allows `unsafe_code`.
|
||||
#![cfg_attr(not(windows), allow(dead_code))]
|
||||
|
||||
/// The status message for every failure; the details go to the log.
|
||||
const FAILED: &str = "the screen color sampler failed";
|
||||
|
||||
/// The largest copy of the virtual screen, in bytes of 32-bit pixels: 1 GiB, eight 7680 × 4320
|
||||
/// monitors. VectorCraft's own limit.
|
||||
const MAX_SNAPSHOT_BYTES: u64 = 1 << 30;
|
||||
|
||||
/// `CLR_INVALID` (`wingdi.h`): what `GetPixel` answers for a pixel it can't read.
|
||||
const CLR_INVALID: u32 = 0xFFFF_FFFF;
|
||||
|
||||
/// The virtual screen in physical pixels: its top-left corner (negative when a monitor is left of
|
||||
/// or above the main one) and its size.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
struct VirtualScreen {
|
||||
left: i32,
|
||||
top: i32,
|
||||
width: i32,
|
||||
height: i32,
|
||||
}
|
||||
|
||||
impl VirtualScreen {
|
||||
/// The virtual screen `GetSystemMetrics` reports, checked before any memory is taken for its
|
||||
/// copy: an error when it is empty, larger than [`MAX_SNAPSHOT_BYTES`], or reaches past the
|
||||
/// coordinates Windows can address.
|
||||
fn new(left: i32, top: i32, width: i32, height: i32) -> Result<Self, String> {
|
||||
if width <= 0 || height <= 0 {
|
||||
return Err(format!("the virtual screen is {width} × {height} pixels"));
|
||||
}
|
||||
let bytes = u64::from(width.unsigned_abs()).saturating_mul(u64::from(height.unsigned_abs())).saturating_mul(4);
|
||||
if bytes > MAX_SNAPSHOT_BYTES {
|
||||
return Err(format!("the virtual screen ({width} × {height} pixels) is larger than the {MAX_SNAPSHOT_BYTES}-byte limit"));
|
||||
}
|
||||
if left.checked_add(width).is_none() || top.checked_add(height).is_none() {
|
||||
return Err(format!("the virtual screen at ({left}, {top}) reaches past the coordinate range"));
|
||||
}
|
||||
Ok(Self { left, top, width, height })
|
||||
}
|
||||
|
||||
/// The pixel of the copy at the screen point (`x`, `y`), or `None` when the point is outside the
|
||||
/// virtual screen.
|
||||
fn pixel(&self, x: i32, y: i32) -> Option<(i32, i32)> {
|
||||
let (px, py) = (x.checked_sub(self.left)?, y.checked_sub(self.top)?);
|
||||
((0..self.width).contains(&px) && (0..self.height).contains(&py)).then_some((px, py))
|
||||
}
|
||||
}
|
||||
|
||||
/// The sRGB components (0 to 1) of a `COLORREF` (`0x00bbggrr`), or `None` for `CLR_INVALID` or any
|
||||
/// other value with its high byte set.
|
||||
fn srgb(colorref: u32) -> Option<[f32; 3]> {
|
||||
if colorref == CLR_INVALID {
|
||||
return None;
|
||||
}
|
||||
let [r, g, b, high] = colorref.to_le_bytes();
|
||||
(high == 0).then(|| [r, g, b].map(|v| f32::from(v) / 255.0))
|
||||
}
|
||||
|
||||
/// The client point of a mouse message. Its `lParam` holds each coordinate as a signed 16-bit
|
||||
/// value (`GET_X_LPARAM` and `GET_Y_LPARAM`,
|
||||
/// <https://learn.microsoft.com/en-us/windows/win32/inputdev/wm-lbuttonup>), so a coordinate past
|
||||
/// 32,767 pixels in a wide virtual screen loses its high bits. Each coordinate becomes the value
|
||||
/// with the same low 16 bits nearest to `near`, the message's own pointer position (`MSG.pt`,
|
||||
/// <https://learn.microsoft.com/en-us/windows/win32/api/winuser/ns-winuser-msg>) in client
|
||||
/// coordinates.
|
||||
fn message_point(lparam: isize, near: (i32, i32)) -> (i32, i32) {
|
||||
let widen = |low: i16, near: i32| near.saturating_add(i32::from(i32::from(low).wrapping_sub(near) as i16));
|
||||
(widen(lparam as i16, near.0), widen((lparam >> 16) as i16, near.1))
|
||||
}
|
||||
|
||||
/// A mouse button: the left one picks, and any other one cancels.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Button {
|
||||
Left,
|
||||
Right,
|
||||
/// The middle button or a side button.
|
||||
Other,
|
||||
}
|
||||
|
||||
/// What the person did in the sampler's window.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Input {
|
||||
Down(Button),
|
||||
Up(Button),
|
||||
Escape,
|
||||
/// The window became the active window.
|
||||
Activated,
|
||||
/// The window stopped being the active window.
|
||||
Deactivated,
|
||||
/// Another window took the mouse capture.
|
||||
CaptureLost,
|
||||
/// The window was asked to close (Alt+F4).
|
||||
Closed,
|
||||
}
|
||||
|
||||
/// What the sampler does next.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Step {
|
||||
Wait,
|
||||
Pick,
|
||||
Cancel,
|
||||
}
|
||||
|
||||
/// The mouse button last pressed in the window, and whether the window has been active.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
struct Press {
|
||||
down: Option<Button>,
|
||||
active: bool,
|
||||
}
|
||||
|
||||
impl Press {
|
||||
/// A release picks or cancels only after its button went down in the window. Losing the focus
|
||||
/// cancels only after the window had it, so a window that never became active still takes a
|
||||
/// click.
|
||||
fn step(&mut self, input: Input) -> Step {
|
||||
match input {
|
||||
Input::Down(button) => {
|
||||
self.down = Some(button);
|
||||
Step::Wait
|
||||
}
|
||||
Input::Up(button) if self.down == Some(button) => {
|
||||
if button == Button::Left {
|
||||
Step::Pick
|
||||
} else {
|
||||
Step::Cancel
|
||||
}
|
||||
}
|
||||
Input::Up(_) => Step::Wait,
|
||||
Input::Activated => {
|
||||
self.active = true;
|
||||
Step::Wait
|
||||
}
|
||||
Input::Deactivated if !self.active => Step::Wait,
|
||||
Input::Escape | Input::Deactivated | Input::CaptureLost | Input::Closed => Step::Cancel,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The screen color sampler; `ui` is woken when it answers.
|
||||
#[cfg(windows)]
|
||||
pub fn sampler(ui: egui::Context) -> vectorcraft_ui_egui::screen_color::StartSampler {
|
||||
Box::new(move || {
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
let ui = ui.clone();
|
||||
std::thread::Builder::new()
|
||||
.name("screen-color".into())
|
||||
.spawn(move || {
|
||||
let answer = overlay::run().map_err(|detail| {
|
||||
log::warn!("the screen color sampler gave no color: {detail}");
|
||||
FAILED.to_string()
|
||||
});
|
||||
// The UI may be gone (the app quitting): nothing waits for the color then.
|
||||
let _ = tx.send(answer);
|
||||
ui.request_repaint();
|
||||
})
|
||||
.map_err(|e| {
|
||||
log::warn!("could not start the screen color sampler's thread: {e}");
|
||||
FAILED.to_string()
|
||||
})?;
|
||||
Ok(rx)
|
||||
})
|
||||
}
|
||||
|
||||
/// The copy of the virtual screen and the window that shows it, on the sampler's thread.
|
||||
#[cfg(windows)]
|
||||
mod overlay {
|
||||
#![allow(unsafe_code)]
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::sync::OnceLock;
|
||||
|
||||
use windows::Win32::Foundation::{HWND, LPARAM, LRESULT, POINT, WPARAM};
|
||||
use windows::Win32::Graphics::Gdi::{
|
||||
BeginPaint, BitBlt, CAPTUREBLT, ClientToScreen, CreateCompatibleBitmap, CreateCompatibleDC, DeleteDC, DeleteObject, EndPaint, GetDC,
|
||||
GetPixel, HBITMAP, HDC, HGDIOBJ, PAINTSTRUCT, ReleaseDC, SRCCOPY, SelectObject,
|
||||
};
|
||||
use windows::Win32::System::LibraryLoader::GetModuleHandleW;
|
||||
use windows::Win32::UI::Input::KeyboardAndMouse::{ReleaseCapture, SetCapture, VK_ESCAPE};
|
||||
use windows::Win32::UI::WindowsAndMessaging::{
|
||||
CreateWindowExW, DefWindowProcW, DestroyWindow, DispatchMessageW, GetCursorPos, GetMessageW, GetSystemMetrics, HCURSOR, IDC_CROSS,
|
||||
LoadCursorW, MSG, PostQuitMessage, RegisterClassExW, SM_CXVIRTUALSCREEN, SM_CYVIRTUALSCREEN, SM_XVIRTUALSCREEN, SM_YVIRTUALSCREEN, SW_SHOW,
|
||||
SetCursor, SetForegroundWindow, ShowWindow, TranslateMessage, WA_INACTIVE, WM_ACTIVATE, WM_CAPTURECHANGED, WM_CLOSE, WM_DESTROY,
|
||||
WM_DPICHANGED, WM_ERASEBKGND, WM_KEYDOWN, WM_LBUTTONDOWN, WM_LBUTTONUP, WM_MBUTTONDOWN, WM_MBUTTONUP, WM_MOUSEMOVE, WM_PAINT, WM_RBUTTONDOWN,
|
||||
WM_RBUTTONUP, WM_SETCURSOR, WM_XBUTTONDOWN, WM_XBUTTONUP, WNDCLASSEXW, WS_EX_TOOLWINDOW, WS_EX_TOPMOST, WS_POPUP,
|
||||
};
|
||||
use windows::core::{PCWSTR, w};
|
||||
|
||||
use super::{Button, Input, Press, Step, VirtualScreen, message_point, srgb};
|
||||
|
||||
/// The window class of the sampler's window.
|
||||
const CLASS: PCWSTR = w!("VectorCraftScreenColor");
|
||||
|
||||
/// The picked color, `None` when canceled, or the details of a failure.
|
||||
type Picked = Result<Option<[f32; 3]>, String>;
|
||||
|
||||
/// A copy of the virtual screen in a memory device context. Dropping it frees the bitmap and
|
||||
/// the device context.
|
||||
struct Snapshot {
|
||||
dc: HDC,
|
||||
bitmap: HBITMAP,
|
||||
/// The bitmap the device context held before [`Snapshot::bitmap`] replaced it.
|
||||
old: HGDIOBJ,
|
||||
}
|
||||
|
||||
impl Snapshot {
|
||||
/// Copies `screen` from the screen's device context, which is released on this thread, as
|
||||
/// `ReleaseDC` requires.
|
||||
fn take(screen: VirtualScreen) -> Result<Self, String> {
|
||||
// SAFETY: `GetDC(None)` takes no pointers; the device context is released below.
|
||||
let screen_dc = unsafe { GetDC(None) };
|
||||
if screen_dc.is_invalid() {
|
||||
return Err("GetDC(NULL) gave no device context".into());
|
||||
}
|
||||
let copied = Self::copy(screen_dc, screen);
|
||||
// SAFETY: the device context `GetDC(None)` gave on this thread, released once.
|
||||
unsafe { ReleaseDC(None, screen_dc) };
|
||||
copied
|
||||
}
|
||||
|
||||
fn copy(screen_dc: HDC, s: VirtualScreen) -> Result<Self, String> {
|
||||
// SAFETY: `screen_dc` is a live device context; a failure answers a null handle.
|
||||
let dc = unsafe { CreateCompatibleDC(Some(screen_dc)) };
|
||||
if dc.is_invalid() {
|
||||
return Err("CreateCompatibleDC failed".into());
|
||||
}
|
||||
// SAFETY: as above; the size was checked by `VirtualScreen::new`.
|
||||
let bitmap = unsafe { CreateCompatibleBitmap(screen_dc, s.width, s.height) };
|
||||
if bitmap.is_invalid() {
|
||||
// SAFETY: the device context made above, deleted once.
|
||||
unsafe {
|
||||
let _ = DeleteDC(dc);
|
||||
}
|
||||
return Err(format!("CreateCompatibleBitmap gave no {} × {} bitmap", s.width, s.height));
|
||||
}
|
||||
// SAFETY: both handles are live and made above.
|
||||
let old = unsafe { SelectObject(dc, bitmap.into()) };
|
||||
if old.is_invalid() {
|
||||
// SAFETY: the handles made above, deleted once.
|
||||
unsafe {
|
||||
let _ = DeleteObject(bitmap.into());
|
||||
let _ = DeleteDC(dc);
|
||||
}
|
||||
return Err("SelectObject failed".into());
|
||||
}
|
||||
let snapshot = Self { dc, bitmap, old };
|
||||
// SAFETY: both device contexts are live; the rectangle is the virtual screen.
|
||||
unsafe { BitBlt(dc, 0, 0, s.width, s.height, Some(screen_dc), s.left, s.top, SRCCOPY | CAPTUREBLT) }
|
||||
.map_err(|e| format!("BitBlt of the virtual screen failed: {e}"))?;
|
||||
Ok(snapshot)
|
||||
}
|
||||
|
||||
/// The `COLORREF` of the copy's pixel (`x`, `y`).
|
||||
fn colorref(&self, x: i32, y: i32) -> u32 {
|
||||
// SAFETY: the device context is live while `self` is; GetPixel checks the coordinates.
|
||||
unsafe { GetPixel(self.dc, x, y) }.0
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Snapshot {
|
||||
fn drop(&mut self) {
|
||||
// SAFETY: the handles `copy` made, freed once, the bitmap after the device context
|
||||
// lets go of it.
|
||||
unsafe {
|
||||
SelectObject(self.dc, self.old);
|
||||
let _ = DeleteObject(self.bitmap.into());
|
||||
let _ = DeleteDC(self.dc);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The sampler shown on this thread.
|
||||
struct Session {
|
||||
snapshot: Snapshot,
|
||||
screen: VirtualScreen,
|
||||
cursor: HCURSOR,
|
||||
press: Press,
|
||||
/// The pointer position, in screen coordinates, of the message being dispatched (`MSG.pt`).
|
||||
message_pt: Option<POINT>,
|
||||
/// The answer, set once.
|
||||
answer: Option<Picked>,
|
||||
/// The window has been destroyed.
|
||||
destroyed: bool,
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
static SESSION: RefCell<Option<Session>> = const { RefCell::new(None) };
|
||||
}
|
||||
|
||||
/// Runs `f` on this thread's session, or answers `None` when there is none or it is in use.
|
||||
/// Win32 calls that send messages to the window (which come back to [`window_proc`]) are made
|
||||
/// outside it.
|
||||
fn with<R>(f: impl FnOnce(&mut Session) -> R) -> Option<R> {
|
||||
SESSION.with(|s| s.try_borrow_mut().ok()?.as_mut().map(f))
|
||||
}
|
||||
|
||||
fn put(session: Option<Session>) -> Option<Session> {
|
||||
SESSION.with(|s| s.try_borrow_mut().ok().map(|mut s| std::mem::replace(&mut *s, session)))?
|
||||
}
|
||||
|
||||
/// Shows the sampler and waits for the person; answers on this thread.
|
||||
pub(super) fn run() -> Picked {
|
||||
// SAFETY: `GetSystemMetrics` takes no pointers.
|
||||
let (left, top, width, height) = unsafe {
|
||||
(
|
||||
GetSystemMetrics(SM_XVIRTUALSCREEN),
|
||||
GetSystemMetrics(SM_YVIRTUALSCREEN),
|
||||
GetSystemMetrics(SM_CXVIRTUALSCREEN),
|
||||
GetSystemMetrics(SM_CYVIRTUALSCREEN),
|
||||
)
|
||||
};
|
||||
let screen = VirtualScreen::new(left, top, width, height)?;
|
||||
let snapshot = Snapshot::take(screen)?;
|
||||
register()?;
|
||||
// SAFETY: a system cursor, loaded by its id.
|
||||
let cursor = unsafe { LoadCursorW(None, IDC_CROSS) }.map_err(|e| format!("LoadCursorW: {e}"))?;
|
||||
// Each sampler runs on a thread of its own, so the thread has no session yet.
|
||||
let _ = put(Some(Session { snapshot, screen, cursor, press: Press::default(), message_pt: None, answer: None, destroyed: false }));
|
||||
let shown = show(screen, cursor);
|
||||
if let Ok(hwnd) = shown {
|
||||
pump();
|
||||
if with(|s| s.destroyed) == Some(false) {
|
||||
// SAFETY: the window made by `show` on this thread, not yet destroyed.
|
||||
let _ = unsafe { DestroyWindow(hwnd) };
|
||||
}
|
||||
}
|
||||
let session = put(None);
|
||||
shown?;
|
||||
session.and_then(|s| s.answer).unwrap_or(Ok(None))
|
||||
}
|
||||
|
||||
/// Registers the window class once for the process.
|
||||
fn register() -> Result<(), String> {
|
||||
static REGISTERED: OnceLock<Result<(), String>> = OnceLock::new();
|
||||
REGISTERED
|
||||
.get_or_init(|| {
|
||||
// SAFETY: the module handle of this program; it is not freed.
|
||||
let instance = unsafe { GetModuleHandleW(None) }.map_err(|e| format!("GetModuleHandleW: {e}"))?;
|
||||
let class = WNDCLASSEXW {
|
||||
cbSize: std::mem::size_of::<WNDCLASSEXW>() as u32,
|
||||
lpfnWndProc: Some(window_proc),
|
||||
hInstance: instance.into(),
|
||||
lpszClassName: CLASS,
|
||||
..Default::default()
|
||||
};
|
||||
// SAFETY: `class` is a complete `WNDCLASSEXW` whose strings are static.
|
||||
if unsafe { RegisterClassExW(&class) } == 0 {
|
||||
return Err(format!("RegisterClassExW: {}", windows::core::Error::from_thread()));
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.clone()
|
||||
}
|
||||
|
||||
/// Shows the window over the virtual screen in front of every other window and takes the mouse.
|
||||
fn show(s: VirtualScreen, cursor: HCURSOR) -> Result<HWND, String> {
|
||||
// SAFETY: the module handle of this program; it is not freed.
|
||||
let instance = unsafe { GetModuleHandleW(None) }.map_err(|e| format!("GetModuleHandleW: {e}"))?;
|
||||
// SAFETY: the class was registered by `register`; the strings are static.
|
||||
let hwnd = unsafe {
|
||||
CreateWindowExW(
|
||||
WS_EX_TOPMOST | WS_EX_TOOLWINDOW,
|
||||
CLASS,
|
||||
w!("Sample Color from Screen"),
|
||||
WS_POPUP,
|
||||
s.left,
|
||||
s.top,
|
||||
s.width,
|
||||
s.height,
|
||||
None,
|
||||
None,
|
||||
Some(instance.into()),
|
||||
None,
|
||||
)
|
||||
}
|
||||
.map_err(|e| format!("CreateWindowExW: {e}"))?;
|
||||
// SAFETY: the window made above, on this thread.
|
||||
unsafe {
|
||||
let _ = ShowWindow(hwnd, SW_SHOW);
|
||||
let _ = SetForegroundWindow(hwnd);
|
||||
SetCapture(hwnd);
|
||||
SetCursor(Some(cursor));
|
||||
}
|
||||
Ok(hwnd)
|
||||
}
|
||||
|
||||
/// The window's message loop, until the window is destroyed.
|
||||
fn pump() {
|
||||
let mut msg = MSG::default();
|
||||
// SAFETY: `msg` is a valid `MSG` for each call. `GetMessageW` answers 0 for `WM_QUIT` and -1
|
||||
// for an error; both end the loop.
|
||||
while unsafe { GetMessageW(&mut msg, None, 0, 0) }.0 > 0 {
|
||||
with(|s| s.message_pt = Some(msg.pt));
|
||||
// SAFETY: the message `GetMessageW` just filled in.
|
||||
unsafe {
|
||||
let _ = TranslateMessage(&msg);
|
||||
DispatchMessageW(&msg);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Answers once, then lets go of the mouse and destroys the window.
|
||||
fn finish(hwnd: HWND, answer: impl FnOnce(&mut Session) -> Picked) {
|
||||
let first = with(|s| {
|
||||
let first = s.answer.is_none();
|
||||
if first {
|
||||
s.answer = Some(answer(s));
|
||||
}
|
||||
first
|
||||
});
|
||||
if first == Some(true) {
|
||||
// SAFETY: the window on this thread; both calls send messages that `window_proc`
|
||||
// handles outside the session.
|
||||
unsafe {
|
||||
let _ = ReleaseCapture();
|
||||
let _ = DestroyWindow(hwnd);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The copy's color at the point where the left button was released: `lparam` of that
|
||||
/// `WM_LBUTTONUP`, in `hwnd`'s client coordinates, not where the pointer is now. The pointer's
|
||||
/// current position stands in for `MSG.pt` only when the release was not dispatched by
|
||||
/// [`pump`].
|
||||
fn pick(s: &mut Session, hwnd: HWND, lparam: LPARAM) -> Picked {
|
||||
let mut origin = POINT::default();
|
||||
// SAFETY: the window on this thread and a valid `POINT`; the call sends no message.
|
||||
unsafe { ClientToScreen(hwnd, &mut origin) }.ok().map_err(|e| format!("ClientToScreen: {e}"))?;
|
||||
let pt = match s.message_pt {
|
||||
Some(pt) => pt,
|
||||
None => {
|
||||
let mut now = POINT::default();
|
||||
// SAFETY: `now` is a valid `POINT`.
|
||||
unsafe { GetCursorPos(&mut now) }.map_err(|e| format!("GetCursorPos: {e}"))?;
|
||||
now
|
||||
}
|
||||
};
|
||||
let near = (pt.x.wrapping_sub(origin.x), pt.y.wrapping_sub(origin.y));
|
||||
let (cx, cy) = message_point(lparam.0, near);
|
||||
let at = POINT { x: cx.saturating_add(origin.x), y: cy.saturating_add(origin.y) };
|
||||
let (x, y) = s.screen.pixel(at.x, at.y).ok_or_else(|| format!("the release at ({}, {}) is outside the virtual screen", at.x, at.y))?;
|
||||
let colorref = s.snapshot.colorref(x, y);
|
||||
srgb(colorref).map(Some).ok_or_else(|| format!("GetPixel({x}, {y}) answered {colorref:#010x}"))
|
||||
}
|
||||
|
||||
/// Draws the copy where the virtual screen is, wherever the window's client area is.
|
||||
fn paint(hwnd: HWND) {
|
||||
let copy = with(|s| (s.snapshot.dc, s.screen));
|
||||
let mut ps = PAINTSTRUCT::default();
|
||||
let mut origin = POINT::default();
|
||||
// SAFETY: the window on this thread, with a `PAINTSTRUCT` for `BeginPaint` and `EndPaint`;
|
||||
// the copy's device context lives as long as the session.
|
||||
unsafe {
|
||||
let _ = ClientToScreen(hwnd, &mut origin);
|
||||
let target = BeginPaint(hwnd, &mut ps);
|
||||
if let Some((dc, s)) = copy
|
||||
&& !target.is_invalid()
|
||||
{
|
||||
let _ = BitBlt(target, s.left.saturating_sub(origin.x), s.top.saturating_sub(origin.y), s.width, s.height, Some(dc), 0, 0, SRCCOPY);
|
||||
}
|
||||
let _ = EndPaint(hwnd, &ps);
|
||||
}
|
||||
}
|
||||
|
||||
/// What `msg` means for the sampler.
|
||||
fn input(hwnd: HWND, msg: u32, wparam: WPARAM, lparam: LPARAM) -> Option<Input> {
|
||||
match msg {
|
||||
WM_LBUTTONDOWN => Some(Input::Down(Button::Left)),
|
||||
WM_LBUTTONUP => Some(Input::Up(Button::Left)),
|
||||
WM_RBUTTONDOWN => Some(Input::Down(Button::Right)),
|
||||
WM_RBUTTONUP => Some(Input::Up(Button::Right)),
|
||||
WM_MBUTTONDOWN | WM_XBUTTONDOWN => Some(Input::Down(Button::Other)),
|
||||
WM_MBUTTONUP | WM_XBUTTONUP => Some(Input::Up(Button::Other)),
|
||||
WM_KEYDOWN if wparam.0 == usize::from(VK_ESCAPE.0) => Some(Input::Escape),
|
||||
WM_ACTIVATE if wparam.0 & 0xFFFF == WA_INACTIVE as usize => Some(Input::Deactivated),
|
||||
WM_ACTIVATE => Some(Input::Activated),
|
||||
// `lParam` is the window that takes the capture.
|
||||
WM_CAPTURECHANGED if lparam.0 != hwnd.0 as isize => Some(Input::CaptureLost),
|
||||
WM_CLOSE => Some(Input::Closed),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
unsafe extern "system" fn window_proc(hwnd: HWND, msg: u32, wparam: WPARAM, lparam: LPARAM) -> LRESULT {
|
||||
// Activation also gives the window the keyboard focus, for Escape.
|
||||
// SAFETY: the arguments Windows passed in, for the window on this thread.
|
||||
let result = if msg == WM_ACTIVATE { unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) } } else { LRESULT(0) };
|
||||
if let Some(input) = input(hwnd, msg, wparam, lparam) {
|
||||
match with(|s| s.press.step(input)) {
|
||||
Some(Step::Pick) => finish(hwnd, |s| pick(s, hwnd, lparam)),
|
||||
Some(Step::Cancel) => finish(hwnd, |_| Ok(None)),
|
||||
Some(Step::Wait) | None => {}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
match msg {
|
||||
WM_SETCURSOR | WM_MOUSEMOVE => {
|
||||
// The cursor is set by hand: a window with the mouse capture gets no WM_SETCURSOR.
|
||||
if let Some(cursor) = with(|s| s.cursor) {
|
||||
// SAFETY: a system cursor loaded by `run`.
|
||||
unsafe { SetCursor(Some(cursor)) };
|
||||
}
|
||||
LRESULT(1)
|
||||
}
|
||||
// The copy covers the whole window.
|
||||
WM_ERASEBKGND => LRESULT(1),
|
||||
WM_PAINT => {
|
||||
paint(hwnd);
|
||||
LRESULT(0)
|
||||
}
|
||||
// The window keeps covering the virtual screen when it reaches a monitor of another scale.
|
||||
WM_DPICHANGED => LRESULT(0),
|
||||
WM_DESTROY => {
|
||||
with(|s| s.destroyed = true);
|
||||
// SAFETY: ends this thread's message loop.
|
||||
unsafe { PostQuitMessage(0) };
|
||||
LRESULT(0)
|
||||
}
|
||||
// SAFETY: the arguments Windows passed in, for the window on this thread.
|
||||
_ => unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) },
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// `COLORREF` is `0x00bbggrr`: red in the low byte. `CLR_INVALID` and other values with the high
|
||||
/// byte set are not colors.
|
||||
#[test]
|
||||
fn colorrefs_read_as_srgb() {
|
||||
assert_eq!(srgb(0x0000_00FF), Some([1.0, 0.0, 0.0]));
|
||||
assert_eq!(srgb(0x00FF_0000), Some([0.0, 0.0, 1.0]));
|
||||
assert_eq!(srgb(0x0056_3412), Some([0x12, 0x34, 0x56].map(|v| v as f32 / 255.0)));
|
||||
assert_eq!(srgb(0), Some([0.0; 3]));
|
||||
assert_eq!(srgb(0x00FF_FFFF), Some([1.0; 3]));
|
||||
assert_eq!(srgb(CLR_INVALID), None);
|
||||
assert_eq!(srgb(0x0100_0000), None);
|
||||
}
|
||||
|
||||
/// The pointer maps to the copy's pixels through the virtual screen's corner, which is negative
|
||||
/// when a monitor is left of or above the main one. A 1920 × 1080 monitor at 100% left of and
|
||||
/// lower than a 3840 × 2160 one at 150% gives a 5760 × 2160 virtual screen from (−1920, 0), in
|
||||
/// physical pixels on both.
|
||||
#[test]
|
||||
fn screen_points_map_to_pixels_of_the_copy() {
|
||||
let s = VirtualScreen::new(-1920, 0, 5760, 2160).unwrap();
|
||||
assert_eq!(s.pixel(-1920, 0), Some((0, 0)));
|
||||
assert_eq!(s.pixel(-1, 300), Some((1919, 300)));
|
||||
assert_eq!(s.pixel(0, 0), Some((1920, 0)));
|
||||
assert_eq!(s.pixel(3839, 2159), Some((5759, 2159)));
|
||||
for (x, y) in [(-1921, 0), (3840, 0), (0, -1), (0, 2160), (i32::MIN, 0), (i32::MAX, i32::MAX)] {
|
||||
assert_eq!(s.pixel(x, y), None, "({x}, {y})");
|
||||
}
|
||||
// A monitor above the main one.
|
||||
let s = VirtualScreen::new(-200, -1440, 2760, 2520).unwrap();
|
||||
assert_eq!(s.pixel(0, 0), Some((200, 1440)));
|
||||
assert_eq!(s.pixel(-200, -1440), Some((0, 0)));
|
||||
// A virtual screen at the far corner of the coordinates maps without overflowing.
|
||||
let s = VirtualScreen::new(i32::MIN, i32::MIN, 10, 10).unwrap();
|
||||
assert_eq!(s.pixel(i32::MIN + 9, i32::MIN), Some((9, 0)));
|
||||
assert_eq!(s.pixel(i32::MAX, 0), None);
|
||||
}
|
||||
|
||||
/// The release's own point picks, with signed coordinates: left of or above the client area
|
||||
/// they are negative. Past 32,767 pixels they are widened by the message's pointer position.
|
||||
#[test]
|
||||
fn the_release_point_comes_from_the_message() {
|
||||
let lparam = |x: i32, y: i32| ((y as u16 as isize) << 16) | x as u16 as isize;
|
||||
assert_eq!(message_point(lparam(100, 200), (140, 260)), (100, 200), "the lParam point wins over a nearby position");
|
||||
assert_eq!(message_point(lparam(65_636, 0), (65_636, 0)), (65_636, 0), "MSG.pt gives the high bits past 65,535 pixels");
|
||||
assert_eq!(message_point(lparam(100, 0), (100, 0)), (100, 0));
|
||||
assert_eq!(message_point(lparam(-5, -1), (10, 10)), (-5, -1));
|
||||
assert_eq!(message_point(lparam(0, 0), (0, 0)), (0, 0));
|
||||
assert_eq!(message_point(lparam(32_767, -32_768), (32_767, -32_768)), (32_767, -32_768));
|
||||
assert_eq!(message_point(lparam(40_010, 2_000), (40_000, 2_100)), (40_010, 2_000), "eight 8K monitors in a row");
|
||||
assert_eq!(message_point(lparam(61_439, 0), (61_000, 0)), (61_439, 0));
|
||||
assert_eq!(message_point(lparam(32_770, 0), (32_760, 0)), (32_770, 0));
|
||||
// A negative `lParam` on 64-bit Windows keeps only its low 32 bits as the point.
|
||||
assert_eq!(message_point(lparam(-3, -4) | !0xFFFF_FFFF, (0, 0)), (-3, -4));
|
||||
assert_eq!(message_point(lparam(5, 5), (i32::MAX, i32::MIN)), (i32::MAX, i32::MIN + 5), "saturates at the coordinate range");
|
||||
}
|
||||
|
||||
/// The size is checked before the copy is made: an empty, negative, oversized or out-of-range
|
||||
/// virtual screen is an error.
|
||||
#[test]
|
||||
fn the_copy_size_is_checked_first() {
|
||||
assert!(VirtualScreen::new(0, 0, 7680 * 8, 4320).is_ok(), "eight 8K monitors in a row");
|
||||
for (left, top, width, height) in [
|
||||
(0, 0, 0, 1080),
|
||||
(0, 0, 1920, 0),
|
||||
(0, 0, -1920, 1080),
|
||||
(0, 0, 7680 * 8, 4370),
|
||||
(0, 0, i32::MAX, i32::MAX),
|
||||
(i32::MAX - 100, 0, 1920, 1080),
|
||||
(0, i32::MAX - 100, 1920, 1080),
|
||||
] {
|
||||
assert!(VirtualScreen::new(left, top, width, height).is_err(), "{left} {top} {width} {height}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A left click picks when it is released; Escape, a click of any other button, closing the
|
||||
/// window and losing the mouse cancel; losing the focus cancels once the window had it. A
|
||||
/// release whose press began elsewhere does nothing.
|
||||
#[test]
|
||||
fn clicks_and_keys_pick_or_cancel() {
|
||||
let run = |inputs: &[Input]| {
|
||||
let mut press = Press::default();
|
||||
inputs.iter().map(|&i| press.step(i)).find(|&s| s != Step::Wait).unwrap_or(Step::Wait)
|
||||
};
|
||||
use Input::{Activated, CaptureLost, Closed, Deactivated, Escape};
|
||||
let (left_down, left_up) = (Input::Down(Button::Left), Input::Up(Button::Left));
|
||||
let (right_down, right_up) = (Input::Down(Button::Right), Input::Up(Button::Right));
|
||||
let (other_down, other_up) = (Input::Down(Button::Other), Input::Up(Button::Other));
|
||||
assert_eq!(run(&[Activated, left_down, left_up]), Step::Pick);
|
||||
assert_eq!(run(&[left_down, left_up]), Step::Pick, "a window that never became active still takes a click");
|
||||
assert_eq!(run(&[Activated, right_down, right_up]), Step::Cancel);
|
||||
assert_eq!(run(&[Activated, other_down, other_up]), Step::Cancel, "the middle and side buttons cancel");
|
||||
assert_eq!(run(&[Activated, other_down, left_up]), Step::Wait);
|
||||
assert_eq!(run(&[Activated, Escape]), Step::Cancel);
|
||||
assert_eq!(run(&[Activated, Deactivated]), Step::Cancel);
|
||||
assert_eq!(run(&[Deactivated]), Step::Wait);
|
||||
assert_eq!(run(&[CaptureLost]), Step::Cancel);
|
||||
assert_eq!(run(&[Closed]), Step::Cancel);
|
||||
assert_eq!(run(&[Activated, left_up, right_up, other_up]), Step::Wait, "releases of presses made before the window showed");
|
||||
assert_eq!(run(&[left_down, right_down, left_up]), Step::Wait, "the right button replaced the left one");
|
||||
assert_eq!(run(&[right_down, left_down, left_up]), Step::Pick);
|
||||
}
|
||||
}
|
||||
+238
-1
@@ -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, ¤t));
|
||||
}
|
||||
}
|
||||
}
|
||||
// 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, ¤t);
|
||||
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),
|
||||
|
||||
@@ -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:?}");
|
||||
}
|
||||
@@ -10,6 +10,7 @@ workspace = true
|
||||
|
||||
[dependencies]
|
||||
craft-dxf = { workspace = true }
|
||||
craft-plotter = { workspace = true }
|
||||
vectorcraft-geom = { workspace = true }
|
||||
vectorcraft-color = { workspace = true }
|
||||
vectorcraft-doc = { workspace = true }
|
||||
|
||||
+2
-428
@@ -1,428 +1,2 @@
|
||||
//! The bytes of an HP-GL file as instructions: two-letter mnemonics and the parameters that follow
|
||||
//! them, read one at a time as the plot asks for them. Printer escape sequences (PCL, HP RTL, the
|
||||
//! HP-GL device-control escapes) and PJL lines around and between the instructions are skipped,
|
||||
//! with the data their escapes carry.
|
||||
|
||||
/// The end-of-text character, the default label terminator.
|
||||
pub(super) const ETX: u8 = 3;
|
||||
const ESC: u8 = 0x1b;
|
||||
|
||||
/// The most digits of a number that count: longer ones are read as their first digits.
|
||||
const MAX_DIGITS: usize = 18;
|
||||
|
||||
/// What the bytes being read hold.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Mode {
|
||||
/// HP-GL instructions.
|
||||
Hpgl,
|
||||
/// PCL or HP RTL: escape sequences and their data, nothing to draw.
|
||||
Pcl,
|
||||
/// After a Universal Exit Language: PJL lines until a language starts.
|
||||
Pjl,
|
||||
}
|
||||
|
||||
/// One item of a PE (Polyline Encoded) instruction.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub(super) enum PeItem {
|
||||
/// Select pen.
|
||||
Pen(i64),
|
||||
/// Rectangle mode: the following coordinates come in fours.
|
||||
Rect,
|
||||
/// A coordinate pair, after a pen-up flag (`up`) and an absolute flag (`absolute`).
|
||||
Point { x: f64, y: f64, up: bool, absolute: bool },
|
||||
}
|
||||
|
||||
/// The state of one PE instruction being read.
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
pub(super) struct Pe {
|
||||
seven_bit: bool,
|
||||
fraction_bits: u32,
|
||||
up: bool,
|
||||
absolute: bool,
|
||||
}
|
||||
|
||||
pub(super) struct Lexer<'a> {
|
||||
b: &'a [u8],
|
||||
at: usize,
|
||||
mode: Mode,
|
||||
/// The file holds HP RTL or PCL raster image data.
|
||||
pub raster: bool,
|
||||
}
|
||||
|
||||
/// Is `c` a byte that separates numeric parameters (or white space between instructions)?
|
||||
fn separator(c: u8) -> bool {
|
||||
matches!(c, b' ' | b',' | b'\t' | b'\r' | b'\n' | 0)
|
||||
}
|
||||
|
||||
impl<'a> Lexer<'a> {
|
||||
pub fn new(b: &'a [u8]) -> Self {
|
||||
Self { b, at: 0, mode: Mode::Hpgl, raster: false }
|
||||
}
|
||||
|
||||
fn peek(&self) -> Option<u8> {
|
||||
self.b.get(self.at).copied()
|
||||
}
|
||||
|
||||
/// Whether everything has been read.
|
||||
pub fn done(&self) -> bool {
|
||||
self.at >= self.b.len()
|
||||
}
|
||||
|
||||
/// How many bytes have been read.
|
||||
pub fn pos(&self) -> usize {
|
||||
self.at
|
||||
}
|
||||
|
||||
/// The next instruction's mnemonic, in upper case; `strict`: only white space, semicolons and
|
||||
/// escape sequences may come before it (anything else gives `None`, as the end does).
|
||||
pub fn op(&mut self, strict: bool) -> Option<[u8; 2]> {
|
||||
loop {
|
||||
let c = self.peek()?;
|
||||
if c == ESC {
|
||||
self.escape();
|
||||
continue;
|
||||
}
|
||||
match self.mode {
|
||||
Mode::Pcl => {
|
||||
self.at += 1;
|
||||
continue;
|
||||
}
|
||||
Mode::Pjl => {
|
||||
if separator(c) {
|
||||
self.at += 1;
|
||||
} else if c == b'@' {
|
||||
self.pjl_line();
|
||||
} else {
|
||||
self.mode = Mode::Hpgl;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
Mode::Hpgl => {}
|
||||
}
|
||||
let next = self.b.get(self.at + 1).copied();
|
||||
if c.is_ascii_alphabetic()
|
||||
&& let Some(n) = next.filter(u8::is_ascii_alphabetic)
|
||||
{
|
||||
self.at += 2;
|
||||
return Some([c.to_ascii_uppercase(), n.to_ascii_uppercase()]);
|
||||
}
|
||||
if strict && !(separator(c) || c == b';' || c < 0x20) {
|
||||
return None;
|
||||
}
|
||||
self.at += 1;
|
||||
}
|
||||
}
|
||||
|
||||
/// One `@PJL` line: an `ENTER LANGUAGE` command picks what follows.
|
||||
fn pjl_line(&mut self) {
|
||||
let rest = &self.b[self.at..];
|
||||
let end = rest.iter().position(|&c| c == b'\n').map_or(rest.len(), |n| n + 1);
|
||||
// A command names its language within its first 256 bytes; longer lines aren't copied.
|
||||
let line = String::from_utf8_lossy(&rest[..end.min(256)]).to_ascii_uppercase();
|
||||
if let Some(lang) = line.split_once("LANGUAGE").map(|(_, l)| l.trim_start_matches([' ', '=']).trim()) {
|
||||
self.mode = if lang.starts_with("HPGL") { Mode::Hpgl } else { Mode::Pcl };
|
||||
}
|
||||
self.at += end;
|
||||
}
|
||||
|
||||
/// An escape sequence at the current byte, with the data it carries.
|
||||
fn escape(&mut self) {
|
||||
self.at += 1;
|
||||
let Some(c) = self.peek() else { return };
|
||||
self.at += 1;
|
||||
match c {
|
||||
// Universal Exit Language (`ESC%-12345X`) and the language switches (`ESC%#B` to HP-GL,
|
||||
// `ESC%#A` to PCL or HP RTL).
|
||||
b'%' => {
|
||||
let (_, end) = self.value();
|
||||
match end {
|
||||
Some(b'X') => self.mode = Mode::Pjl,
|
||||
Some(b'B') => self.mode = Mode::Hpgl,
|
||||
Some(b'A') => self.mode = Mode::Pcl,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
// Reset: PCL follows, until a language switch.
|
||||
b'E' => self.mode = Mode::Pcl,
|
||||
// HP-GL device control: `ESC.` and a letter, with parameters up to a colon.
|
||||
b'.' => {
|
||||
let Some(kind) = self.peek() else { return };
|
||||
self.at += 1;
|
||||
if !b"()YZBEJKLORUX".contains(&kind) {
|
||||
let rest = &self.b[self.at..self.b.len().min(self.at + 80)];
|
||||
if let Some(n) = rest.iter().position(|&c| c == b':')
|
||||
&& rest[..n].iter().all(|c| c.is_ascii_digit() || matches!(c, b';' | b' ' | b','))
|
||||
{
|
||||
self.at += n + 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
// Parameterized PCL: a group character, then values each ending in a letter (upper case
|
||||
// ends the sequence); `W`, `*b…V` (raster data by plane) and `&p…X` (transparent print
|
||||
// data) are followed by that many bytes of data. Without a group character (`ESC(8U`,
|
||||
// `ESC)0N`), one value and the letter ending it.
|
||||
0x21..=0x2f => {
|
||||
let Some(group) = self.peek().filter(|g| (0x60..=0x7e).contains(g)) else {
|
||||
self.value();
|
||||
return;
|
||||
};
|
||||
self.at += 1;
|
||||
loop {
|
||||
let (v, end) = self.value();
|
||||
let Some(end) = end else { return };
|
||||
let upper = end.to_ascii_uppercase();
|
||||
if upper == b'W' || (c, group, upper) == (b'*', b'b', b'V') || (c, group, upper) == (b'&', b'p', b'X') {
|
||||
let n = v.max(0.0).min((self.b.len() - self.at) as f64) as usize;
|
||||
if (c, group) == (b'*', b'b') && n > 0 {
|
||||
self.raster = true;
|
||||
}
|
||||
self.at += n;
|
||||
}
|
||||
if (c, group, end) == (b'*', b'r', b'A') {
|
||||
self.raster = true;
|
||||
}
|
||||
if !end.is_ascii_lowercase() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
// A two-character escape.
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// A PCL value (`[+-]digits[.digits]`, any part missing) and the character that ends it; `None`
|
||||
/// when that is not a letter or `@` (which is then left unread).
|
||||
fn value(&mut self) -> (f64, Option<u8>) {
|
||||
let v = self.number_here().unwrap_or(0.0);
|
||||
match self.peek() {
|
||||
Some(c) if c.is_ascii_alphabetic() || c == b'@' => {
|
||||
self.at += 1;
|
||||
(v, Some(c))
|
||||
}
|
||||
_ => (v, None),
|
||||
}
|
||||
}
|
||||
|
||||
/// A number starting at the current byte (`[+-]digits[.digits]`), `None` when it has no digit
|
||||
/// (its sign and point are read all the same).
|
||||
fn number_here(&mut self) -> Option<f64> {
|
||||
let mut neg = false;
|
||||
if let Some(c @ (b'+' | b'-')) = self.peek() {
|
||||
neg = c == b'-';
|
||||
self.at += 1;
|
||||
}
|
||||
let (mut v, mut digits, mut scale) = (0.0f64, 0usize, 1.0f64);
|
||||
let mut point = false;
|
||||
while let Some(c) = self.peek() {
|
||||
if c.is_ascii_digit() {
|
||||
if digits < MAX_DIGITS {
|
||||
if point {
|
||||
scale /= 10.0;
|
||||
v += f64::from(c - b'0') * scale;
|
||||
} else {
|
||||
v = v * 10.0 + f64::from(c - b'0');
|
||||
}
|
||||
} else if !point {
|
||||
// Past the digits that count, an integer part keeps its size.
|
||||
v *= 10.0;
|
||||
}
|
||||
digits += 1;
|
||||
} else if c == b'.' && !point {
|
||||
point = true;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
self.at += 1;
|
||||
}
|
||||
let v = v.min(f64::MAX);
|
||||
(digits > 0).then_some(if neg { -v } else { v })
|
||||
}
|
||||
|
||||
/// The next numeric parameter of the instruction being read, or `None` at its end (a semicolon
|
||||
/// ending it is read).
|
||||
pub fn number(&mut self) -> Option<f64> {
|
||||
loop {
|
||||
let c = self.peek()?;
|
||||
if separator(c) {
|
||||
self.at += 1;
|
||||
} else if c.is_ascii_digit() || matches!(c, b'+' | b'-' | b'.') {
|
||||
if let Some(v) = self.number_here() {
|
||||
return Some(v);
|
||||
}
|
||||
} else {
|
||||
if c == b';' {
|
||||
self.at += 1;
|
||||
}
|
||||
return None;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Up to `out.len()` numeric parameters into `out` (the rest are read and dropped) → how many.
|
||||
pub fn numbers(&mut self, out: &mut [f64]) -> usize {
|
||||
let mut n = 0;
|
||||
while let Some(v) = self.number() {
|
||||
if let Some(slot) = out.get_mut(n) {
|
||||
*slot = v;
|
||||
}
|
||||
n += 1;
|
||||
}
|
||||
n.min(out.len())
|
||||
}
|
||||
|
||||
/// Read and drop the parameters of the instruction being read: numbers and quoted strings.
|
||||
pub fn params(&mut self) {
|
||||
loop {
|
||||
while self.number().is_some() {}
|
||||
if self.peek() != Some(b'"') {
|
||||
return;
|
||||
}
|
||||
self.quoted();
|
||||
}
|
||||
}
|
||||
|
||||
/// Read and drop numeric parameters → whether a semicolon ended them (an instruction the reader
|
||||
/// doesn't know, written out in full).
|
||||
pub fn closed_params(&mut self) -> bool {
|
||||
while self.number().is_some() {}
|
||||
self.at > 0 && self.b.get(self.at - 1) == Some(&b';')
|
||||
}
|
||||
|
||||
/// A comment (CO): its quoted string or nothing, then the terminator or the end → whether it
|
||||
/// is one.
|
||||
pub fn comment(&mut self) -> bool {
|
||||
while self.peek().is_some_and(separator) {
|
||||
self.at += 1;
|
||||
}
|
||||
match self.peek() {
|
||||
Some(b'"') => self.quoted(),
|
||||
Some(b';') => {
|
||||
self.at += 1;
|
||||
true
|
||||
}
|
||||
None => true,
|
||||
Some(_) => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// The text of a label, up to and including `terminator` (or the end).
|
||||
pub fn label(&mut self, terminator: u8) {
|
||||
let rest = &self.b[self.at..];
|
||||
self.at += rest.iter().position(|&c| c == terminator).map_or(rest.len(), |n| n + 1);
|
||||
}
|
||||
|
||||
/// A quoted string (CO): the parameters up to its closing quote, then the terminator → whether
|
||||
/// there was one.
|
||||
pub fn quoted(&mut self) -> bool {
|
||||
while self.peek().is_some_and(separator) {
|
||||
self.at += 1;
|
||||
}
|
||||
let found = self.peek() == Some(b'"');
|
||||
if found {
|
||||
self.at += 1;
|
||||
let rest = &self.b[self.at..];
|
||||
self.at += rest.iter().position(|&c| c == b'"').map_or(rest.len(), |n| n + 1);
|
||||
}
|
||||
if self.peek() == Some(b';') {
|
||||
self.at += 1;
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
/// The character right after the mnemonic (DT, SM), `None` when it is a semicolon or the end
|
||||
/// (the semicolon is read).
|
||||
pub fn char(&mut self) -> Option<u8> {
|
||||
let c = self.peek()?;
|
||||
self.at += 1;
|
||||
(c != b';').then_some(c)
|
||||
}
|
||||
|
||||
/// The next item of a PE instruction, `None` at its end (its semicolon is read).
|
||||
pub fn pe(&mut self, st: &mut Pe) -> Option<PeItem> {
|
||||
loop {
|
||||
let raw = self.peek()?;
|
||||
let c = raw & 0x7f;
|
||||
// Spaces, deletes, control characters and bytes 128 to 160 and 255 are ignored.
|
||||
if raw <= 32 || raw == 127 || (128..=160).contains(&raw) || raw == 255 {
|
||||
self.at += 1;
|
||||
continue;
|
||||
}
|
||||
match c {
|
||||
b';' => {
|
||||
self.at += 1;
|
||||
return None;
|
||||
}
|
||||
// Flags keep their meaning with the eighth bit set; digits are 63 and up (191 and up).
|
||||
b':' | b'<' | b'>' | b'=' | b'7' | b'9' if raw < 63 || (0xb7..191).contains(&raw) => {
|
||||
self.at += 1;
|
||||
match c {
|
||||
b':' => return self.pe_value(st).map(PeItem::Pen).or_else(|| self.end_pe()),
|
||||
b'<' => st.up = true,
|
||||
b'>' => match self.pe_value(st) {
|
||||
Some(n) => st.fraction_bits = n.clamp(0, 52) as u32,
|
||||
None => return self.end_pe(),
|
||||
},
|
||||
b'=' => st.absolute = true,
|
||||
b'7' => st.seven_bit = true,
|
||||
_ => return Some(PeItem::Rect),
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
let scale = 0.5f64.powi(st.fraction_bits as i32);
|
||||
let (Some(x), Some(y)) = (self.pe_value(st), self.pe_value(st)) else { return self.end_pe() };
|
||||
let item = PeItem::Point { x: x as f64 * scale, y: y as f64 * scale, up: st.up, absolute: st.absolute };
|
||||
(st.up, st.absolute) = (false, false);
|
||||
return Some(item);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The rest of a PE instruction that can't be decoded: see [`Lexer::skip_pe`].
|
||||
fn end_pe(&mut self) -> Option<PeItem> {
|
||||
self.skip_pe();
|
||||
None
|
||||
}
|
||||
|
||||
/// The data of a PE instruction, up to and including its semicolon, unread: its data is never
|
||||
/// read as instructions.
|
||||
pub fn skip_pe(&mut self) {
|
||||
let rest = &self.b[self.at..];
|
||||
self.at += rest.iter().position(|&c| c == b';').map_or(rest.len(), |n| n + 1);
|
||||
}
|
||||
|
||||
/// One encoded PE number, `None` when the instruction ends inside it (or a byte that is no
|
||||
/// digit comes first, which is read).
|
||||
fn pe_value(&mut self, st: &Pe) -> Option<i64> {
|
||||
let (base, low, high): (u64, std::ops::RangeInclusive<u8>, std::ops::RangeInclusive<u8>) =
|
||||
if st.seven_bit { (32, 63..=94, 95..=126) } else { (64, 63..=126, 191..=254) };
|
||||
let (mut v, mut place) = (0u64, 1u64);
|
||||
loop {
|
||||
let raw = self.peek()?;
|
||||
let c = if st.seven_bit { raw & 0x7f } else { raw };
|
||||
if raw <= 32 || raw == 127 || (128..=160).contains(&raw) || raw == 255 {
|
||||
self.at += 1;
|
||||
continue;
|
||||
}
|
||||
if c == b';' {
|
||||
return None;
|
||||
}
|
||||
self.at += 1;
|
||||
let (digit, last) = if low.contains(&c) {
|
||||
(u64::from(c - 63), false)
|
||||
} else if high.contains(&c) {
|
||||
(u64::from(c - high.start()), true)
|
||||
} else {
|
||||
return None;
|
||||
};
|
||||
v = v.saturating_add(digit.saturating_mul(place));
|
||||
place = place.saturating_mul(base);
|
||||
if last {
|
||||
// The low bit is the sign.
|
||||
let n = i64::try_from(v >> 1).unwrap_or(i64::MAX);
|
||||
return Some(if v & 1 == 1 { -n } else { n });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
//! Shared HP-GL byte lexer; drawing interpretation remains local.
|
||||
pub(super) use craft_plotter::hpgl::lex::{ETX, Lexer, Pe, PeItem};
|
||||
@@ -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 => {
|
||||
|
||||
@@ -192,14 +192,23 @@ fn write_css(lib: &SwatchLibrary, keep: impl Fn(&&Swatch) -> bool) -> String {
|
||||
// A mirrored conic turns counterclockwise, and CSS only turns clockwise: its stops
|
||||
// are written mirrored about the seam instead.
|
||||
let mirrored = g.gradient.kind == GradientKind::Conic && g.geom.is_some_and(|geom| geom.is_mirrored());
|
||||
let stop = |s: &crate::GradientStop| {
|
||||
let at = if mirrored { 1.0 - s.offset } else { s.offset };
|
||||
format!("{} {}%", css_color(&s.color, s.opacity), at * 100.0)
|
||||
let stop = |&(t, c, o): &(f32, Color, f32)| {
|
||||
let at = if mirrored { 1.0 - t } else { t };
|
||||
format!("{} {}%", css_color(&c, o), at * 100.0)
|
||||
};
|
||||
// Stops that repeat or reflect run that many times across the box.
|
||||
// Stops that repeat or reflect run that many times across the box. CSS mixes
|
||||
// hex colors evenly in sRGB between two stops
|
||||
// (https://www.w3.org/TR/css-color-4/#interpolation-space), so an off-center
|
||||
// midpoint and the curve of a Perceptual or hue gradient are written as stops
|
||||
// of their own, each with its color and opacity. A gradient that would need
|
||||
// more than `MAX_SPREAD_STOPS` stops that way is written with its own stops.
|
||||
let unrolled = g.gradient.unrolled();
|
||||
let stops: Vec<String> =
|
||||
if mirrored { unrolled.stops.iter().rev().map(stop).collect() } else { unrolled.stops.iter().map(stop).collect() };
|
||||
let expanded: Vec<(f32, Color, f32)> = if unrolled.expanded().nth(crate::gradient::MAX_SPREAD_STOPS).is_none() {
|
||||
unrolled.expanded_stops()
|
||||
} else {
|
||||
unrolled.stops.iter().map(|s| (s.offset, s.color, s.opacity)).collect()
|
||||
};
|
||||
let stops: Vec<String> = if mirrored { expanded.iter().rev().map(stop).collect() } else { expanded.iter().map(stop).collect() };
|
||||
match g.gradient.kind {
|
||||
GradientKind::Radial => format!("radial-gradient(circle, {})", stops.join(", ")),
|
||||
// CSS sweeps clockwise from straight up; the angle is counted counterclockwise
|
||||
|
||||
@@ -284,6 +284,99 @@ fn css_writes_spread_gradient_swatches_with_their_stops_repeated() {
|
||||
}
|
||||
}
|
||||
|
||||
/// The color and opacity a written CSS gradient value has at `p` (0..1 along its stops), by the
|
||||
/// CSS rule (https://www.w3.org/TR/css-images-3/#coloring-gradient-line): between two stops the
|
||||
/// color mixes evenly with premultiplied alpha, in sRGB for hex colors
|
||||
/// (https://www.w3.org/TR/css-color-4/#interpolation-space); before the first stop and after the
|
||||
/// last the end colors hold.
|
||||
fn css_gradient_at(value: &str, p: f64) -> ([f64; 3], f64) {
|
||||
let list = value.split_once(", ").map_or("", |(_, rest)| rest).trim_end_matches(')');
|
||||
let stops: Vec<([f64; 3], f64, f64)> = list
|
||||
.split(", ")
|
||||
.map(|stop| {
|
||||
let (hex, at) = stop.split_once(' ').unwrap_or_else(|| panic!("stop {stop:?}"));
|
||||
let byte = |i: usize| hex.get(1 + 2 * i..3 + 2 * i).map_or(255.0, |h| f64::from(u8::from_str_radix(h, 16).unwrap()));
|
||||
let at: f64 = at.trim_end_matches('%').parse().unwrap();
|
||||
([byte(0), byte(1), byte(2)].map(|v| v / 255.0), byte(3) / 255.0, at / 100.0)
|
||||
})
|
||||
.collect();
|
||||
let p = p.clamp(stops[0].2, stops[stops.len() - 1].2);
|
||||
let i = stops.windows(2).position(|w| p <= w[1].2).unwrap_or(0);
|
||||
let ((c0, a0, p0), (c1, a1, p1)) = (stops[i], stops[i + 1]);
|
||||
let w = if p1 > p0 { (p - p0) / (p1 - p0) } else { 1.0 };
|
||||
let a = a0 + (a1 - a0) * w;
|
||||
let c = std::array::from_fn(|k| if a > 0.0 { (c0[k] * a0 + (c1[k] * a1 - c0[k] * a0) * w) / a } else { 0.0 });
|
||||
(c, a)
|
||||
}
|
||||
|
||||
/// A gradient swatch's CSS draws, by the CSS rule, the colors and opacity the swatch has: an
|
||||
/// off-center midpoint and the curve of a Perceptual or hue gradient are written as stops of their
|
||||
/// own, also on a reflected and a mirrored conic swatch.
|
||||
#[test]
|
||||
fn css_gradient_swatches_draw_their_midpoints_and_curves() {
|
||||
let check = |label: &str, gp: GradientPaint, at: &dyn Fn(f64) -> f64| {
|
||||
let lib = SwatchLibrary {
|
||||
name: "x".into(),
|
||||
swatches: vec![Swatch { name: "x".into(), paint: Paint::Gradient(Box::new(gp.clone())), global: false, spot: false }],
|
||||
groups: vec![],
|
||||
};
|
||||
let text = written(&lib, PaletteFormat::Css);
|
||||
let value = text.lines().find_map(|l| l.trim().strip_prefix("--x: ")).unwrap_or_else(|| panic!("{text}")).trim_end_matches(';');
|
||||
for i in 0..64 {
|
||||
let p = (f64::from(i) + 0.5) / 64.0;
|
||||
let (css, css_alpha) = css_gradient_at(value, p);
|
||||
let (color, opacity) = gp.gradient.sample(at(p) as f32);
|
||||
let want = color.to_rgb();
|
||||
let off = (0..3).map(|k| (css[k] - f64::from(want[k])).abs()).fold((css_alpha - f64::from(opacity)).abs(), f64::max);
|
||||
assert!(off < 2.0 / 255.0, "{label} at {p}: {css:?} {css_alpha} vs {want:?} {opacity}: {value}");
|
||||
}
|
||||
};
|
||||
let ramp = |method| Gradient {
|
||||
method,
|
||||
..Gradient::new(
|
||||
GradientKind::Linear,
|
||||
vec![GradientStop { midpoint: 0.25, ..GradientStop::new(0.0, Color::rgb8(255, 0, 0)) }, GradientStop::new(1.0, Color::rgb8(0, 0, 255))],
|
||||
)
|
||||
};
|
||||
for method in crate::GradientMethod::ALL {
|
||||
check(&format!("{method:?}"), GradientPaint::new(ramp(method)), &|p| p);
|
||||
}
|
||||
// Opacity through an off-center midpoint, on one color so premultiplying does not change it.
|
||||
let fade = Gradient::new(
|
||||
GradientKind::Linear,
|
||||
vec![
|
||||
GradientStop { midpoint: 0.25, ..GradientStop::new(0.0, Color::BLACK) },
|
||||
GradientStop { opacity: 0.0, ..GradientStop::new(1.0, Color::BLACK) },
|
||||
],
|
||||
);
|
||||
check("fade", GradientPaint::new(fade), &|p| p);
|
||||
let reflected = Gradient { spread: crate::GradientSpread::Reflect, repeats: 2, ..ramp(crate::GradientMethod::Classic) };
|
||||
let spread = reflected.spreader();
|
||||
check("reflect", GradientPaint::new(reflected), &spread);
|
||||
let mut conic = GradientPaint::new(Gradient { kind: GradientKind::Conic, ..ramp(crate::GradientMethod::HueClockwise) });
|
||||
conic.geom = Some(crate::GradientGeom { start: kurbo::Point::ZERO, end: kurbo::Point::new(0.0, -10.0), aspect: -1.0, focal: None });
|
||||
check("mirrored conic", conic, &|p| 1.0 - p);
|
||||
}
|
||||
|
||||
/// A gradient swatch whose curve would need more than `MAX_SPREAD_STOPS` stops is written with its
|
||||
/// own stops.
|
||||
#[test]
|
||||
fn css_gradient_swatches_keep_their_stop_count_bounded() {
|
||||
let n = 4000;
|
||||
let stops = (0..n)
|
||||
.map(|i| GradientStop::new(i as f32 / (n - 1) as f32, if i % 2 == 0 { Color::rgb8(255, 0, 0) } else { Color::rgb8(0, 255, 255) }))
|
||||
.collect();
|
||||
let g = Gradient { method: crate::GradientMethod::HueClockwise, ..Gradient::new(GradientKind::Linear, stops) };
|
||||
assert!(g.expanded().nth(crate::gradient::MAX_SPREAD_STOPS).is_some(), "the curve needs more stops than allowed");
|
||||
let lib = SwatchLibrary {
|
||||
name: "x".into(),
|
||||
swatches: vec![Swatch { name: "x".into(), paint: Paint::Gradient(Box::new(GradientPaint::new(g))), global: false, spot: false }],
|
||||
groups: vec![],
|
||||
};
|
||||
let text = written(&lib, PaletteFormat::Css);
|
||||
assert_eq!(text.matches('%').count(), n, "one stop for each of the gradient's own");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn holds_counts_the_swatches_each_format_writes() {
|
||||
// `sample()` holds the spot color Ink, the linear gradient Fade, the pattern Tiles and two solid colors in a group.
|
||||
|
||||
@@ -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 }
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
@@ -752,6 +752,18 @@ impl Document {
|
||||
|
||||
/// [`Document::locked_artboards`] leaving out artboard `index`.
|
||||
pub fn locked_artboards_except(&self, index: usize) -> LockedArtboards<'_> {
|
||||
self.locks_except(index, false)
|
||||
}
|
||||
|
||||
/// [`Document::locked_artboards`] starting with the symbol art boxes earlier hit tests kept
|
||||
/// ([`Document::kept_symbol_boxes`]). Kept boxes made after it keep its measurements too
|
||||
/// ([`crate::symbols::KeptBoxes::keeping`]).
|
||||
pub(crate) fn locked_artboards_kept(&self) -> LockedArtboards<'_> {
|
||||
self.locks_except(usize::MAX, true)
|
||||
}
|
||||
|
||||
/// [`Document::locked_artboards_except`], with `kept` measuring with kept art boxes.
|
||||
fn locks_except(&self, index: usize, kept: bool) -> LockedArtboards<'_> {
|
||||
// Art flush with an edge from outside can overlap it by a rounding error, as in
|
||||
// `art_bounds_on` (#1295).
|
||||
let rects: Vec<Rect> =
|
||||
@@ -770,7 +782,9 @@ impl Document {
|
||||
if let Some(layer) = self.pattern_edit.as_ref().filter(|_| !rects.is_empty()).and_then(|e| self.layers.iter().find(|l| l.id == e.layer)) {
|
||||
objects(layer, &mut pattern_art);
|
||||
}
|
||||
LockedArtboards { rects, symbols: self.symbol_boxes(), new_art: self.new_art.get(), pattern_art, held: Default::default() }
|
||||
// Nothing is measured without a locked artboard.
|
||||
let symbols = if kept && !rects.is_empty() { self.symbol_boxes_from_kept() } else { self.symbol_boxes() };
|
||||
LockedArtboards { rects, symbols, new_art: self.new_art.get(), pattern_art, held: Default::default() }
|
||||
}
|
||||
|
||||
/// Is `id` on a locked artboard ([`LockedArtboards::holds_id`])? A layer or sublayer is on none.
|
||||
|
||||
+20
-10
@@ -451,8 +451,9 @@ pub fn hit_test_visible_skipping(doc: &Document, p: Point, opt: HitOptions, skip
|
||||
/// outline, as a click there hits it.
|
||||
pub fn selected_hidden_at(doc: &Document, p: Point, opt: HitOptions, selected: &[NodeId]) -> Option<NodeId> {
|
||||
let _walk = ArtWalk::open();
|
||||
let symbols = doc.symbol_boxes();
|
||||
let locks = doc.locked_artboards();
|
||||
// The locks first: they copy the kept art boxes that `symbols` takes, and `symbols` keeps theirs.
|
||||
let locks = doc.locked_artboards_kept();
|
||||
let symbols = doc.kept_symbol_boxes().keeping(&locks.symbols);
|
||||
selected.iter().rev().copied().find(|&id| {
|
||||
let Some(chain) = doc.ancestry(id) else { return false };
|
||||
let nodes: Vec<&Node> = chain.iter().filter_map(|a| doc.node(*a)).collect();
|
||||
@@ -520,7 +521,9 @@ pub fn objects_at(doc: &Document, p: Point, opt: HitOptions, scope: Option<NodeI
|
||||
}
|
||||
let mut tops = Vec::new();
|
||||
let mut seen = HashSet::new();
|
||||
let symbols = doc.symbol_boxes();
|
||||
// The locks first: they copy the kept art boxes that `symbols` takes, and `symbols` keeps theirs.
|
||||
let locks = doc.locked_artboards_kept();
|
||||
let symbols = doc.kept_symbol_boxes().keeping(&locks.symbols);
|
||||
for layer in doc.layers.iter().rev() {
|
||||
if !layer.visible || layer.locked || layer.is_template() || doc.pattern_edit.as_ref().is_some_and(|e| e.layer != layer.id) {
|
||||
continue;
|
||||
@@ -535,7 +538,6 @@ pub fn objects_at(doc: &Document, p: Point, opt: HitOptions, scope: Option<NodeI
|
||||
}
|
||||
}
|
||||
// The objects on a locked artboard can't be selected, as `hit_test_skipping` passes over them.
|
||||
let locks = doc.locked_artboards();
|
||||
if !locks.is_empty() {
|
||||
tops.retain(|id| !doc.node(*id).is_some_and(|n| locks.holds(n)));
|
||||
}
|
||||
@@ -625,7 +627,7 @@ pub const MAX_LOCKED_AT: usize = 20;
|
||||
/// (`opt.scope`) only what is inside the isolated group or object.
|
||||
pub fn locked_objects_at(doc: &Document, p: Point, opt: HitOptions) -> Vec<NodeId> {
|
||||
let _walk = ArtWalk::open();
|
||||
let symbols = doc.symbol_boxes();
|
||||
let symbols = doc.kept_symbol_boxes();
|
||||
let mut out = Vec::new();
|
||||
if let Some(scope) = opt.scope
|
||||
&& let Some(isolated) = doc.node(scope)
|
||||
@@ -725,7 +727,7 @@ fn hit_test_skipping(doc: &Document, p: Point, opt: HitOptions, skip: &dyn Fn(No
|
||||
h.layers = h.ancestry.iter().take_while(|a| doc.node(**a).is_some_and(Node::is_layer)).count();
|
||||
h
|
||||
};
|
||||
let locks = doc.locked_artboards();
|
||||
let locks = doc.locked_artboards_kept();
|
||||
let on_locked = |id: NodeId| {
|
||||
editable_only
|
||||
&& !locks.is_empty()
|
||||
@@ -733,7 +735,8 @@ fn hit_test_skipping(doc: &Document, p: Point, opt: HitOptions, skip: &dyn Fn(No
|
||||
&& doc.node(id).is_some_and(|n| locks.holds(n))
|
||||
};
|
||||
let skip = &|id| skip(id) || on_locked(id);
|
||||
let symbols = doc.symbol_boxes();
|
||||
// `locks` copies the kept art boxes that `symbols` takes, and `symbols` keeps theirs.
|
||||
let symbols = doc.kept_symbol_boxes().keeping(&locks.symbols);
|
||||
// Isolation mode: only what is inside the isolated container hits. The art around it is
|
||||
// locked, and clicks pass through it (#833).
|
||||
if editable_only
|
||||
@@ -801,6 +804,12 @@ pub fn set_clip_region(f: ClipRegion) {
|
||||
let _ = CLIP_REGION.set(f);
|
||||
}
|
||||
|
||||
/// What the regions of clipping paths with live effects depend on outside the document: the
|
||||
/// registered [`LiveInputs`] now, and whether a [`ClipRegion`] is registered.
|
||||
pub(crate) fn clip_region_inputs() -> (u64, bool) {
|
||||
(live_inputs(), CLIP_REGION.get().is_some())
|
||||
}
|
||||
|
||||
/// Does `clip`, or anything it holds, have a visible effect of its own or on a fill or stroke? Only
|
||||
/// then can the registered [`ClipRegion`] find a geometry effect in it.
|
||||
fn has_effects(clip: &Node) -> bool {
|
||||
@@ -1620,7 +1629,7 @@ fn moved(n: &Node, xf: vectorcraft_geom::Affine) -> Node {
|
||||
pub fn symbol_part_at(doc: &Document, inst: &Node, p: Point, opt: HitOptions) -> Option<Vec<u32>> {
|
||||
let _walk = ArtWalk::open();
|
||||
let art = InstanceArt::of(doc, inst)?;
|
||||
let symbols = doc.symbol_boxes();
|
||||
let symbols = doc.kept_symbol_boxes();
|
||||
let mut path = vec![];
|
||||
let outline = opt.outline || below_preview_off(doc, inst, opt.scope);
|
||||
let find = FindPart { art: &art, p, opt, symbols: &symbols, whole_instance: false };
|
||||
@@ -2042,7 +2051,9 @@ fn previews_off(n: &Node) -> bool {
|
||||
fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, whole_compounds: bool, outline: bool) -> Vec<NodeId> {
|
||||
let _walk = ArtWalk::open();
|
||||
let mut out = Vec::new();
|
||||
let symbols = doc.symbol_boxes();
|
||||
// The locks first: they copy the kept art boxes that `symbols` takes, and `symbols` keeps theirs.
|
||||
let locks = doc.locked_artboards_kept();
|
||||
let symbols = doc.kept_symbol_boxes().keeping(&locks.symbols);
|
||||
// The objects the marquee may touch ([`Top`]).
|
||||
let tops: Vec<Top> = match scope.and_then(|s| doc.node(s)) {
|
||||
// Isolated art whose layer, or a group around it, was locked or hidden afterwards: the
|
||||
@@ -2284,7 +2295,6 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
|
||||
}
|
||||
}
|
||||
}
|
||||
let locks = doc.locked_artboards();
|
||||
for (t, r, outline, edge, drawn) in tops {
|
||||
if !t.visible || t.locked || locks.holds_id(t.id) {
|
||||
continue;
|
||||
|
||||
+107
-16
@@ -15,7 +15,8 @@ use crate::{AppearanceItem, Document, Node, NodeKind};
|
||||
pub struct Inks {
|
||||
/// Process inks C, M, Y, K (0..1).
|
||||
pub cmyk: [f32; 4],
|
||||
/// Spot ink (swatch name, tint 0..1).
|
||||
/// Spot ink (swatch name, tint 0..1). A spot ink named like a process plate ("Cyan",
|
||||
/// "Magenta", "Yellow", "Black") prints on that plate: its tint is in `cmyk` too.
|
||||
pub spot: Option<(String, f32)>,
|
||||
/// Registration: the tint (every process ink's) prints on every spot plate too.
|
||||
pub registration: bool,
|
||||
@@ -49,7 +50,20 @@ pub struct Plate {
|
||||
pub rgb: [f32; 3],
|
||||
}
|
||||
|
||||
/// The plates of `doc`: the four process plates plus one per spot swatch.
|
||||
/// Spot swatch `name` as art links to it: [`Document::swatch`] `name` when that is a spot swatch of
|
||||
/// a solid colour.
|
||||
fn spot_swatch<'a>(doc: &'a Document, name: &str) -> Option<&'a vectorcraft_color::Swatch> {
|
||||
doc.swatch(name).filter(|s| s.spot && s.paint.color().is_some())
|
||||
}
|
||||
|
||||
/// The index in [`PROCESS_PLATES`] of the process plate named `name`.
|
||||
fn process_plate(name: &str) -> Option<usize> {
|
||||
PROCESS_PLATES.iter().position(|p| *p == name)
|
||||
}
|
||||
|
||||
/// The plates of `doc`: the four process plates plus one per spot swatch that art can link to. A
|
||||
/// link names a swatch, which is the first swatch of that name ([`Document::swatch`]), so a spot
|
||||
/// swatch after another of its name, or named like a process plate, gets no plate.
|
||||
pub fn plates(doc: &Document) -> Vec<Plate> {
|
||||
let c = vectorcraft_color::cms::active();
|
||||
let mut v: Vec<Plate> = PROCESS_PLATES
|
||||
@@ -61,20 +75,29 @@ pub fn plates(doc: &Document) -> Vec<Plate> {
|
||||
Plate { name: (*n).into(), spot: false, rgb: c.cmyk_to_srgb(ink, false) }
|
||||
})
|
||||
.collect();
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
for sw in doc.swatches_iter() {
|
||||
if let (true, Paint::Solid { color, .. }) = (sw.spot, &sw.paint)
|
||||
&& !v.iter().any(|p| p.name == sw.name)
|
||||
// Only the first swatch of a name is the one [`spot_swatch`] finds.
|
||||
if !seen.insert(sw.name.as_str()) {
|
||||
continue;
|
||||
}
|
||||
if let (true, Some(color)) = (sw.spot, sw.paint.color())
|
||||
&& !PROCESS_PLATES.contains(&sw.name.as_str())
|
||||
{
|
||||
v.push(Plate { name: sw.name.clone(), spot: true, rgb: c.display_rgb(&doc.linked_color(*color, true)) });
|
||||
v.push(Plate { name: sw.name.clone(), spot: true, rgb: c.display_rgb(&doc.linked_color(color, true)) });
|
||||
}
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
/// The ink colour of spot swatch `name` as it shows ([`Document::linked_color`]).
|
||||
/// The ink colour of spot swatch `name` as it shows ([`Document::linked_color`]); `None` when
|
||||
/// [`Document::swatch`] `name` is not a spot swatch, or `name` is a process plate's, whose ink
|
||||
/// prints on that plate.
|
||||
pub fn spot_color(doc: &Document, name: &str) -> Option<Color> {
|
||||
let s = doc.swatch(name).filter(|s| s.spot)?;
|
||||
s.paint.color().map(|c| doc.linked_color(c, true))
|
||||
if process_plate(name).is_some() {
|
||||
return None;
|
||||
}
|
||||
spot_swatch(doc, name)?.paint.color().map(|c| doc.linked_color(c, true))
|
||||
}
|
||||
|
||||
/// A colour's swatch link and tint (`(swatch name, tint 0..1)`), as the colour visitors pass it.
|
||||
@@ -86,16 +109,22 @@ fn ink_amount(v: f32) -> f32 {
|
||||
}
|
||||
|
||||
/// Separate one colour into inks. A colour linked to a spot swatch prints on that plate only, at
|
||||
/// its tint; one linked to the Registration swatch prints its tint on every plate. A tint that is
|
||||
/// not a finite number prints no ink.
|
||||
/// its tint, and one linked to a spot swatch named like a process plate prints its tint on that
|
||||
/// process plate, as PDF and EPS export write it; one linked to the Registration swatch prints its
|
||||
/// tint on every plate. A tint that is not a finite number prints no ink.
|
||||
pub fn inks(doc: &Document, c: &Cms, color: &Color, link: Link, intent: Intent) -> Inks {
|
||||
if let Some((REGISTRATION, tint)) = link {
|
||||
return Inks { cmyk: [ink_amount(tint); 4], spot: None, registration: true };
|
||||
}
|
||||
if let Some((name, tint)) = link
|
||||
&& doc.swatch(name).is_some_and(|s| s.spot && s.paint.color().is_some())
|
||||
&& spot_swatch(doc, name).is_some()
|
||||
{
|
||||
return Inks { cmyk: [0.0; 4], spot: Some((name.to_string(), ink_amount(tint))), registration: false };
|
||||
let tint = ink_amount(tint);
|
||||
let mut cmyk = [0.0; 4];
|
||||
if let Some(i) = process_plate(name) {
|
||||
cmyk[i] = tint;
|
||||
}
|
||||
return Inks { cmyk, spot: Some((name.to_string(), tint)), registration: false };
|
||||
}
|
||||
Inks { cmyk: c.to_cmyk(color, intent), spot: None, registration: false }
|
||||
}
|
||||
@@ -106,11 +135,18 @@ pub type StopPlates = Option<[f32; 4]>;
|
||||
|
||||
/// [`inks`] of a colour that may print process plates `plates` with its spot tint. The plates
|
||||
/// print only beside a spot ink: a colour without a valid spot link, or linked to Registration,
|
||||
/// prints as [`inks`] separates it. A plate amount that is not a finite number prints no ink.
|
||||
/// prints as [`inks`] separates it. A spot ink named like a process plate prints its tint layered
|
||||
/// over that plate's amount; EPS export can't write that ink beside process plates in one DeviceN
|
||||
/// space, so it writes such a gradient in process colors with a warning. A plate amount that is
|
||||
/// not a finite number prints no ink.
|
||||
pub fn stop_inks(doc: &Document, c: &Cms, color: &Color, link: Link, plates: StopPlates, intent: Intent) -> Inks {
|
||||
let mut ink = inks(doc, c, color, link, intent);
|
||||
if let (Some(p), Some(_)) = (plates, &ink.spot) {
|
||||
ink.cmyk = p.map(ink_amount);
|
||||
if let (Some(p), Some((name, tint))) = (plates, &ink.spot) {
|
||||
let mut cmyk = p.map(ink_amount);
|
||||
if let Some(i) = process_plate(name) {
|
||||
cmyk[i] = 1.0 - (1.0 - cmyk[i]) * (1.0 - tint);
|
||||
}
|
||||
ink.cmyk = cmyk;
|
||||
}
|
||||
ink
|
||||
}
|
||||
@@ -201,7 +237,7 @@ pub fn map_document_colors(doc: &mut Document, f: &mut dyn FnMut(&Color, Link) -
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{NodeId, SymbolOverride};
|
||||
use vectorcraft_color::{Freeform, FreeformPoint, Gradient, GradientKind, GradientPaint, GradientStop, Swatch};
|
||||
use vectorcraft_color::{Freeform, FreeformPoint, Gradient, GradientKind, GradientPaint, GradientStop, Swatch, SwatchGroup};
|
||||
use vectorcraft_geom::Affine;
|
||||
|
||||
/// A document with spot swatch `Gold` and process swatch `Teal`.
|
||||
@@ -233,6 +269,61 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// The names of `doc`'s spot plates, in order.
|
||||
fn spot_plates(doc: &Document) -> Vec<String> {
|
||||
plates(doc).into_iter().filter(|p| p.spot).map(|p| p.name).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_spot_swatch_named_like_an_earlier_process_swatch_gets_no_plate() {
|
||||
// Art links to a swatch by name, which finds the earlier process `Teal`: the later spot
|
||||
// `Teal` in a colour group prints nothing, so it gets no plate.
|
||||
let mut d = gold_doc();
|
||||
let spot_teal = Swatch { name: "Teal".into(), paint: Paint::solid(Color::cmyk(0.9, 0.0, 0.4, 0.0)), global: true, spot: true };
|
||||
d.swatch_groups.push(SwatchGroup { name: "Inks".into(), swatches: vec![spot_teal.clone()] });
|
||||
let c = vectorcraft_color::cms::active();
|
||||
let look = Color::cmyk(0.8, 0.0, 0.3, 0.0);
|
||||
let teal = inks(&d, &c, &look, Some(("Teal", 1.0)), Intent::RelativeColorimetric);
|
||||
assert_eq!(teal, Inks { cmyk: c.to_cmyk(&look, Intent::RelativeColorimetric), spot: None, registration: false });
|
||||
let stop = stop_inks(&d, &c, &look, Some(("Teal", 1.0)), Some([0.25, 0.0, 0.4, 0.0]), Intent::RelativeColorimetric);
|
||||
assert_eq!(stop, teal, "a gradient stop linked to it separates as process too");
|
||||
assert_eq!(spot_color(&d, "Teal"), None);
|
||||
assert_eq!(spot_plates(&d), ["Gold"], "no plate for the spot swatch that no art reaches");
|
||||
// The first swatch of a name decides either way: a spot swatch first gets its plate, and a
|
||||
// later process swatch of the same name does not take it away.
|
||||
let mut d = gold_doc();
|
||||
d.swatches.retain(|s| s.name != "Teal");
|
||||
d.swatches.insert(0, spot_teal);
|
||||
let process_teal = Swatch { name: "Teal".into(), paint: Paint::solid(look), global: true, spot: false };
|
||||
d.swatch_groups.push(SwatchGroup { name: "Inks".into(), swatches: vec![process_teal] });
|
||||
assert_eq!(spot_plates(&d), ["Teal", "Gold"]);
|
||||
let teal = inks(&d, &c, &look, Some(("Teal", 0.5)), Intent::RelativeColorimetric);
|
||||
assert_eq!(teal, Inks { cmyk: [0.0; 4], spot: Some(("Teal".into(), 0.5)), registration: false });
|
||||
assert_eq!(spot_color(&d, "Teal"), Some(Color::cmyk(0.9, 0.0, 0.4, 0.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_spot_swatch_named_like_a_process_plate_prints_on_that_plate() {
|
||||
// A spot `Cyan` has the process Cyan plate's name, so art linked to it prints its tint on
|
||||
// that plate, as a Separation ink named `Cyan` in PDF and EPS export does, instead of a
|
||||
// spot amount that no plate prints.
|
||||
let mut d = gold_doc();
|
||||
let blue = Color::cmyk(1.0, 0.3, 0.0, 0.1);
|
||||
d.swatches.insert(0, Swatch { name: "Cyan".into(), paint: Paint::solid(blue), global: true, spot: true });
|
||||
let c = vectorcraft_color::cms::active();
|
||||
let ink = inks(&d, &c, &blue, Some(("Cyan", 0.5)), Intent::RelativeColorimetric);
|
||||
assert_eq!(ink, Inks { cmyk: [0.5, 0.0, 0.0, 0.0], spot: Some(("Cyan".into(), 0.5)), registration: false });
|
||||
assert_eq!((ink.on_plate("Cyan"), ink.on_plate("Magenta"), ink.on_plate("Gold")), (0.5, 0.0, 0.0));
|
||||
let nan = inks(&d, &c, &blue, Some(("Cyan", f32::NAN)), Intent::RelativeColorimetric);
|
||||
assert_eq!(nan.cmyk, [0.0; 4], "a tint that is not a number prints no ink");
|
||||
// A gradient stop's own process plates still print, with the tint layered over its Cyan.
|
||||
let stop = stop_inks(&d, &c, &blue, Some(("Cyan", 0.5)), Some([0.2, 0.4, 0.0, 0.0]), Intent::RelativeColorimetric);
|
||||
assert!((stop.on_plate("Cyan") - 0.6).abs() < 1e-6, "{stop:?}");
|
||||
assert_eq!((stop.on_plate("Magenta"), stop.on_plate("Yellow"), stop.on_plate("Black")), (0.4, 0.0, 0.0));
|
||||
assert_eq!(spot_color(&d, "Cyan"), None);
|
||||
assert_eq!(spot_plates(&d), ["Gold"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_spot_or_registration_tint_that_is_not_a_finite_number_prints_no_ink() {
|
||||
let d = gold_doc();
|
||||
|
||||
@@ -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
@@ -65,7 +65,9 @@ pub use expand::{
|
||||
#[cfg(test)]
|
||||
use mesh::grid_eval;
|
||||
pub use mesh::{Coons, GradientMesh, MeshAppearance, MeshPiece, MeshPoint, MeshQuad, default_fidelity, grid_points, nodes_bounds};
|
||||
pub use warp::{WARP_NET, WarpNet, WarpStyle, fit_piece, map_nonlinear, map_nonlinear_within, pieces, uses_net, warp_point, warp_version};
|
||||
pub use warp::{
|
||||
WARP_NET, WarpNet, WarpStyle, fit_piece, map_nonlinear, map_nonlinear_within, map_smooth_within, pieces, uses_net, warp_point, warp_version,
|
||||
};
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
@@ -88,6 +90,30 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// The smooth map takes each handle along the map's derivative, also far from the origin,
|
||||
/// where a fixed sampling step would round away (#7069): the identity map keeps a curve's
|
||||
/// handles there.
|
||||
#[test]
|
||||
fn map_smooth_within_keeps_handles_far_from_the_origin() {
|
||||
for at in [0.0, 1e13] {
|
||||
let o = Point::new(at, at);
|
||||
let curve = PathData::single(vectorcraft_geom::SubPath::new(
|
||||
vec![
|
||||
vectorcraft_geom::Anchor::with_handles(o, o, o + vectorcraft_geom::Vec2::new(0.2, 0.0)),
|
||||
vectorcraft_geom::Anchor::with_handles(
|
||||
o + vectorcraft_geom::Vec2::new(1.0, 0.5),
|
||||
o + vectorcraft_geom::Vec2::new(0.8, 0.5),
|
||||
o + vectorcraft_geom::Vec2::new(1.0, 0.5),
|
||||
),
|
||||
],
|
||||
false,
|
||||
));
|
||||
let out = map_smooth_within(&curve, 10.0, usize::MAX, |p| p);
|
||||
let (a, b) = (&curve.subpaths[0].anchors, &out.subpaths[0].anchors);
|
||||
assert!(a[0].h_out.distance(b[0].h_out) < 0.01 && a[1].h_in.distance(b[1].h_in) < 0.01, "at {at}: {:?} {:?}", b[0].h_out, b[1].h_in);
|
||||
}
|
||||
}
|
||||
|
||||
/// #3578: a non-linear map within an anchor budget splits its segments into longer pieces,
|
||||
/// down to one a segment, and matches the plain map where the budget leaves room.
|
||||
#[test]
|
||||
|
||||
@@ -497,6 +497,37 @@ pub fn map_nonlinear(path: &PathData, max_piece: f64, f: impl Fn(Point) -> Point
|
||||
/// where pieces of `max_piece` would make more, the pieces grow until they don't ([`fit_piece`]),
|
||||
/// a coarser approximation of the image curve. Geometry effects map within their anchor budget.
|
||||
pub fn map_nonlinear_within(path: &PathData, max_piece: f64, max: usize, f: impl Fn(Point) -> Point) -> PathData {
|
||||
map_pieces_within(path, max_piece, max, &f, |_, h| f(h))
|
||||
}
|
||||
|
||||
/// [`map_nonlinear_within`] with each handle mapped along `f`'s derivative at its point
|
||||
/// ([`mapped_handle`]) rather than as a point of its own: where `f` turns quickly (Twist), handles
|
||||
/// mapped as points point different ways on the two sides of a join and the curve kinks there
|
||||
/// (#7069); along the derivative, the pieces on both sides leave each join in one direction.
|
||||
pub fn map_smooth_within(path: &PathData, max_piece: f64, max: usize, f: impl Fn(Point) -> Point) -> PathData {
|
||||
map_pieces_within(path, max_piece, max, &f, |p, h| mapped_handle(&f, p, h))
|
||||
}
|
||||
|
||||
/// Handle `h` of point `p` mapped through `f`: `f(p)` plus `f`'s derivative at `p` along `h - p`
|
||||
/// (a central difference), so the image curve leaves `f(p)` the way `f` takes the curve.
|
||||
fn mapped_handle(f: &impl Fn(Point) -> Point, p: Point, h: Point) -> Point {
|
||||
let v = h - p;
|
||||
let len = v.hypot();
|
||||
// A retracted handle stays retracted, and a non-finite one has no direction to follow.
|
||||
if len.is_nan() || len <= 0.0 || len.is_infinite() {
|
||||
return f(p);
|
||||
}
|
||||
// A thousandth of the handle, or more where the coordinates are so large that so short a
|
||||
// step would round away (#7069): the samples stay a billionth of the coordinates apart, and
|
||||
// at most at the handle's own end.
|
||||
let size = p.x.abs().max(p.y.abs()).max(1.0);
|
||||
let step = (1e-3f64).max(size * 1e-9 / len).min(1.0);
|
||||
let d = (f(p + v * step) - f(p - v * step)) / (2.0 * step);
|
||||
f(p) + d
|
||||
}
|
||||
|
||||
/// [`map_nonlinear_within`]'s pieces, with `handle(point, handle)` giving each mapped handle.
|
||||
fn map_pieces_within(path: &PathData, max_piece: f64, max: usize, f: &impl Fn(Point) -> Point, handle: impl Fn(Point, Point) -> Point) -> PathData {
|
||||
let mut max_piece = max_piece.max(1e-3);
|
||||
// Each segment adds one anchor per piece past its first.
|
||||
let room = max.saturating_sub(path.anchor_count());
|
||||
@@ -516,20 +547,20 @@ pub fn map_nonlinear_within(path: &PathData, max_piece: f64, max: usize, f: impl
|
||||
let mut pending_in: Option<Point> = None;
|
||||
for i in 0..n {
|
||||
let a = &sp.anchors[i];
|
||||
let h_in = pending_in.take().unwrap_or_else(|| f(a.h_in));
|
||||
res.push(Anchor { p: f(a.p), h_in, h_out: f(a.h_out), kind: a.kind });
|
||||
let h_in = pending_in.take().unwrap_or_else(|| handle(a.p, a.h_in));
|
||||
res.push(Anchor { p: f(a.p), h_in, h_out: handle(a.p, a.h_out), kind: a.kind });
|
||||
if i < segs {
|
||||
let c = seg_cubic(sp, i);
|
||||
let k = pieces(poly_len(&c), max_piece, MAX_PIECES);
|
||||
for j in 0..k {
|
||||
let sub = c.subsegment((j as f64 / k as f64)..((j + 1) as f64 / k as f64));
|
||||
if let Some(last) = res.last_mut() {
|
||||
last.h_out = f(sub.p1);
|
||||
last.h_out = handle(sub.p0, sub.p1);
|
||||
}
|
||||
if j + 1 < k {
|
||||
res.push(Anchor { p: f(sub.p3), h_in: f(sub.p2), h_out: f(sub.p3), kind: Default::default() });
|
||||
res.push(Anchor { p: f(sub.p3), h_in: handle(sub.p3, sub.p2), h_out: f(sub.p3), kind: Default::default() });
|
||||
} else {
|
||||
pending_in = Some(f(sub.p2));
|
||||
pending_in = Some(handle(sub.p3, sub.p2));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -608,6 +608,18 @@ impl Node {
|
||||
}
|
||||
}
|
||||
|
||||
/// [`Self::walk`] that ends at the first node for which `f` returns [`std::ops::ControlFlow::Break`]: no
|
||||
/// node after it is visited, and the break is returned.
|
||||
pub fn try_walk<'a, B>(&'a self, f: &mut impl FnMut(&'a Node) -> std::ops::ControlFlow<B>) -> std::ops::ControlFlow<B> {
|
||||
f(self)?;
|
||||
if let Some(ch) = self.children() {
|
||||
for c in ch {
|
||||
c.try_walk(f)?;
|
||||
}
|
||||
}
|
||||
std::ops::ControlFlow::Continue(())
|
||||
}
|
||||
|
||||
/// Count of nodes in this subtree, ruler guides left out.
|
||||
pub fn count(&self) -> usize {
|
||||
let mut n = 0;
|
||||
|
||||
@@ -805,3 +805,31 @@ fn mapping_ruler_guide_positions_looks_at_each_child_of_nested_layers_once() {
|
||||
assert!(Arc::ptr_eq(&group.children().unwrap()[0], &twice));
|
||||
assert_eq!(calls, 0);
|
||||
}
|
||||
|
||||
/// `try_walk` visits in `walk`'s order and visits nothing after the node that breaks it: not its
|
||||
/// children, its later siblings or its ancestors' later siblings.
|
||||
#[test]
|
||||
fn try_walk_ends_at_the_break() {
|
||||
use std::ops::ControlFlow;
|
||||
let leaf = |id| Arc::new(Node::group(NodeId(id), vec![]));
|
||||
let inner = Node::group(NodeId(2), vec![leaf(3), leaf(4), leaf(5)]);
|
||||
let root = Node::group(NodeId(1), vec![Arc::new(inner), leaf(6), leaf(7)]);
|
||||
let mut all = vec![];
|
||||
root.walk(&mut |n| all.push(n.id));
|
||||
let mut seen = vec![];
|
||||
assert_eq!(
|
||||
root.try_walk(&mut |n| {
|
||||
seen.push(n.id);
|
||||
ControlFlow::<()>::Continue(())
|
||||
}),
|
||||
ControlFlow::Continue(())
|
||||
);
|
||||
assert_eq!(seen, all, "without a break it visits what walk visits, in the same order");
|
||||
seen.clear();
|
||||
let flow = root.try_walk(&mut |n| {
|
||||
seen.push(n.id);
|
||||
if n.id == NodeId(3) { ControlFlow::Break(n.id) } else { ControlFlow::Continue(()) }
|
||||
});
|
||||
assert_eq!(flow, ControlFlow::Break(NodeId(3)));
|
||||
assert_eq!(seen, [NodeId(1), NodeId(2), NodeId(3)]);
|
||||
}
|
||||
+119
-7
@@ -4,7 +4,7 @@
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use vectorcraft_color::{BlendMode, Color, Paint};
|
||||
use vectorcraft_color::{BlendMode, Color, GradientKind, Paint};
|
||||
|
||||
use crate::{Document, Node, NodeId, NodeKind};
|
||||
|
||||
@@ -46,14 +46,21 @@ impl Default for OverprintBlack {
|
||||
}
|
||||
|
||||
impl OverprintBlack {
|
||||
/// Whether `p` is black: a solid colour (linked to one of the spot swatches `spots` only with
|
||||
/// [`Self::spot`]), or a gradient whose every stop is.
|
||||
/// Whether `p` is black: a solid color (linked to one of the spot swatches `spots` only with
|
||||
/// [`Self::spot`]), a gradient whose every stop is, or a freeform gradient with color points
|
||||
/// whose every point is (it draws from its points, not its stops).
|
||||
fn black(&self, p: &Paint, spots: &[String]) -> bool {
|
||||
let ink = |color: &Color, swatch: &Option<String>| {
|
||||
(self.spot || !swatch.as_ref().is_some_and(|s| spots.contains(s))) && is_black_ink(color, self.min_k, self.rich)
|
||||
};
|
||||
match p {
|
||||
Paint::Solid { color, swatch, .. } => {
|
||||
(self.spot || !swatch.as_ref().is_some_and(|s| spots.contains(s))) && is_black_ink(color, self.min_k, self.rich)
|
||||
}
|
||||
Paint::Gradient(g) => !g.gradient.stops.is_empty() && g.gradient.stops.iter().all(|s| is_black_ink(&s.color, self.min_k, self.rich)),
|
||||
Paint::Solid { color, swatch, .. } => ink(color, swatch),
|
||||
// Only a freeform gradient draws its points; another kind draws its stops whatever it holds.
|
||||
Paint::Gradient(g) => match g.freeform.as_ref().filter(|f| g.gradient.kind == GradientKind::Freeform && !f.points.is_empty()) {
|
||||
Some(f) => f.points.iter().all(|pt| is_black_ink(&pt.color, self.min_k, self.rich)),
|
||||
// Without points of its own a freeform gradient places them from its stops.
|
||||
None => !g.gradient.stops.is_empty() && g.gradient.stops.iter().all(|s| ink(&s.color, &s.swatch)),
|
||||
},
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
@@ -85,6 +92,52 @@ impl OverprintBlack {
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
/// [`Self::apply`] to every node of `a`'s subtree, copying only the nodes on the way to those
|
||||
/// that change. Returns whether anything changed.
|
||||
pub fn apply_deep(&self, a: &mut Arc<Node>, spots: &[String]) -> bool {
|
||||
match self.marked(a, spots) {
|
||||
Some(n) => {
|
||||
*a = n;
|
||||
true
|
||||
}
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// `n`'s subtree with [`Self::apply`] done to each node, when that changes anything (`None`
|
||||
/// otherwise). Each node is visited once, and only the nodes on the way to a change are copied.
|
||||
fn marked(&self, n: &Arc<Node>, spots: &[String]) -> Option<Arc<Node>> {
|
||||
let members: Vec<(usize, Arc<Node>)> =
|
||||
n.children().into_iter().flatten().enumerate().filter_map(|(i, c)| Some((i, self.marked(c, spots)?))).collect();
|
||||
if members.is_empty() && !self.changes(n, spots) {
|
||||
return None;
|
||||
}
|
||||
let mut copy = Arc::clone(n);
|
||||
let m = Arc::make_mut(&mut copy);
|
||||
self.apply(m, spots);
|
||||
if let Some(children) = m.children_mut() {
|
||||
for (i, c) in members {
|
||||
if let Some(slot) = children.get_mut(i) {
|
||||
*slot = c;
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(copy)
|
||||
}
|
||||
|
||||
/// Whether [`Self::apply`] changes a fill, stroke or character of `n` itself.
|
||||
fn changes(&self, n: &Node, spots: &[String]) -> bool {
|
||||
let on = !self.remove;
|
||||
let item = |it: &crate::AppearanceItem| {
|
||||
it.overprint() != on && (if it.is_fill() { self.fill } else { self.stroke }) && self.black(it.paint(), spots)
|
||||
};
|
||||
let run = |r: &crate::TextRun| {
|
||||
(self.fill && r.style.overprint_fill != on && self.black(&r.style.fill, spots))
|
||||
|| (self.stroke && r.style.overprint_stroke != on && self.black(&r.style.stroke, spots))
|
||||
};
|
||||
n.appearance.items.iter().any(item) || matches!(&n.kind, NodeKind::Text(t) if t.runs.iter().any(run))
|
||||
}
|
||||
}
|
||||
|
||||
impl Node {
|
||||
@@ -236,6 +289,65 @@ mod tests {
|
||||
assert!(tx.runs[0].style.overprint_fill);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_freeform_gradient_is_black_when_every_point_is() {
|
||||
use vectorcraft_color::freeform::{Freeform, FreeformPoint};
|
||||
let k = Color::cmyk(0.0, 0.0, 0.0, 1.0);
|
||||
let mut g = vectorcraft_color::GradientPaint::new(vectorcraft_color::Gradient { kind: GradientKind::Freeform, ..Default::default() });
|
||||
for s in &mut g.gradient.stops {
|
||||
s.color = k;
|
||||
}
|
||||
let points = vec![FreeformPoint::new(Point::ZERO, k), FreeformPoint::new(Point::new(10.0, 0.0), Color::cmyk(1.0, 0.0, 0.0, 0.0))];
|
||||
g.freeform = Some(Freeform { points, ..Default::default() });
|
||||
let fill = |g: &vectorcraft_color::GradientPaint| Appearance::basic(Paint::Gradient(Box::new(g.clone())), Paint::None, 0.0);
|
||||
let mut n = Node::path(NodeId(1), Default::default(), fill(&g));
|
||||
assert!(!OverprintBlack::default().apply(&mut n, &[]), "a cyan point is drawn, whatever the stops");
|
||||
// Another kind of gradient draws its black stops, not the points it still holds.
|
||||
let mut linear = g.clone();
|
||||
linear.gradient.kind = GradientKind::Linear;
|
||||
let mut n = Node::path(NodeId(1), Default::default(), fill(&linear));
|
||||
assert!(OverprintBlack::default().apply(&mut n, &[]), "a linear gradient is judged by its stops");
|
||||
if let Some(f) = &mut g.freeform {
|
||||
f.points[1].color = Color::gray(1.0);
|
||||
}
|
||||
let mut n = Node::path(NodeId(1), Default::default(), fill(&g));
|
||||
assert!(OverprintBlack::default().apply(&mut n, &[]), "every point black");
|
||||
g.freeform = Some(Freeform::default());
|
||||
let mut n = Node::path(NodeId(1), Default::default(), fill(&g));
|
||||
assert!(OverprintBlack::default().apply(&mut n, &[]), "no points: placed from the black stops");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_gradient_with_a_spot_linked_stop_is_black_only_with_spot() {
|
||||
let mut g = vectorcraft_color::GradientPaint::new(Default::default());
|
||||
for s in &mut g.gradient.stops {
|
||||
s.color = Color::cmyk(0.0, 0.0, 0.0, 1.0);
|
||||
}
|
||||
g.gradient.stops[0].swatch = Some("Ink".into());
|
||||
let k = Paint::Gradient(Box::new(g));
|
||||
let mut n = Node::path(NodeId(1), Default::default(), Appearance::basic(k, Paint::None, 0.0));
|
||||
let spots = ["Ink".to_string()];
|
||||
assert!(!OverprintBlack::default().apply(&mut n, &spots), "a stop linked to a spot swatch is not process black");
|
||||
assert!(OverprintBlack { spot: true, ..Default::default() }.apply(&mut n, &spots), "Include Spot Blacks takes it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn apply_deep_copies_only_the_nodes_that_change() {
|
||||
let k = cmyk(0.0, 0.0, 0.0, 1.0);
|
||||
let black = Arc::new(Node::path(NodeId(2), Default::default(), Appearance::basic(k, Paint::None, 0.0)));
|
||||
let cyan = Arc::new(Node::path(NodeId(3), Default::default(), Appearance::basic(cmyk(1.0, 0.0, 0.0, 0.0), Paint::None, 0.0)));
|
||||
let mut group = Arc::new(Node::group(NodeId(1), vec![black.clone(), cyan.clone()]));
|
||||
let before = group.clone();
|
||||
assert!(OverprintBlack::default().apply_deep(&mut group, &[]));
|
||||
let members = group.children().unwrap();
|
||||
assert!(members[0].appearance.fill().unwrap().overprint && !black.has_overprint(), "the copy is marked, not the original");
|
||||
assert!(Arc::ptr_eq(&members[1], &cyan), "the cyan member is shared, not copied");
|
||||
assert!(!before.has_overprint());
|
||||
let marked = group.clone();
|
||||
assert!(!OverprintBlack::default().apply_deep(&mut group, &[]), "nothing left to change");
|
||||
assert!(Arc::ptr_eq(&group, &marked), "and nothing is copied");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legacy_overprint_black_list_migrates() {
|
||||
let mut d = Document::new(100.0, 100.0);
|
||||
|
||||
+60
-13
@@ -183,23 +183,69 @@ impl Selection {
|
||||
self.key_anchor = None;
|
||||
}
|
||||
}
|
||||
/// [`Self::add`] for each of `ids` in order, going through the selected objects once.
|
||||
pub fn add_all(&mut self, ids: impl IntoIterator<Item = NodeId>) {
|
||||
self.each(ids, false);
|
||||
}
|
||||
/// [`Self::toggle`] for each of `ids` in order, going through the selected objects once. An id
|
||||
/// listed twice is removed and then added again at the end.
|
||||
pub fn toggle_all(&mut self, ids: impl IntoIterator<Item = NodeId>) {
|
||||
self.each(ids, true);
|
||||
}
|
||||
/// [`Self::add_all`], or [`Self::toggle_all`] when `toggle` is set. Each selected object slot
|
||||
/// carries the number of the activation that made it; an id's slots are kept only when they
|
||||
/// carry its current activation, so a removal drops every slot of the id at once.
|
||||
fn each(&mut self, ids: impl IntoIterator<Item = NodeId>, toggle: bool) {
|
||||
use std::collections::hash_map::{Entry, HashMap};
|
||||
let mut ids = ids.into_iter().peekable();
|
||||
if ids.peek().is_none() {
|
||||
return;
|
||||
}
|
||||
self.target = None;
|
||||
self.slices.clear();
|
||||
self.symbol_part = None;
|
||||
self.on_path_member = None;
|
||||
let mut live: HashMap<NodeId, usize> = self.objects.iter().map(|id| (*id, 0)).collect();
|
||||
let mut added: Vec<(NodeId, usize)> = Vec::new();
|
||||
let mut removed = false;
|
||||
for id in ids {
|
||||
match live.entry(id) {
|
||||
Entry::Vacant(e) => {
|
||||
let activation = added.len() + 1;
|
||||
e.insert(activation);
|
||||
added.push((id, activation));
|
||||
}
|
||||
Entry::Occupied(e) if toggle => {
|
||||
e.remove();
|
||||
removed = true;
|
||||
self.anchors.remove(&id);
|
||||
self.segments.remove(&id);
|
||||
if self.key == Some(id) {
|
||||
self.key = None;
|
||||
}
|
||||
if self.key_anchor.is_some_and(|(k, _)| k == id) {
|
||||
self.key_anchor = None;
|
||||
}
|
||||
}
|
||||
Entry::Occupied(_) => {}
|
||||
}
|
||||
}
|
||||
if removed {
|
||||
self.objects.retain(|id| live.get(id) == Some(&0));
|
||||
}
|
||||
self.objects.extend(added.into_iter().filter(|(id, n)| live.get(id) == Some(n)).map(|(id, _)| id));
|
||||
}
|
||||
/// Select slices `ids` (see [`Selection::slices`]) and nothing else.
|
||||
pub fn set_slices(&mut self, ids: impl IntoIterator<Item = NodeId>) {
|
||||
self.clear();
|
||||
for id in ids {
|
||||
if !self.slices.contains(&id) {
|
||||
self.slices.push(id);
|
||||
}
|
||||
}
|
||||
let mut seen = HashSet::new();
|
||||
self.slices.extend(ids.into_iter().filter(|id| seen.insert(*id)));
|
||||
}
|
||||
/// Select ruler guides `ids` (see [`Selection::guides`]) and nothing else.
|
||||
pub fn set_guides(&mut self, ids: impl IntoIterator<Item = NodeId>) {
|
||||
self.clear();
|
||||
for i in ids {
|
||||
if !self.guides.contains(&i) {
|
||||
self.guides.push(i);
|
||||
}
|
||||
}
|
||||
let mut seen = HashSet::new();
|
||||
self.guides.extend(ids.into_iter().filter(|id| seen.insert(*id)));
|
||||
}
|
||||
/// Add ruler guide `i` to the selection, or take it out, keeping the selected objects (a
|
||||
/// Shift-click on a guide).
|
||||
@@ -426,10 +472,11 @@ impl Selection {
|
||||
};
|
||||
let locks = doc.locked_artboards();
|
||||
ids.retain(|i| !locks.holds_id(*i));
|
||||
if ids.iter().all(|i| self.contains(*i)) {
|
||||
ids.iter().for_each(|i| self.remove(*i));
|
||||
let selected: HashSet<NodeId> = self.objects.iter().copied().collect();
|
||||
if ids.iter().all(|i| selected.contains(i)) {
|
||||
self.remove_all(ids);
|
||||
} else {
|
||||
ids.into_iter().for_each(|i| self.add(i));
|
||||
self.add_all(ids);
|
||||
}
|
||||
self.target = None;
|
||||
}
|
||||
|
||||
@@ -45,6 +45,174 @@ 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] {
|
||||
let mut s = Selection::default();
|
||||
for i in 1..=4 {
|
||||
s.add(NodeId(i));
|
||||
}
|
||||
s.anchors.insert(NodeId(2), BTreeSet::from([(0, 0), (0, 1)]));
|
||||
s.anchors.insert(NodeId(3), BTreeSet::from([(0, 2)]));
|
||||
s.key_anchor = Some((NodeId(2), (0, 0)));
|
||||
s.symbol_part = Some(SymbolPart { instance: NodeId(1), path: vec![0] });
|
||||
s.guides = vec![NodeId(10)];
|
||||
s.key_guide = Some(NodeId(10));
|
||||
let ids = if kept { [NodeId(3), NodeId(8), NodeId(3)] } else { [NodeId(2), NodeId(8), NodeId(2)] };
|
||||
let mut one_by_one = s.clone();
|
||||
for id in ids {
|
||||
one_by_one.remove(id);
|
||||
}
|
||||
let mut all = s.clone();
|
||||
all.remove_all(ids);
|
||||
assert_eq!(all, one_by_one);
|
||||
assert_eq!(all.key_anchor.is_some(), kept);
|
||||
assert_eq!((all.symbol_part.clone(), all.guides.clone(), all.key_guide), (None, vec![NodeId(10)], Some(NodeId(10))));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn guides_are_selected_on_their_own() {
|
||||
let mut s = Selection::default();
|
||||
|
||||
+239
-5
@@ -8,6 +8,7 @@
|
||||
//! change; [`Document::map_paints`] replaces whole paints of any kind in the same places.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::ops::ControlFlow;
|
||||
use std::sync::Arc;
|
||||
|
||||
use vectorcraft_color::swatch::REGISTRATION;
|
||||
@@ -340,18 +341,39 @@ fn map_style_paint(attrs: &mut serde_json::Map<String, serde_json::Value>, key:
|
||||
/// and gradient stops (with their link), a dynamic symbol instance's own paints
|
||||
/// ([`override_paints`]), then mesh points (unlinked), in paint order.
|
||||
pub fn node_colors(n: &Node, f: &mut dyn FnMut(&Color, Option<&str>)) {
|
||||
n.walk(&mut |m| {
|
||||
let _ = try_node_colors::<()>(n, &mut |c, s| {
|
||||
f(c, s);
|
||||
ControlFlow::Continue(())
|
||||
});
|
||||
}
|
||||
|
||||
/// Whether the subtree of `n` holds any color [`node_colors`] visits. It stops at the first one.
|
||||
pub fn node_has_colors(n: &Node) -> bool {
|
||||
try_node_colors(n, &mut |_, _| ControlFlow::Break(())).is_break()
|
||||
}
|
||||
|
||||
/// [`node_colors`] that ends at the first color for which `f` returns [`ControlFlow::Break`]: no
|
||||
/// paint or node after it is visited.
|
||||
fn try_node_colors<B>(n: &Node, f: &mut dyn FnMut(&Color, Option<&str>) -> ControlFlow<B>) -> ControlFlow<B> {
|
||||
n.try_walk(&mut |m| {
|
||||
for p in node_paints(m).chain(override_paints(m)) {
|
||||
match p {
|
||||
Paint::Solid { color, swatch, .. } => f(color, swatch.as_deref()),
|
||||
Paint::Gradient(g) => g.gradient.stops.iter().for_each(|s| f(&s.color, s.swatch.as_deref())),
|
||||
Paint::Solid { color, swatch, .. } => f(color, swatch.as_deref())?,
|
||||
Paint::Gradient(g) => {
|
||||
for s in &g.gradient.stops {
|
||||
f(&s.color, s.swatch.as_deref())?;
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if let NodeKind::Mesh(mesh) = &m.kind {
|
||||
mesh.points.iter().for_each(|p| f(&p.color, None));
|
||||
for p in &mesh.points {
|
||||
f(&p.color, None)?;
|
||||
}
|
||||
}
|
||||
});
|
||||
ControlFlow::Continue(())
|
||||
})
|
||||
}
|
||||
|
||||
fn item_paint(it: &AppearanceItem) -> &Paint {
|
||||
@@ -821,4 +843,216 @@ mod tests {
|
||||
node_colors(d.node(b).unwrap(), &mut |c, s| colors.push((*c, s.map(str::to_string))));
|
||||
assert_eq!(colors, [(Color::rgb(1.0, 0.0, 0.0), None)]);
|
||||
}
|
||||
|
||||
/// The colors [`node_colors`] visits, in its order, by a [`Node::walk`] that reads the whole subtree.
|
||||
fn full_walk(n: &Node, f: &mut dyn FnMut(&Color, Option<&str>)) {
|
||||
n.walk(&mut |m| {
|
||||
for p in node_paints(m).chain(override_paints(m)) {
|
||||
match p {
|
||||
Paint::Solid { color, swatch, .. } => f(color, swatch.as_deref()),
|
||||
Paint::Gradient(g) => g.gradient.stops.iter().for_each(|s| f(&s.color, s.swatch.as_deref())),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if let NodeKind::Mesh(mesh) = &m.kind {
|
||||
mesh.points.iter().for_each(|p| f(&p.color, None));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Whether [`full_walk`] finds a color in `n`.
|
||||
fn full_walk_has_colors(n: &Node) -> bool {
|
||||
let mut found = false;
|
||||
full_walk(n, &mut |_, _| found = true);
|
||||
found
|
||||
}
|
||||
|
||||
/// The colors of `n` by [`full_walk`], in order.
|
||||
fn full_walk_colors(n: &Node) -> Vec<(Color, Option<String>)> {
|
||||
let mut out = vec![];
|
||||
full_walk(n, &mut |c, s| out.push((*c, s.map(str::to_string))));
|
||||
out
|
||||
}
|
||||
|
||||
fn square(id: u64, fill: Paint, stroke: Paint) -> Node {
|
||||
Node::path(NodeId(id), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::basic(fill, stroke, 1.0))
|
||||
}
|
||||
|
||||
fn holder(id: u64, kind: fn(Vec<Arc<Node>>) -> NodeKind, children: Vec<Node>) -> Node {
|
||||
Node::new(NodeId(id), kind(children.into_iter().map(Arc::new).collect()))
|
||||
}
|
||||
|
||||
/// One node of each kind of paint [`node_colors`] reads or skips, with whether it shows a color.
|
||||
fn color_cases() -> Vec<(&'static str, Node, bool)> {
|
||||
let red = Paint::solid(Color::rgb(1.0, 0.0, 0.0));
|
||||
let gradient = |stops: usize| {
|
||||
let mut g = vectorcraft_color::Gradient::default();
|
||||
g.stops.truncate(stops);
|
||||
Paint::Gradient(Box::new(vectorcraft_color::GradientPaint::new(g)))
|
||||
};
|
||||
let pattern = Paint::Pattern { pattern: "Dots".into(), xf: vectorcraft_geom::Affine::IDENTITY };
|
||||
let area = shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0));
|
||||
let mesh = crate::GradientMesh::for_path_with(&area, 2, 2, &|_| (Color::BLACK, 1.0)).unwrap();
|
||||
let mut empty_mesh = mesh.clone();
|
||||
empty_mesh.points.clear();
|
||||
let text = |fill: Paint| {
|
||||
let style = crate::CharStyle { fill, stroke: Paint::None, ..Default::default() };
|
||||
let mut n =
|
||||
Node::new(NodeId(20), NodeKind::Text(Box::new(crate::TextObject::point(vectorcraft_geom::Point::new(0.0, 0.0), "Hi", style))));
|
||||
n.appearance = Appearance::basic(Paint::None, Paint::None, 0.0).into();
|
||||
n
|
||||
};
|
||||
let image = |colorize: Option<Paint>| {
|
||||
let im = crate::ImageObject {
|
||||
key: "k".into(),
|
||||
width: 2,
|
||||
height: 2,
|
||||
xf: vectorcraft_geom::Affine::IDENTITY,
|
||||
link: None,
|
||||
placement: Default::default(),
|
||||
pixels: None,
|
||||
};
|
||||
let mut n = Node::new(NodeId(21), NodeKind::Image(Box::new(im)));
|
||||
n.appearance = Appearance::basic(Paint::None, Paint::None, 0.0).into();
|
||||
n.extras_mut().colorize = colorize.map(Box::new);
|
||||
n
|
||||
};
|
||||
let overridden = |fill: Option<Paint>| {
|
||||
let mut n = square(22, Paint::None, Paint::None);
|
||||
n.extras_mut().symbol_overrides = vec![crate::SymbolOverride { path: vec![0], fill, ..Default::default() }];
|
||||
n
|
||||
};
|
||||
let masked = {
|
||||
let mut n = square(23, Paint::None, Paint::None);
|
||||
n.extras_mut().mask = Some(Box::new(crate::OpacityMask::new(square(24, red.clone(), Paint::None), true)));
|
||||
n
|
||||
};
|
||||
let group = |children| NodeKind::Group { children, clip: false };
|
||||
let clip = |children| NodeKind::Group { children, clip: true };
|
||||
let compound = |children| NodeKind::Compound { children, rule: Default::default() };
|
||||
let blend = |children| NodeKind::Blend { children, spec: Default::default() };
|
||||
let blank = |id| square(id, Paint::None, Paint::None);
|
||||
vec![
|
||||
("no paint", blank(1), false),
|
||||
("solid fill", square(2, red.clone(), Paint::None), true),
|
||||
("solid stroke", square(3, Paint::None, red.clone()), true),
|
||||
("pattern only", square(4, pattern.clone(), pattern.clone()), false),
|
||||
("gradient without stops", square(5, gradient(0), Paint::None), false),
|
||||
("gradient with stops", square(6, gradient(2), Paint::None), true),
|
||||
("mesh with points", Node::new(NodeId(7), NodeKind::Mesh(mesh)), true),
|
||||
("mesh without points", Node::new(NodeId(8), NodeKind::Mesh(empty_mesh)), false),
|
||||
("text run fill", text(red.clone()), true),
|
||||
("text without paint", text(Paint::None), false),
|
||||
("image colorize", image(Some(red.clone())), true),
|
||||
("image without colorize", image(None), false),
|
||||
("image with a pattern colorize", image(Some(pattern.clone())), false),
|
||||
("symbol override fill", overridden(Some(red.clone())), true),
|
||||
("symbol override without paint", overridden(None), false),
|
||||
("color only in the opacity mask", masked, false),
|
||||
("group, color first", holder(30, group, vec![square(31, red.clone(), Paint::None), blank(32), blank(33)]), true),
|
||||
("group, color last", holder(34, group, vec![blank(35), blank(36), square(37, red.clone(), Paint::None)]), true),
|
||||
("group without color", holder(38, group, vec![blank(39), blank(40)]), false),
|
||||
("clip group", holder(41, clip, vec![blank(42), square(43, red.clone(), Paint::None)]), true),
|
||||
("compound shape", holder(44, compound, vec![blank(45), square(46, gradient(3), Paint::None)]), true),
|
||||
("blend", holder(47, blend, vec![blank(48), blank(49)]), false),
|
||||
(
|
||||
"nested groups, color deepest",
|
||||
holder(50, group, vec![blank(51), holder(52, group, vec![holder(53, group, vec![blank(54), square(55, red.clone(), Paint::None)])])]),
|
||||
true,
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn has_colors_matches_the_full_walk() {
|
||||
for (label, n, expected) in color_cases() {
|
||||
let all = full_walk_colors(&n);
|
||||
assert_eq!(node_has_colors(&n), full_walk_has_colors(&n), "{label}");
|
||||
assert_eq!(full_walk_has_colors(&n), !all.is_empty(), "{label}");
|
||||
assert_eq!(node_has_colors(&n), expected, "{label}");
|
||||
let mut listed = vec![];
|
||||
node_colors(&n, &mut |c, s| listed.push((*c, s.map(str::to_string))));
|
||||
assert_eq!(listed, all, "{label}: node_colors lists the same colors in the same order");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn has_colors_stops_at_the_first_color() {
|
||||
let red = Paint::solid(Color::rgb(1.0, 0.0, 0.0));
|
||||
let mut stops = vectorcraft_color::Gradient::default();
|
||||
stops.stops.push(stops.stops[0].clone());
|
||||
let gradient = Paint::Gradient(Box::new(vectorcraft_color::GradientPaint::new(stops)));
|
||||
let mut later = vec![square(2, gradient, red.clone())];
|
||||
later.extend((3..100).map(|id| square(id, red.clone(), red.clone())));
|
||||
let n = holder(1, |children| NodeKind::Group { children, clip: false }, later);
|
||||
let (mut colors, mut nodes) = (0, 0);
|
||||
let flow = try_node_colors(&n, &mut |_, _| {
|
||||
colors += 1;
|
||||
ControlFlow::Break(())
|
||||
});
|
||||
assert!(flow.is_break());
|
||||
assert_eq!(colors, 1, "the first gradient stop ends the walk: no later stop, stroke or object is read");
|
||||
let flow = n.try_walk(&mut |m| {
|
||||
nodes += 1;
|
||||
if node_paints(m).next().is_some() { ControlFlow::Break(()) } else { ControlFlow::Continue(()) }
|
||||
});
|
||||
assert!(flow.is_break());
|
||||
assert_eq!(nodes, 2, "the group, then its first member: none of the 97 after it");
|
||||
}
|
||||
|
||||
/// Times [`node_has_colors`] against the full walk it replaces on one group of 100,000 paths, alternating the two in
|
||||
/// one process: `cargo test --release -p vectorcraft-doc --lib -- --ignored --nocapture has_colors_timing`.
|
||||
#[test]
|
||||
#[ignore = "a timing, not a check"]
|
||||
fn has_colors_timing() {
|
||||
/// This thread's CPU time in nanoseconds on Linux; the elapsed time since `start` elsewhere.
|
||||
fn clock(start: std::time::Instant) -> u128 {
|
||||
let cpu = std::fs::read_to_string("/proc/thread-self/schedstat").ok();
|
||||
cpu.and_then(|s| s.split_whitespace().next()?.parse().ok()).unwrap_or_else(|| start.elapsed().as_nanos())
|
||||
}
|
||||
let red = Paint::solid(Color::rgb(1.0, 0.0, 0.0));
|
||||
let count = 100_000u64;
|
||||
let group = |colored: &dyn Fn(u64) -> bool| {
|
||||
let children =
|
||||
(0..count).map(|i| if colored(i) { square(i + 1, red.clone(), Paint::None) } else { square(i + 1, Paint::None, Paint::None) });
|
||||
holder(0, |children| NodeKind::Group { children, clip: false }, children.collect())
|
||||
};
|
||||
let cases = [
|
||||
("every path filled", group(&|_| true)),
|
||||
("only the last path filled", group(&|i| i == count - 1)),
|
||||
("no path filled", group(&|_| false)),
|
||||
];
|
||||
let start = std::time::Instant::now();
|
||||
println!("clock: {}", if std::fs::metadata("/proc/thread-self/schedstat").is_ok() { "thread CPU time" } else { "wall clock" });
|
||||
// The time per call of `f` on `n`: batches of calls double until one takes at least 100 ms.
|
||||
let per_call = |f: fn(&Node) -> bool, n: &Node| {
|
||||
let mut calls = 1u32;
|
||||
loop {
|
||||
let t = clock(start);
|
||||
for _ in 0..calls {
|
||||
std::hint::black_box(f(std::hint::black_box(n)));
|
||||
}
|
||||
let spent = clock(start) - t;
|
||||
if spent >= 100_000_000 || calls >= 1 << 30 {
|
||||
return (spent as f64 / f64::from(calls), calls);
|
||||
}
|
||||
calls *= 2;
|
||||
}
|
||||
};
|
||||
for (label, n) in &cases {
|
||||
assert_eq!(full_walk_has_colors(n), node_has_colors(n), "{label}");
|
||||
let (mut old, mut new) = (vec![], vec![]);
|
||||
for _ in 0..7 {
|
||||
old.push(per_call(full_walk_has_colors, n));
|
||||
new.push(per_call(node_has_colors, n));
|
||||
}
|
||||
old.sort_by(|a, b| a.0.total_cmp(&b.0));
|
||||
new.sort_by(|a, b| a.0.total_cmp(&b.0));
|
||||
let (o, nw) = (old[3], new[3]);
|
||||
println!(
|
||||
"{label}: full walk {:.1} ns per call ({} calls), node_has_colors {:.1} ns per call ({} calls), median of 7 runs",
|
||||
o.0, o.1, nw.0, nw.1
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
+455
-10
@@ -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
|
||||
@@ -107,6 +107,134 @@ pub struct SymbolBoxes<'a> {
|
||||
consulted: RefCell<Option<HashSet<String>>>,
|
||||
}
|
||||
|
||||
/// What the art boxes and nesting depths of a document's symbols depend on: each symbol's name and
|
||||
/// art, the symbols' 9-slice guides (which symbols' art holds instances placed through guides), and
|
||||
/// the inputs of the live geometry effects of clipping paths ([`crate::hit::set_clip_region`]).
|
||||
/// Symbol sizes only move art placed through guides, which is measured on each call. Each symbol's
|
||||
/// art is held by a weak pointer. While a weak pointer to an art's allocation is held, nothing else
|
||||
/// can be at that address, and the art can't be changed in place (`Arc::make_mut` moves it), so art
|
||||
/// changed in any way no longer matches, as in the cache of `Document::inline_cycles`.
|
||||
struct KeptKey {
|
||||
symbols: Vec<(String, std::sync::Weak<Node>)>,
|
||||
guides: Option<serde_json::Value>,
|
||||
inputs: (u64, bool),
|
||||
}
|
||||
|
||||
impl KeptKey {
|
||||
/// The key of the document's 9-slice guides.
|
||||
const GUIDES: &str = crate::symbol_nine_slice::SYMBOL_NINE_SLICE;
|
||||
|
||||
fn of(doc: &Document, inputs: (u64, bool)) -> Self {
|
||||
KeptKey {
|
||||
symbols: doc.symbols.iter().map(|s| (s.name.clone(), Arc::downgrade(&s.art))).collect(),
|
||||
guides: doc.unknown.get(Self::GUIDES).cloned(),
|
||||
inputs,
|
||||
}
|
||||
}
|
||||
|
||||
/// Does this describe `doc`'s symbols as they are now, with inputs `inputs`?
|
||||
fn is_of(&self, doc: &Document, inputs: (u64, bool)) -> bool {
|
||||
self.inputs == inputs
|
||||
&& self.symbols.len() == doc.symbols.len()
|
||||
&& self.symbols.iter().zip(&doc.symbols).all(|((name, art), s)| std::ptr::eq(art.as_ptr(), Arc::as_ptr(&s.art)) && *name == s.name)
|
||||
&& self.guides.as_ref() == doc.unknown.get(Self::GUIDES)
|
||||
}
|
||||
|
||||
fn same(&self, other: &KeptKey) -> bool {
|
||||
self.inputs == other.inputs
|
||||
&& self.symbols.len() == other.symbols.len()
|
||||
&& self.symbols.iter().zip(&other.symbols).all(|((n, a), (m, b))| a.ptr_eq(b) && n == m)
|
||||
&& self.guides == other.guides
|
||||
}
|
||||
}
|
||||
|
||||
/// Art boxes, nesting depths and the name index measured by boxes made by
|
||||
/// [`Document::kept_symbol_boxes`], kept for the next ones made for the same symbols.
|
||||
struct Kept {
|
||||
key: KeptKey,
|
||||
names: Option<Arc<SymbolNames>>,
|
||||
measured: HashMap<String, Option<ArtBox>>,
|
||||
depths: HashMap<String, Option<usize>>,
|
||||
}
|
||||
|
||||
/// How many sets of symbols [`Document::kept_symbol_boxes`] keeps measurements for on each thread:
|
||||
/// clicks can alternate between two open documents.
|
||||
const KEPT_SETS: usize = 2;
|
||||
|
||||
thread_local! {
|
||||
/// The measurements [`Document::kept_symbol_boxes`] keeps, the latest first.
|
||||
static KEPT: RefCell<Vec<Kept>> = const { RefCell::new(Vec::new()) };
|
||||
}
|
||||
|
||||
/// [`SymbolBoxes`] made by [`Document::kept_symbol_boxes`], which keep their measurements for the
|
||||
/// next ones when dropped.
|
||||
pub(crate) struct KeptBoxes<'a> {
|
||||
boxes: SymbolBoxes<'a>,
|
||||
/// What the measurements depend on, under which they are kept.
|
||||
key: Option<KeptKey>,
|
||||
/// Other boxes of the same document whose measurements are kept with these
|
||||
/// ([`Self::keeping`]).
|
||||
also: Option<&'a SymbolBoxes<'a>>,
|
||||
}
|
||||
|
||||
impl<'a> std::ops::Deref for KeptBoxes<'a> {
|
||||
type Target = SymbolBoxes<'a>;
|
||||
|
||||
fn deref(&self) -> &SymbolBoxes<'a> {
|
||||
&self.boxes
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> KeptBoxes<'a> {
|
||||
/// These boxes, which also keep the art boxes and nesting depths `other` has measured when
|
||||
/// dropped. `other` measures the same document, as the boxes of
|
||||
/// [`Document::locked_artboards_kept`] do.
|
||||
pub(crate) fn keeping(mut self, other: &'a SymbolBoxes<'a>) -> Self {
|
||||
self.also = Some(other);
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for KeptBoxes<'_> {
|
||||
/// Keeps the measurements, adding them to those kept for the same symbols by other boxes alive
|
||||
/// at the same time. Art boxes of symbols whose art holds instances of symbols with 9-slice
|
||||
/// guides are left out: measuring them places art within a budget the boxes share
|
||||
/// ([`SymbolBoxes::sliced_visual`]).
|
||||
fn drop(&mut self) {
|
||||
let Some(key) = self.key.take() else { return };
|
||||
let b = &self.boxes;
|
||||
let mut measured = b.measured.take();
|
||||
let mut depths = b.depths.take();
|
||||
if let Some(other) = self.also {
|
||||
for (name, a) in other.measured.borrow().iter() {
|
||||
measured.entry(name.clone()).or_insert(*a);
|
||||
}
|
||||
for (name, d) in other.depths.borrow().iter() {
|
||||
depths.entry(name.clone()).or_insert(*d);
|
||||
}
|
||||
}
|
||||
measured.retain(|_, a| a.is_none_or(|a| !a.sliced));
|
||||
let mut kept = Kept { key, names: b.names.get().cloned(), measured, depths };
|
||||
// Nothing is kept while the thread ends or the list is in use.
|
||||
let _ = KEPT.try_with(|k| {
|
||||
if let Ok(mut k) = k.try_borrow_mut() {
|
||||
if let Some(i) = k.iter().position(|e| e.key.same(&kept.key)) {
|
||||
let other = k.remove(i);
|
||||
kept.names = kept.names.or(other.names);
|
||||
for (name, a) in other.measured {
|
||||
kept.measured.entry(name).or_insert(a);
|
||||
}
|
||||
for (name, d) in other.depths {
|
||||
kept.depths.entry(name).or_insert(d);
|
||||
}
|
||||
}
|
||||
k.insert(0, kept);
|
||||
k.truncate(KEPT_SETS);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
impl Document {
|
||||
/// [`SymbolBoxes`] for this document's symbols, none measured yet.
|
||||
pub fn symbol_boxes(&self) -> SymbolBoxes<'_> {
|
||||
@@ -131,10 +259,60 @@ impl Document {
|
||||
}
|
||||
}
|
||||
|
||||
/// [`Self::symbol_boxes`] that start with the art boxes, nesting depths and name index measured
|
||||
/// by the last such boxes made on this thread for the same symbols, and keep theirs for the next
|
||||
/// ones when dropped. The measurements are made again when a symbol's name or art, the symbols'
|
||||
/// 9-slice guides, or the inputs of the live geometry effects of clipping paths have
|
||||
/// changed since. Measurements for the last [`KEPT_SETS`] sets of symbols are kept.
|
||||
pub(crate) fn kept_symbol_boxes(&self) -> KeptBoxes<'_> {
|
||||
self.kept_boxes(false)
|
||||
}
|
||||
|
||||
/// [`Self::symbol_boxes`] that start with a copy of the measurements
|
||||
/// [`Self::kept_symbol_boxes`] would start with, and keep nothing themselves.
|
||||
pub(crate) fn symbol_boxes_from_kept(&self) -> SymbolBoxes<'_> {
|
||||
let mut kept = self.kept_boxes(true);
|
||||
kept.key = None;
|
||||
std::mem::replace(&mut kept.boxes, self.symbol_boxes())
|
||||
}
|
||||
|
||||
/// [`Self::kept_symbol_boxes`], taking the kept measurements, or with `copy` copying them.
|
||||
fn kept_boxes(&self, copy: bool) -> KeptBoxes<'_> {
|
||||
let mut boxes = self.symbol_boxes();
|
||||
let inputs = crate::hit::clip_region_inputs();
|
||||
let found = KEPT
|
||||
.try_with(|k| {
|
||||
let mut k = k.try_borrow_mut().ok()?;
|
||||
let i = k.iter().position(|e| e.key.is_of(self, inputs))?;
|
||||
if copy {
|
||||
let e = k.get(i)?;
|
||||
let key = KeptKey { symbols: e.key.symbols.clone(), guides: e.key.guides.clone(), inputs };
|
||||
Some(Kept { key, names: e.names.clone(), measured: e.measured.clone(), depths: e.depths.clone() })
|
||||
} else {
|
||||
Some(k.remove(i))
|
||||
}
|
||||
})
|
||||
.ok()
|
||||
.flatten();
|
||||
let key = match found {
|
||||
Some(e) => {
|
||||
if let Some(names) = e.names {
|
||||
// The boxes were just made, so no index is set yet.
|
||||
let _ = boxes.names.set(names);
|
||||
}
|
||||
*boxes.measured.get_mut() = e.measured;
|
||||
*boxes.depths.get_mut() = e.depths;
|
||||
e.key
|
||||
}
|
||||
None => KeptKey::of(self, inputs),
|
||||
};
|
||||
KeptBoxes { boxes, key: Some(key), also: None }
|
||||
}
|
||||
|
||||
/// 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() {
|
||||
@@ -144,10 +322,21 @@ 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) };
|
||||
/// How many art boxes [`SymbolBoxes::art`] has measured on this thread.
|
||||
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> {
|
||||
@@ -156,6 +345,16 @@ impl<'a> SymbolBoxes<'a> {
|
||||
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 {
|
||||
@@ -163,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
|
||||
@@ -218,6 +422,8 @@ impl<'a> SymbolBoxes<'a> {
|
||||
pub(crate) fn art(&self, name: &str) -> Option<ArtBox> {
|
||||
let cached = self.measured.borrow().get(name).copied();
|
||||
let b = cached.unwrap_or_else(|| {
|
||||
#[cfg(test)]
|
||||
ART_BOXES_MEASURED.with(|c| c.set(c.get() + 1));
|
||||
let b = self.measure_art(name, |art| self.in_art(|| art_box(art, self))).flatten();
|
||||
self.measured.borrow_mut().insert(name.to_string(), b);
|
||||
b
|
||||
@@ -584,10 +790,10 @@ fn art_box(art: &Arc<Node>, symbols: &SymbolBoxes) -> Option<ArtBox> {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_geom::shapes;
|
||||
use vectorcraft_geom::{Point, shapes};
|
||||
|
||||
use super::*;
|
||||
use crate::{Appearance, Symbol};
|
||||
use crate::{Appearance, NodeId, Symbol};
|
||||
|
||||
/// A rectangle filled black, with a `stroke` pt black stroke (0: none).
|
||||
fn rect(d: &mut Document, r: Rect, stroke: f64) -> Node {
|
||||
@@ -722,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
|
||||
@@ -911,4 +1168,192 @@ mod tests {
|
||||
assert_eq!(s.effects_reach("Leaf", [2.0, 0.0, 0.0, 2.0], &measure(7.0)), 7.0);
|
||||
assert_eq!(runs.get(), MAX_REACHES + 2);
|
||||
}
|
||||
|
||||
/// How many art boxes `f` measures on this thread.
|
||||
fn art_boxes_measured(f: impl FnOnce()) -> usize {
|
||||
let before = ART_BOXES_MEASURED.with(Cell::get);
|
||||
f();
|
||||
ART_BOXES_MEASURED.with(Cell::get) - before
|
||||
}
|
||||
|
||||
/// A document with symbols "S 0" to "S 9", each a 10 × 10 square around the origin, and an
|
||||
/// instance of each at (40 i + 20, 20).
|
||||
fn ten_symbols() -> Document {
|
||||
let mut d = Document::new(400.0, 100.0);
|
||||
let layer = d.layers.first().map(|l| l.id);
|
||||
for i in 0..10 {
|
||||
let square = rect(&mut d, Rect::new(-5.0, -5.0, 5.0, 5.0), 0.0);
|
||||
symbol(&mut d, &format!("S {i}"), vec![square]);
|
||||
let at = instance(&mut d, &format!("S {i}"), Affine::translate((40.0 * f64::from(i) + 20.0, 20.0)));
|
||||
d.insert(layer, usize::MAX, at).unwrap();
|
||||
}
|
||||
d
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hit_tests_measure_each_symbols_art_once_while_the_symbols_stay_the_same() {
|
||||
use crate::hit::{self, HitOptions};
|
||||
let d = ten_symbols();
|
||||
let clicks = || {
|
||||
for i in 0..10 {
|
||||
let p = Point::new(40.0 * f64::from(i) + 20.0, 20.0);
|
||||
assert!(hit::hit_test(&d, p, HitOptions::default()).is_some(), "instance {i} is hit");
|
||||
assert_eq!(hit::objects_at(&d, p, HitOptions::default(), None).len(), 1);
|
||||
}
|
||||
assert_eq!(hit::marquee(&d, Rect::new(0.0, 0.0, 400.0, 100.0), None, false).len(), 10);
|
||||
};
|
||||
let first = art_boxes_measured(clicks);
|
||||
assert_eq!(first, 10, "each symbol's art box measured once");
|
||||
assert_eq!(art_boxes_measured(clicks), 0, "art boxes measured again");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hit_tests_measure_a_symbol_again_after_it_changes() {
|
||||
use crate::hit::{self, HitOptions};
|
||||
let mut d = ten_symbols();
|
||||
// Past the square of "S 1" at (60, 20).
|
||||
let past = Point::new(71.0, 20.0);
|
||||
assert!(hit::hit_test(&d, past, HitOptions::default()).is_none());
|
||||
// The art grows 3 times in place: no other copy of it is held in the document.
|
||||
Arc::make_mut(&mut d.symbols[1].art).transform(Affine::scale(3.0), false);
|
||||
let measured = art_boxes_measured(|| assert!(hit::hit_test(&d, past, HitOptions::default()).is_some(), "the grown art is hit"));
|
||||
assert!(measured > 0);
|
||||
// New art for "S 2", 40 wide.
|
||||
let wide = rect(&mut d, Rect::new(-20.0, -5.0, 20.0, 5.0), 0.0);
|
||||
d.symbols[2].art = Arc::new(wide);
|
||||
assert!(hit::hit_test(&d, Point::new(115.0, 20.0), HitOptions::default()).is_some(), "the new art is hit");
|
||||
// "S 3" renamed: its instance now shows the 20 × 20 square.
|
||||
d.symbols[3].name = "Renamed".into();
|
||||
assert!(hit::hit_test(&d, Point::new(148.0, 28.0), HitOptions::default()).is_some(), "the square is hit");
|
||||
assert_eq!(hits(&d), fresh_hits(&d));
|
||||
}
|
||||
|
||||
/// What clicks on a grid over `d` hit, and what a marquee over it selects.
|
||||
fn hits(d: &Document) -> (Vec<Option<Vec<NodeId>>>, Vec<NodeId>) {
|
||||
use crate::hit::{self, HitOptions};
|
||||
let mut clicks = Vec::new();
|
||||
for y in (0..400).step_by(5) {
|
||||
for x in (0..400).step_by(5) {
|
||||
let p = Point::new(f64::from(x), f64::from(y));
|
||||
clicks.push(hit::hit_test(d, p, HitOptions::default()).map(|h| h.ancestry));
|
||||
}
|
||||
}
|
||||
(clicks, hit::marquee(d, Rect::new(0.0, 0.0, 400.0, 400.0), None, false))
|
||||
}
|
||||
|
||||
/// [`hits`] with no measurements kept from earlier hit tests.
|
||||
fn fresh_hits(d: &Document) -> (Vec<Option<Vec<NodeId>>>, Vec<NodeId>) {
|
||||
KEPT.with_borrow_mut(Vec::clear);
|
||||
hits(d)
|
||||
}
|
||||
|
||||
/// A bar in a panel with or without 9-slice guides, in a holder whose instance at (50, 50) is
|
||||
/// scaled 2 times across. With the guides, the bar draws from x 30 to 210 and y 90 to 110; without
|
||||
/// them, from x 70 to 190, inside the panel's frame from x 50 to 250 and y 50 to 150.
|
||||
fn sliced_holder(guides: bool) -> Document {
|
||||
let mut d = Document::new(400.0, 400.0);
|
||||
let bar = rect(&mut d, Rect::new(10.0, 40.0, 70.0, 60.0), 0.0);
|
||||
symbol(&mut d, "Bar", vec![bar]);
|
||||
let frame = rect(&mut d, Rect::new(0.0, 0.0, 100.0, 100.0), 0.0);
|
||||
let inner = instance(&mut d, "Bar", Affine::IDENTITY);
|
||||
symbol(&mut d, "Panel", vec![frame, inner]);
|
||||
if guides {
|
||||
d.set_symbol_nine_slice("Panel", Some(crate::SymbolNineSlice::default()));
|
||||
}
|
||||
let panel = instance(&mut d, "Panel", Affine::IDENTITY);
|
||||
symbol(&mut d, "Holder", vec![panel]);
|
||||
let layer = d.layers.first().map(|l| l.id);
|
||||
let holder = instance(&mut d, "Holder", Affine::translate((50.0, 50.0)) * Affine::scale_non_uniform(2.0, 1.0));
|
||||
d.insert(layer, usize::MAX, holder).unwrap();
|
||||
d
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hit_tests_follow_new_9_slice_guides_and_symbol_sizes() {
|
||||
use crate::hit::{self, HitOptions};
|
||||
let mut d = sliced_holder(false);
|
||||
// Left of the frame, where only the bar placed through the guides draws.
|
||||
let left = Point::new(40.0, 100.0);
|
||||
assert!(hit::hit_test(&d, left, HitOptions::default()).is_none());
|
||||
d.set_symbol_nine_slice("Panel", Some(crate::SymbolNineSlice::default()));
|
||||
assert!(hit::hit_test(&d, left, HitOptions::default()).is_some(), "the bar placed through the guides is hit");
|
||||
assert_eq!(hits(&d), fresh_hits(&d));
|
||||
let before = hits(&d);
|
||||
d.unknown.insert(crate::SYMBOL_SIZES.into(), serde_json::json!({ "Panel": [200.0, 100.0] }));
|
||||
let after = hits(&d);
|
||||
assert_ne!(after, before, "the size moves the guides");
|
||||
assert_eq!(after, fresh_hits(&d));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hit_tests_measure_symbols_holding_9_slice_instances_on_each_call() {
|
||||
use crate::hit::{self, HitOptions};
|
||||
let d = sliced_holder(true);
|
||||
let left = Point::new(40.0, 100.0);
|
||||
assert!(hit::hit_test(&d, left, HitOptions::default()).is_some());
|
||||
// The holder's art holds an instance of a symbol with guides; the panel's art holds none.
|
||||
KEPT.with_borrow(|k| {
|
||||
let measured = &k[0].measured;
|
||||
assert!(measured.contains_key("Panel") && !measured.contains_key("Holder"), "{:?}", measured.keys());
|
||||
});
|
||||
let again = art_boxes_measured(|| assert!(hit::hit_test(&d, left, HitOptions::default()).is_some()));
|
||||
assert!(again > 0, "the holder's art box measured again");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn kept_measurements_depend_on_the_inputs_of_clipping_path_effects() {
|
||||
let d = ten_symbols();
|
||||
let key = KeptKey::of(&d, (0, false));
|
||||
assert!(key.is_of(&d, (0, false)));
|
||||
assert!(!key.is_of(&d, (1, false)), "live inputs changed");
|
||||
assert!(!key.is_of(&d, (0, true)), "a clip region registered");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hit_tests_with_a_locked_artboard_measure_each_symbols_art_once() {
|
||||
use crate::hit::{self, HitOptions};
|
||||
let mut d = ten_symbols();
|
||||
d.artboards[0].locked = true;
|
||||
let clicks = || {
|
||||
for i in 0..10 {
|
||||
let p = Point::new(40.0 * f64::from(i) + 20.0, 20.0);
|
||||
assert!(hit::hit_test(&d, p, HitOptions::default()).is_none(), "instance {i} is on the locked artboard");
|
||||
assert!(hit::objects_at(&d, p, HitOptions::default(), None).is_empty());
|
||||
}
|
||||
};
|
||||
assert!(art_boxes_measured(clicks) >= 10, "each symbol's art box measured");
|
||||
assert_eq!(art_boxes_measured(clicks), 0, "art boxes measured again");
|
||||
// A marquee passes over the objects on a locked artboard without measuring them itself: only
|
||||
// its locks measure their art.
|
||||
let mut d = ten_symbols();
|
||||
d.artboards[0].locked = true;
|
||||
let marquee = || assert!(hit::marquee(&d, Rect::new(0.0, 0.0, 400.0, 100.0), None, false).is_empty());
|
||||
assert_eq!(art_boxes_measured(marquee), 10, "each symbol's art box measured once");
|
||||
assert_eq!(art_boxes_measured(marquee), 0, "art boxes measured again");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hit_tests_hold_no_symbol_art() {
|
||||
use crate::hit::{self, HitOptions};
|
||||
let d = ten_symbols();
|
||||
drop(hit::hit_test(&d, Point::new(20.0, 20.0), HitOptions::default()));
|
||||
assert!(KEPT.with_borrow(|k| !k.is_empty()));
|
||||
assert!(d.symbols.iter().all(|s| Arc::strong_count(&s.art) == 1), "only the document holds the symbols' art");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hit_tests_keep_the_measurements_of_two_sets_of_symbols() {
|
||||
use crate::hit::{self, HitOptions};
|
||||
let docs = [ten_symbols(), ten_symbols(), ten_symbols()];
|
||||
let p = Point::new(20.0, 20.0);
|
||||
for d in &docs {
|
||||
drop(hit::hit_test(d, p, HitOptions::default()));
|
||||
}
|
||||
assert_eq!(KEPT.with_borrow(Vec::len), KEPT_SETS);
|
||||
// The last two are kept, the first is measured again.
|
||||
let kept = art_boxes_measured(|| docs[1..].iter().for_each(|d| drop(hit::hit_test(d, p, HitOptions::default()))));
|
||||
assert_eq!(kept, 0);
|
||||
let first = art_boxes_measured(|| drop(hit::hit_test(&docs[0], p, HitOptions::default())));
|
||||
assert!(first > 0);
|
||||
}
|
||||
}
|
||||
@@ -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};
|
||||
|
||||
|
||||
@@ -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() {
|
||||
|
||||
@@ -631,6 +631,8 @@ pub enum FirstBaseline {
|
||||
XHeight,
|
||||
/// The first line's leading.
|
||||
Leading,
|
||||
/// The top of the first line's ideographic em box touches the frame top.
|
||||
EmBoxHeight,
|
||||
/// Exactly `first_baseline_min` below the top.
|
||||
Fixed,
|
||||
}
|
||||
@@ -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))
|
||||
}
|
||||
|
||||
@@ -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.
|
||||
@@ -554,6 +647,20 @@ fn text_flow_is_saved_only_when_by_rows() {
|
||||
assert!(serde_json::from_value::<AreaOptions>(serde_json::json!({"flow": "diagonal"})).is_err());
|
||||
}
|
||||
|
||||
/// First Baseline Em Box Height saves as `emBoxHeight` with its minimum and reads back; files from
|
||||
/// before it read their own first baseline as they did, Ascent when they have none.
|
||||
#[test]
|
||||
fn em_box_height_first_baseline_is_saved_and_read_back() {
|
||||
let set = AreaOptions { first_baseline: FirstBaseline::EmBoxHeight, first_baseline_min: 9.0, ..AreaOptions::default() };
|
||||
let saved = serde_json::to_value(&set).unwrap();
|
||||
assert_eq!((saved["firstBaseline"].as_str(), saved["firstBaselineMin"].as_f64()), (Some("emBoxHeight"), Some(9.0)));
|
||||
assert_eq!(serde_json::from_value::<AreaOptions>(saved).unwrap(), set);
|
||||
let old = serde_json::json!({"firstBaseline": "leading", "firstBaselineMin": 3.0});
|
||||
assert_eq!(serde_json::from_value::<AreaOptions>(old).unwrap().first_baseline, FirstBaseline::Leading);
|
||||
assert_eq!(serde_json::from_value::<AreaOptions>(serde_json::json!({})).unwrap().first_baseline, FirstBaseline::Ascent);
|
||||
assert!(serde_json::from_value::<AreaOptions>(serde_json::json!({"firstBaseline": "emBox"})).is_err());
|
||||
}
|
||||
|
||||
/// 120 × 40 area type at (40, 40), its text drawn at twice its size.
|
||||
fn area_type() -> TextObject {
|
||||
let mut t = TextObject::point(Point::ZERO, "Some text", CharStyle::default());
|
||||
|
||||
@@ -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> {
|
||||
|
||||
@@ -720,7 +720,9 @@ fn moved_type_group(n: &Node) -> Option<Node> {
|
||||
/// Type in a clipping path, other type that [`moved_type`] doesn't copy, and type inside live
|
||||
/// objects or inside groups with Pathfinder or geometry effects or fills and strokes that paint, is
|
||||
/// outlined as [`evaluate_container`] outlines it, and the other members become what it makes of
|
||||
/// them. `None` when no type stays type.
|
||||
/// them. `None` when no type stays type, and for a group or layer whose copies each carry the raster
|
||||
/// effects listed before their Transform effect ([`crate::outer_effects`]), which is baked as the
|
||||
/// canvas draws it ([`evaluate_container`]).
|
||||
fn container_keeping_type(d: &Document, n: &Node) -> Option<Node> {
|
||||
fn keep(d: &Document, n: &mut Node, moves: &[serde_json::Value], clipping: bool, kept: &mut bool) {
|
||||
if !clipping {
|
||||
@@ -756,7 +758,11 @@ fn container_keeping_type(d: &Document, n: &Node) -> Option<Node> {
|
||||
}
|
||||
}
|
||||
}
|
||||
if !matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }) || has_pathfinder(n) || has_own_paint(n) {
|
||||
if !matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. })
|
||||
|| has_pathfinder(n)
|
||||
|| has_own_paint(n)
|
||||
|| crate::reshape::copied_container_raster_at(n).is_some()
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let fx = geometry_effects(n);
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -832,11 +832,15 @@ fn take_sublayer_guides(n: &mut Node, out: &mut Vec<Arc<Node>>, is_guide: &impl
|
||||
/// transparency, opacity mask and raster effects stay. `None` when it has none of these. Live
|
||||
/// objects among the members are evaluated with the symbols of `doc` (see [`member_shapes`]), and
|
||||
/// a Pathfinder operation or compound shape takes the symbol instances among its members as their
|
||||
/// symbols' art from `doc`.
|
||||
/// symbols' art from `doc`. A Transform effect that makes copies with raster effects listed before
|
||||
/// it gives each copy those raster effects ([`copied_container`]).
|
||||
pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option<Node> {
|
||||
if !is_container(n) {
|
||||
return None;
|
||||
}
|
||||
if let Some(t) = crate::reshape::copied_container_raster_at(n) {
|
||||
return Some(copied_container(doc, n, t));
|
||||
}
|
||||
let pathfinder = has_pathfinder(n);
|
||||
let fx = crate::reshape::geometry_effects(n);
|
||||
let paint = has_own_paint(n);
|
||||
@@ -901,6 +905,63 @@ pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option<Node> {
|
||||
Some(m)
|
||||
}
|
||||
|
||||
/// `n`, a group or layer whose own effects split at `t` ([`crate::reshape::copied_container_raster_at`]),
|
||||
/// as plain art: the effects before the Transform effect at `t` evaluated on its members as one
|
||||
/// piece ([`evaluate_container`]), with the raster effects among them, and that piece copied by the
|
||||
/// Transform effect, each copy a group of its own carrying those raster effects moved, turned,
|
||||
/// reflected and scaled with it ([`crate::reshape::copied_container_art`]). The art keeps the kind,
|
||||
/// transparency and opacity mask of `n` and the raster effects from `t` on, which paint once around
|
||||
/// all the copies; a clip group's or clipping layer's copies each clip, and the art itself does not.
|
||||
/// Its ruler guides, those in its sublayers and groups included, go once above the copies, hidden
|
||||
/// and locked as their containers were.
|
||||
fn copied_container(doc: Option<&Document>, n: &Node, t: usize) -> Node {
|
||||
let mut m = n.clone();
|
||||
let mut guides = vec![];
|
||||
take_sublayer_guides(&mut m, &mut guides, &Node::is_ruler_guide);
|
||||
let mut source = m.clone();
|
||||
source.appearance.effects = n.appearance.effects.get(..t).unwrap_or_default().to_vec();
|
||||
// With no geometry effect before the Transform effect, `evaluate_container` leaves the members'
|
||||
// own effects live (it only paints the group's own fills and strokes): the members are drawn
|
||||
// first, so their effects apply before the copies are made.
|
||||
if crate::reshape::geometry_effects(&source).is_empty() {
|
||||
source = crate::reshape::outlined_members(doc, &source);
|
||||
// The members' raster effects follow the group's own Transform effects as well.
|
||||
let _later = crate::raster::LaterGroups::enter(&n.appearance.effects);
|
||||
members_as_drawn(doc, &mut source);
|
||||
}
|
||||
let mut piece = evaluate_container(doc, &source).unwrap_or_else(|| {
|
||||
let mut p = source.clone();
|
||||
p.appearance.effects = crate::raster::without_geometry(&p.appearance.effects);
|
||||
p
|
||||
});
|
||||
// The piece is one copy: the transparency, opacity mask and guides stay on the art.
|
||||
piece.name = None;
|
||||
piece.visible = true;
|
||||
piece.locked = false;
|
||||
(piece.opacity, piece.blend, piece.isolate) = (1.0, Default::default(), false);
|
||||
piece.extras_mut().mask = None;
|
||||
// The copies are made about the piece's bounds, measured first: a layer leaves its hidden
|
||||
// members out of them, and a group does not.
|
||||
let bounds = piece.geometric_bounds();
|
||||
// A layer's copies are groups in it.
|
||||
if let NodeKind::Layer { children, clip, .. } = &mut piece.kind {
|
||||
piece.kind = NodeKind::Group { children: std::mem::take(children), clip: *clip };
|
||||
}
|
||||
let (art, effects) = crate::reshape::copied_container_art(doc, n, t, piece, bounds);
|
||||
let copies = art.children().cloned().unwrap_or_default();
|
||||
if let NodeKind::Group { children, clip } | NodeKind::Layer { children, clip, .. } = &mut m.kind {
|
||||
*children = copies;
|
||||
*clip = false;
|
||||
}
|
||||
m.appearance.items.clear();
|
||||
m.appearance.contents_index = None;
|
||||
m.appearance.effects = effects;
|
||||
if let Some(ch) = m.children_mut() {
|
||||
ch.extend(guides);
|
||||
}
|
||||
m
|
||||
}
|
||||
|
||||
/// Replace each visible member of `n` with geometry or Pathfinder effects of its own, at every
|
||||
/// depth of its groups and layers, by the art it draws ([`evaluate_container`],
|
||||
/// [`crate::reshape::own_effects_art`]), so the geometry effects of `n` reshape what its members
|
||||
|
||||
@@ -82,7 +82,7 @@ pub use live::{expand_live, expand_live_deep, expanded_live_group, outline_objec
|
||||
pub use marks::{CROP_MARKS, crop_marks_art, has_crop_marks};
|
||||
pub use pixel::{PIXEL_EFFECTS, PixelFx, PixelSpace};
|
||||
pub use raster::{
|
||||
RASTERIZE, RasterFx, Rasterize, color_param, follow_items, item_effects_in, outset, raster_effects, rasterize_stage, stage_map, staged_effects,
|
||||
RASTERIZE, RasterFx, Rasterize, color_param, follow_items, item_effects_in, outset, raster_effects, rasterize_stage, stage_maps, staged_effects,
|
||||
without_geometry,
|
||||
};
|
||||
pub use reshape::{
|
||||
@@ -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,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! Use Preview Bounds: objects measured as they are drawn, with their geometry effects.
|
||||
//! Use Preview Bounds: objects measured as they are drawn, with geometry and projected 3D effects.
|
||||
//!
|
||||
//! [`drawn_art`] gives an object whose geometry effects change what it draws as plain art. A path
|
||||
//! or compound path is given as its effected geometry, and a fill or stroke with geometry effects
|
||||
@@ -11,12 +11,15 @@
|
||||
//! ([`expanded_live_group`]), with each of those objects given as its own art. A clip group or
|
||||
//! layer whose clipping path has strokes with geometry effects is given as that path's geometry
|
||||
//! before its effects, which the renderer clips by, and those strokes as drawn. Fills and
|
||||
//! strokes that paint nothing (hidden, or painted None) are left out. [`bounds_of`],
|
||||
//! strokes that paint nothing (hidden, or painted None) are left out. Extrude & Bevel, Revolve,
|
||||
//! Inflate and Rotate are measured by the same projected vector art the renderer draws, with
|
||||
//! any geometry effects after projection applied to that art; [`drawn_art`], which clicks and
|
||||
//! marquees use, leaves 3D effects unprojected. [`bounds_of`],
|
||||
//! [`oriented_bounds`] and [`anchor_bounds`] measure the visual bounds of that art, strokes
|
||||
//! included, where [`Document::bounds_of`], [`Document::oriented_bounds`] and
|
||||
//! [`Selection::anchor_bounds`] measure the objects themselves. Raster effects (shadows, glows,
|
||||
//! blurs) are not measured. In one object, the art of at most 4,096 symbol instances is measured
|
||||
//! with its geometry effects, and the other instances in it are measured without them.
|
||||
//! with its geometry and 3D effects, and the other instances in it are measured without them.
|
||||
//! [`bounds_of_with`], [`oriented_bounds_with`] and [`anchor_bounds_with`] measure as these do and,
|
||||
//! with [`Measure::glyphs`], take point type by the ink of its glyphs (Measure Type by Glyph Bounds).
|
||||
|
||||
@@ -31,12 +34,12 @@ use vectorcraft_geom::{Affine, PathData, Rect, Shape, union_opt};
|
||||
use crate::group::has_own_paint;
|
||||
use crate::reshape::{geometry_effects, leaf_geometry};
|
||||
use crate::{
|
||||
GeomContext, apply_geometry_with, evaluate_container, expanded_live_group, has_geometry, has_item_geometry, has_pathfinder, has_transform_art,
|
||||
needs_outline, outline_art, paints, reshape,
|
||||
GeomContext, apply_geometry_with, evaluate_container, expanded_live_group, has_geometry, has_item_geometry, has_pathfinder, has_revolve,
|
||||
has_solid, has_transform_art, needs_outline, outline_art, paints, reshape, revolve_art_in, solid_art_in,
|
||||
};
|
||||
|
||||
/// Most symbol instances in one object whose art [`Drawn`] measures with its geometry effects:
|
||||
/// past it, the other instances in the object are measured without geometry effects.
|
||||
/// Most symbol instances in one object whose art [`Drawn`] measures with geometry or 3D effects:
|
||||
/// past it, the other instances in the object are measured without those effects.
|
||||
const MAX_INSTANCES: usize = 4096;
|
||||
|
||||
/// The bounds of `ids`: with `preview`, their visual bounds as drawn ([`visual_bounds`]), else
|
||||
@@ -191,8 +194,8 @@ pub fn laid_out_ink(layout: &vectorcraft_text::TextLayout, t: &vectorcraft_doc::
|
||||
.fold(layout.ink_bounds(), |acc, (_, bar)| union_opt(acc, Some(bar.bounding_box())))
|
||||
}
|
||||
|
||||
/// The visual bounds of `n` as drawn: those of its [`drawn_art`], else
|
||||
/// [`Node::visual_bounds_with`].
|
||||
/// The visual bounds of `n` as drawn: those of its [`drawn_art`] with its 3D effects projected,
|
||||
/// else [`Node::visual_bounds_with`].
|
||||
pub fn visual_bounds(symbols: &SymbolBoxes, n: &Node) -> Option<Rect> {
|
||||
Drawn::new(symbols).visual_bounds(n)
|
||||
}
|
||||
@@ -204,31 +207,45 @@ pub fn bounds_in(symbols: &SymbolBoxes, n: &Node, a: Affine) -> Option<Rect> {
|
||||
}
|
||||
|
||||
/// `n` as plain art with the geometry effects in it applied, at every depth, symbol instances
|
||||
/// measured by `symbols`. Raster effects stay on the art. A group, layer or intertwine without a
|
||||
/// clip is rebuilt with the drawn art of each member that has one. A clip group or layer becomes a
|
||||
/// group of its clipping path without strokes and the drawn art of the path's strokes, when they
|
||||
/// have one. `None` when no geometry effect in `n` changes what it draws.
|
||||
/// measured by `symbols`, for clicks and marquees. Raster effects stay on the art. A group, layer or
|
||||
/// intertwine without a clip is rebuilt with the drawn art of each member that has one. A clip group
|
||||
/// or layer becomes a group of its clipping path without strokes and the drawn art of the path's
|
||||
/// strokes, when they have one. 3D effects stay on the art unprojected, so each object in it keeps
|
||||
/// its own id. `None` when no geometry effect in `n` changes what it draws.
|
||||
pub fn drawn_art(symbols: &SymbolBoxes, n: &Node) -> Option<Node> {
|
||||
Drawn::new(symbols).drawn_art(n)
|
||||
Drawn::without_3d(symbols).drawn_art(n)
|
||||
}
|
||||
|
||||
/// Whether [`drawn_art`] gives `n` art of its own, or would give one to an object in it. A symbol
|
||||
/// instance in `n` counts when its symbol's art has a geometry effect.
|
||||
/// Whether `n` is measured by art of its own with Use Preview Bounds, or an object in it is: a
|
||||
/// geometry or 3D effect in it changes what it draws. A symbol instance in `n` counts when its
|
||||
/// symbol's art has geometry or 3D effects.
|
||||
pub fn draws_geometry(symbols: &SymbolBoxes, n: &Node) -> bool {
|
||||
Drawn::new(symbols).draws_geometry(n)
|
||||
}
|
||||
|
||||
/// One measurement: whether the art of each symbol checked so far draws geometry, by symbol name,
|
||||
/// and how many more instances' art it measures with its geometry effects in the current object ([`MAX_INSTANCES`]).
|
||||
/// One measurement: whether each symbol checked so far draws geometry or 3D art, by symbol name,
|
||||
/// and how many more instances it measures with those effects in the current object ([`MAX_INSTANCES`]).
|
||||
/// With `three_d` false, 3D effects are left on the art unprojected ([`drawn_art`]).
|
||||
struct Drawn<'s, 'd> {
|
||||
symbols: &'s SymbolBoxes<'d>,
|
||||
draws: RefCell<HashMap<String, bool>>,
|
||||
left: Cell<usize>,
|
||||
three_d: bool,
|
||||
}
|
||||
|
||||
impl<'s, 'd> Drawn<'s, 'd> {
|
||||
fn new(symbols: &'s SymbolBoxes<'d>) -> Self {
|
||||
Drawn { symbols, draws: RefCell::default(), left: Cell::new(MAX_INSTANCES) }
|
||||
Drawn { symbols, draws: RefCell::default(), left: Cell::new(MAX_INSTANCES), three_d: true }
|
||||
}
|
||||
|
||||
/// A measurement that projects no 3D effect, for clicks and marquees ([`drawn_art`]).
|
||||
fn without_3d(symbols: &'s SymbolBoxes<'d>) -> Self {
|
||||
Drawn { three_d: false, ..Self::new(symbols) }
|
||||
}
|
||||
|
||||
/// Whether `n` has a 3D effect of its own that this measurement projects.
|
||||
fn projects(&self, n: &Node) -> bool {
|
||||
self.three_d && (has_revolve(n) || has_solid(n))
|
||||
}
|
||||
|
||||
/// Sets the count of instances left back to [`MAX_INSTANCES`], for the next object.
|
||||
@@ -273,6 +290,7 @@ impl<'s, 'd> Drawn<'s, 'd> {
|
||||
let mut found = false;
|
||||
n.walk(&mut |c| {
|
||||
found = found
|
||||
|| self.projects(c)
|
||||
|| match &c.kind {
|
||||
NodeKind::SymbolInstance { symbol, .. } => !geometry_effects(c).is_empty() || self.symbol_draws(symbol),
|
||||
_ => reshapes(c),
|
||||
@@ -292,14 +310,29 @@ impl<'s, 'd> Drawn<'s, 'd> {
|
||||
d
|
||||
}
|
||||
|
||||
/// The art the geometry effects of `n` itself give it, or that a symbol instance gets from the
|
||||
/// geometry effects in its symbol's art. A group or layer with fills or strokes of its own that
|
||||
/// The art the geometry or 3D effects of `n` itself give it, or that a symbol instance gets from
|
||||
/// those effects in its symbol's art, with the instance's appearance overrides applied.
|
||||
/// A group or layer with fills or strokes of its own that
|
||||
/// paint, around members with geometry effects, is evaluated too: its fills and strokes paint
|
||||
/// the members' geometry before their effects. A blend, envelope or repeat whose objects have
|
||||
/// geometry effects is evaluated as the renderer evaluates it ([`expanded_live_group`]), and
|
||||
/// the objects in its evaluated art keep their geometry effects. `None` when it has none, and
|
||||
/// for a symbol instance past [`MAX_INSTANCES`].
|
||||
fn own_art(&self, n: &Node) -> Option<Node> {
|
||||
let doc = Some(self.symbols.document());
|
||||
// A symbol instance with a 3D effect of its own counts toward MAX_INSTANCES before its art is built.
|
||||
let counted = matches!(n.kind, NodeKind::SymbolInstance { .. }) && self.projects(n);
|
||||
if counted {
|
||||
let left = self.left.get().checked_sub(1)?;
|
||||
self.left.set(left);
|
||||
}
|
||||
if self.three_d
|
||||
&& let Some(art) = revolve_art_in(doc, n).or_else(|| solid_art_in(doc, n))
|
||||
{
|
||||
// The builders retain later geometry on the projected group. Measure it after that
|
||||
// geometry too; item-level effects are handled by the ordinary member traversal.
|
||||
return Some(self.own_art(&art).unwrap_or(art));
|
||||
}
|
||||
let inner = || n.children().is_some_and(|ch| ch.iter().any(|c| self.draws_geometry(c)));
|
||||
let painted = || has_own_paint(n) && inner();
|
||||
match &n.kind {
|
||||
@@ -312,9 +345,14 @@ impl<'s, 'd> Drawn<'s, 'd> {
|
||||
if geometry_effects(n).is_empty() && !self.symbol_draws(symbol) {
|
||||
return None;
|
||||
}
|
||||
let left = self.left.get().checked_sub(1)?;
|
||||
self.left.set(left);
|
||||
if !counted {
|
||||
let left = self.left.get().checked_sub(1)?;
|
||||
self.left.set(left);
|
||||
}
|
||||
let art = self.symbols.measure_art(symbol, Arc::clone)?;
|
||||
// Paint overrides can remove a projected surface or change its stroke outline.
|
||||
let art =
|
||||
if n.extras().symbol_overrides.is_empty() { art } else { Arc::new(vectorcraft_doc::symbol_overrides::dynamic_art(&art, n)) };
|
||||
// An instance in perspective is projected by `reshape`.
|
||||
let doc = Some(self.symbols.document());
|
||||
reshape(doc, n, Some(&*art)).or_else(|| outline_art(doc, n, Some(&*art)))
|
||||
|
||||
@@ -608,21 +608,36 @@ fn transform_step(e: &Effect) -> Option<Affine> {
|
||||
|
||||
/// The Transform effects of `effects` that move the image of its last visible Rasterize effect
|
||||
/// instead of the art it is made from: the indices of the visible Transform effects listed after
|
||||
/// it that move the art, when from the first visible Transform effect after it on every visible
|
||||
/// effect is a Transform effect that moves the art once (no copies, not at random). Effects apply
|
||||
/// in the order they are listed, so the image is made of the art before those Transform effects
|
||||
/// and moves with them, its pixel grid and room around the art included. `None` when there is no
|
||||
/// such Transform effect, or the effects after the Rasterize effect hold anything else from there
|
||||
/// on.
|
||||
/// it that move or copy the art, when from the first visible Transform effect after it on every
|
||||
/// visible effect is a Transform effect that does not move at random, and at most one of them makes
|
||||
/// copies. Effects apply in the order they are listed, so the image is made of the art before those
|
||||
/// Transform effects and moves with them, its pixel grid and room around the art included; each copy
|
||||
/// carries the same image ([`stage_maps`]). `None` when there is no such Transform effect, or the
|
||||
/// effects after the Rasterize effect hold anything else from there on.
|
||||
pub fn rasterize_stage(effects: &[Effect]) -> Option<Vec<usize>> {
|
||||
let r = effects.iter().rposition(|e| e.visible && e.id == RASTERIZE)?;
|
||||
let first = r + 1 + effects.get(r + 1..)?.iter().position(|e| e.visible && e.id == "distort.transform")?;
|
||||
let mut at = vec![];
|
||||
let mut copying = false;
|
||||
for (i, e) in effects.iter().enumerate().skip(first).filter(|(_, e)| e.visible) {
|
||||
if e.id != "distort.transform" || transform_step(e).is_none() {
|
||||
if e.id != "distort.transform" {
|
||||
return None;
|
||||
}
|
||||
if crate::distort::transform_map(Rect::ZERO, &merged_params(&e.id, &e.params), 0).0 != Affine::IDENTITY {
|
||||
let p = merged_params(&e.id, &e.params);
|
||||
if !flag(&p, "objects", true) {
|
||||
continue;
|
||||
}
|
||||
if flag(&p, "random", false) {
|
||||
return None;
|
||||
}
|
||||
let (map, copies) = crate::distort::transform_map(Rect::ZERO, &p, 0);
|
||||
if copies > 0 {
|
||||
if copying {
|
||||
return None;
|
||||
}
|
||||
copying = true;
|
||||
}
|
||||
if copies > 0 || map != Affine::IDENTITY {
|
||||
at.push(i);
|
||||
}
|
||||
}
|
||||
@@ -641,22 +656,41 @@ pub fn staged_effects(effects: &[Effect], at: &[usize]) -> Vec<Effect> {
|
||||
out
|
||||
}
|
||||
|
||||
/// The map the Transform effects at `at` of `effects` ([`rasterize_stage`]) move the Rasterize
|
||||
/// The maps the Transform effects at `at` of `effects` ([`rasterize_stage`]) place the Rasterize
|
||||
/// image by, for `staged`, the geometry the effects before them make: each one's map about its
|
||||
/// reference point on the bounds of the geometry it takes, as the geometry pass applies it, the
|
||||
/// last one outermost. `None` when `staged` is empty or the map is not a number.
|
||||
pub fn stage_map(effects: &[Effect], at: &[usize], staged: &vectorcraft_geom::PathData) -> Option<Affine> {
|
||||
/// last one outermost. A Transform effect with copies places the image once more for each copy
|
||||
/// the geometry pass makes, copy `k` through its map `k` times. The maps come in the order the
|
||||
/// images paint, the lowest first: the last copy lowest and the original on top, as copied objects
|
||||
/// stack. `None` when `staged` is empty or a map is not a number.
|
||||
pub fn stage_maps(effects: &[Effect], at: &[usize], staged: &vectorcraft_geom::PathData) -> Option<Vec<Affine>> {
|
||||
let mut cur = staged.clone();
|
||||
let mut b = staged.bounds()?;
|
||||
let mut map = Affine::IDENTITY;
|
||||
// The original's map first, then each copy's.
|
||||
let mut maps = vec![Affine::IDENTITY];
|
||||
for &i in at {
|
||||
let e = effects.get(i)?;
|
||||
let (m, _) = crate::distort::transform_map(b, &merged_params(&e.id, &e.params), 0);
|
||||
map = m * map;
|
||||
cur = cur.transformed(m);
|
||||
let p = merged_params(&e.id, &e.params);
|
||||
let (m, copies) = crate::distort::transform_map(b, &p, 0);
|
||||
if copies == 0 {
|
||||
maps.iter_mut().for_each(|x| *x = m * *x);
|
||||
cur = cur.transformed(m);
|
||||
} else {
|
||||
// As many copies as the geometry pass makes: it stops early past its limits.
|
||||
let next = crate::distort::transform(&cur, b, &p, 0);
|
||||
let made = (next.anchor_count() / cur.anchor_count().max(1)).saturating_sub(1);
|
||||
let placed = maps.clone();
|
||||
let mut xf = Affine::IDENTITY;
|
||||
for _ in 0..made {
|
||||
xf = m * xf;
|
||||
maps.extend(placed.iter().map(|x| xf * *x));
|
||||
}
|
||||
cur = next;
|
||||
}
|
||||
b = cur.bounds().unwrap_or(b);
|
||||
}
|
||||
map.is_finite().then_some(map)
|
||||
maps.reverse();
|
||||
maps.iter().all(|m| m.is_finite()).then_some(maps)
|
||||
}
|
||||
|
||||
/// Does raster effect `id` follow the Transform effects listed after it ([`followed`])? An SVG
|
||||
|
||||
@@ -208,6 +208,110 @@ pub(crate) fn copied_raster_at(n: &Node) -> Option<usize> {
|
||||
(carried && !excluded).then_some(t)
|
||||
}
|
||||
|
||||
/// Where the own effects of `n`, a group or layer, split so that each copy of a Transform effect
|
||||
/// carries the raster effects listed before that effect ([`crate::evaluate_container`]), as those of
|
||||
/// a path split ([`copied_raster_at`]): the index of the last visible Transform effect that makes
|
||||
/// copies, when a visible raster effect that follows a Transform effect is listed before it and
|
||||
/// every other visible effect before it is a geometry effect or such a raster effect. `None`
|
||||
/// otherwise, and for a compound shape, a Shaper group, a group or layer with a Pathfinder effect, a
|
||||
/// linked opacity mask, a 3D effect, Crop Marks, Vector Halftone, a live-effect plug-in that paints
|
||||
/// what it returns, a perspective, or a fill or stroke that paints with geometry effects of its own.
|
||||
pub(crate) fn copied_container_raster_at(n: &Node) -> Option<usize> {
|
||||
if !matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }) {
|
||||
return None;
|
||||
}
|
||||
let effects = &n.appearance.effects;
|
||||
// Checked first: this runs for every group and layer drawn.
|
||||
if !effects.iter().any(|e| e.visible && crate::raster::follows(&e.id)) || !effects.iter().any(|e| e.visible && e.id == "distort.transform") {
|
||||
return None;
|
||||
}
|
||||
let t = effects.iter().rposition(|e| {
|
||||
e.visible && e.id == "distort.transform" && crate::distort::transform_map(Rect::ZERO, &merged_params(&e.id, &e.params), 0).1 > 0
|
||||
})?;
|
||||
let before = effects.get(..t)?;
|
||||
let carried = before.iter().any(|e| e.visible && crate::raster::follows(&e.id))
|
||||
&& before.iter().all(|e| !e.visible || is_geometry(&e.id) || crate::raster::follows(&e.id));
|
||||
let excluded = n.is_compound_shape()
|
||||
|| n.extras().shaper.is_some()
|
||||
|| crate::has_pathfinder(n)
|
||||
|| n.extras().mask.as_ref().is_some_and(|m| m.linked)
|
||||
|| crate::has_solid(n)
|
||||
|| crate::has_revolve(n)
|
||||
|| crate::has_crop_marks(n)
|
||||
|| crate::addons::halftone::has_halftone(n)
|
||||
|| effects.iter().any(|e| painted_plugin(e).is_some())
|
||||
|| n.appearance.items.iter().any(|i| crate::paints(i) && crate::has_geometry(i.effects()))
|
||||
|| n.projection().is_some();
|
||||
(carried && !excluded).then_some(t)
|
||||
}
|
||||
|
||||
/// `piece`, the art that the effects of `n` (a group or layer whose own effects split at `t`,
|
||||
/// [`copied_container_raster_at`]) before the Transform effect at `t` make of it, with the raster
|
||||
/// effects among them as its own, copied by that Transform effect: a group with `n`'s id holding
|
||||
/// the copies, the last copy lowest and the original on top, each copy's own raster effects moved,
|
||||
/// turned, reflected and scaled with it ([`crate::raster::follow_contents`]), once, whatever Scale
|
||||
/// Strokes & Effects says. The members' own raster effects in each copy stay as a Transform effect
|
||||
/// that copies a group leaves them. The geometry effects after `t` then reshape all the copies as
|
||||
/// one piece. The copies stop where [`copy_art`]'s do, each with its raster effects. The copies
|
||||
/// inside `piece` that an earlier copying Transform effect of `n` made, which carry `n`'s id, have
|
||||
/// their raster effects moved, turned, reflected and scaled with each copy in the same way
|
||||
/// ([`follow_carried`]). The copies are made about `bounds`, the piece's bounds. Returns the art
|
||||
/// and the raster effects from `t` on, as they ran.
|
||||
pub(crate) fn copied_container_art(doc: Option<&Document>, n: &Node, t: usize, piece: Node, bounds: Option<Rect>) -> (Node, Vec<Effect>) {
|
||||
let rest = n.appearance.effects.get(t..).unwrap_or_default();
|
||||
let own = piece.appearance.effects.clone();
|
||||
let original = piece.clone();
|
||||
let mut art = Node::group(n.id, vec![Arc::new(piece)]);
|
||||
if let (Some(e), Some(bounds)) = (rest.first(), bounds) {
|
||||
let params = merged_params(&e.id, &e.params);
|
||||
let (m, copies) = crate::distort::transform_map(bounds, ¶ms, n.id.0);
|
||||
let max = Budget::EFFECTS.at_least(art_cost(&art));
|
||||
copy_art(&mut art, m, copies, copy_scaling(crate::distort::TransformOptions::of(¶ms)), max);
|
||||
if let Some(children) = art.children_mut() {
|
||||
// The original is last, and each copy above it is mapped once more by `m`.
|
||||
let step = m.with_translation(vectorcraft_geom::Vec2::ZERO);
|
||||
let mut a = Affine::IDENTITY;
|
||||
for (k, c) in children.iter_mut().rev().enumerate() {
|
||||
// Each copy is the piece in a group of its own: the piece takes its place.
|
||||
if let Some([one]) = c.children().map(Vec::as_slice) {
|
||||
*c = one.clone();
|
||||
}
|
||||
if k > 0 {
|
||||
a *= step;
|
||||
// Scale Strokes & Effects scaled the copy's own effects with it: they follow
|
||||
// its map from their values on the original instead.
|
||||
let copy = Arc::make_mut(c);
|
||||
copy.appearance.effects = own.clone();
|
||||
crate::raster::follow_contents(&mut copy.appearance.effects, a, Affine::IDENTITY);
|
||||
follow_carried(copy, &original, n.id, a);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let later: Vec<&Effect> = rest.iter().skip(1).filter(|e| e.visible && is_geometry(&e.id)).collect();
|
||||
let carry = reshape_leaves_apart(&mut art, &later, &n.appearance.effects, Budget::EFFECTS, (false, false), doc);
|
||||
let mut ran = n.appearance.effects.clone();
|
||||
if carry.skipped() {
|
||||
carry.hide_skipped(&mut ran);
|
||||
}
|
||||
let effects = crate::raster::without_geometry(ran.get(t..).unwrap_or_default());
|
||||
(art, effects)
|
||||
}
|
||||
|
||||
/// Give the members of `copy` with `id` (the copies that an earlier copying Transform effect of a
|
||||
/// group or layer made, [`copied_container_art`]), at every depth below such members, the raster
|
||||
/// effects of the matching members of `original`, the piece `copy` was made from, made to follow
|
||||
/// `a` ([`crate::raster::follow_contents`]).
|
||||
fn follow_carried(copy: &mut Node, original: &Node, id: NodeId, a: Affine) {
|
||||
let (Some(ch), Some(was)) = (copy.children_mut(), original.children()) else { return };
|
||||
for (c, w) in ch.iter_mut().zip(was).filter(|(c, w)| w.id == id && c.id == id) {
|
||||
let c = Arc::make_mut(c);
|
||||
c.appearance.effects = w.appearance.effects.clone();
|
||||
crate::raster::follow_contents(&mut c.appearance.effects, a, Affine::IDENTITY);
|
||||
follow_carried(c, w, id, a);
|
||||
}
|
||||
}
|
||||
|
||||
/// Is `e` a visible live-effect plug-in whose manifest declares `paintOutput`: its id's plug-in id,
|
||||
/// else `None`.
|
||||
fn painted_plugin(e: &Effect) -> Option<&str> {
|
||||
@@ -1172,9 +1276,10 @@ fn copied_raster_art(doc: Option<&Document>, n: &Node, t: usize, apart: bool, ou
|
||||
|
||||
/// The effects of `n` that paint around its whole art: all of its own, or from the Transform effect
|
||||
/// on for a path, compound path, type, image or symbol instance whose copies each carry the raster
|
||||
/// effects listed before it ([`copied_raster_at`]).
|
||||
/// effects listed before it ([`copied_raster_at`]) and for a group or layer whose copies do
|
||||
/// ([`copied_container_raster_at`]).
|
||||
pub fn outer_effects(n: &Node) -> &[Effect] {
|
||||
match copied_raster_at(n) {
|
||||
match copied_raster_at(n).or_else(|| copied_container_raster_at(n)) {
|
||||
Some(t) => n.appearance.effects.get(t..).unwrap_or_default(),
|
||||
None => &n.appearance.effects,
|
||||
}
|
||||
|
||||
@@ -801,7 +801,7 @@ pub(crate) fn revolve_meshes(n: &Node, total: &mut usize, limit: usize) -> Resul
|
||||
let b = path.bounds().ok_or("Revolve requires a shape with at least two anchors")?;
|
||||
let (paint, opacity, _) = paint_of(item);
|
||||
let mesh = vectorcraft_three_d::revolve_mesh(path, rule, b, fx_options(fx))?;
|
||||
Ok(crate::SolidMesh { mesh, color: crate::solids::mesh_color(&paint, opacity) })
|
||||
Ok(crate::SolidMesh::plain(mesh, crate::solids::mesh_color(&paint, opacity)))
|
||||
};
|
||||
if let Some(index) = n.appearance.effects.iter().position(|e| e.visible && is_revolve(&e.id)) {
|
||||
let before = n.appearance.effects.get(..index).unwrap_or_default();
|
||||
@@ -924,7 +924,7 @@ fn group_meshes(n: &Node, total: &mut usize, limit: usize) -> Result<Vec<crate::
|
||||
let Some(item) = surface_item(&s.items) else { continue };
|
||||
let (paint, opacity, _) = paint_of(item);
|
||||
let mesh = vectorcraft_three_d::revolve_mesh(&s.path, s.rule, b, options)?;
|
||||
crate::solids::keep_mesh(&mut out, total, crate::SolidMesh { mesh, color: crate::solids::mesh_color(&paint, opacity * s.opacity) }, limit)?;
|
||||
crate::solids::keep_mesh(&mut out, total, crate::SolidMesh::plain(mesh, crate::solids::mesh_color(&paint, opacity * s.opacity)), limit)?;
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
@@ -25,8 +25,8 @@ pub(crate) use source::{resolve, resolve_for};
|
||||
|
||||
pub(crate) mod graphics;
|
||||
pub use graphics::{
|
||||
GRAPHICS, GraphicFrame, MAX_GRAPHICS, MappedGraphic, graphic_symbols, mapped_graphics, missing_symbol, names_graphic_symbol,
|
||||
rename_graphic_symbol, rename_graphic_symbol_in, takes_graphics, with_graphic,
|
||||
GRAPHICS, GraphicFrame, MAX_GRAPHICS, MappedGraphic, MeshGraphics, graphic_symbols, mapped_graphics, mesh_graphics_art, missing_symbol,
|
||||
names_graphic_symbol, rename_graphic_symbol, rename_graphic_symbol_in, takes_graphics, with_graphic,
|
||||
};
|
||||
pub use graphics::{
|
||||
MAX_OFFSET as GRAPHIC_MAX_OFFSET, NOT_TAKEN as GRAPHICS_NOT_TAKEN, SCALE_RANGE as GRAPHIC_SCALE_RANGE, appearance_graphic_symbols,
|
||||
@@ -2322,6 +2322,71 @@ pub struct SolidMesh {
|
||||
/// The paint's display color (sRGB, 0..1) and its opacity: a gradient's stops averaged, gray
|
||||
/// for a pattern.
|
||||
pub color: [f32; 4],
|
||||
/// The graphics mapped onto the mesh when it is the part of a solid's planar face that carries
|
||||
/// some ([`split_graphics`]); `None` otherwise.
|
||||
pub graphics: Option<MeshGraphics>,
|
||||
}
|
||||
|
||||
impl SolidMesh {
|
||||
/// A mesh painted `color`, with no graphics.
|
||||
pub fn plain(mesh: Mesh, color: [f32; 4]) -> Self {
|
||||
Self { mesh, color, graphics: None }
|
||||
}
|
||||
}
|
||||
|
||||
/// The parts of `mesh`, a solid that 3D effect `id` with parameters `p` built about `bounds`, painted
|
||||
/// `color` from a fill or stroke at `opacity`: for each planar face that carries graphics (Extrude &
|
||||
/// Bevel's caps, the plane), the triangles on it as a mesh of their own with the art point of each
|
||||
/// corner ([`MeshGraphics`]), then the rest. Revolve's side, whose graphics are not mapped onto its
|
||||
/// mesh, stays plain.
|
||||
fn split_graphics(id: &str, p: &Value, bounds: Rect, mesh: Mesh, (color, opacity): ([f32; 4], f32)) -> Vec<SolidMesh> {
|
||||
let list = graphics::mapped_graphics(p);
|
||||
if list.is_empty() || !takes_graphics(id) || id == crate::REVOLVE {
|
||||
return vec![SolidMesh::plain(mesh, color)];
|
||||
}
|
||||
let view = view_options(p);
|
||||
let mut rest = mesh;
|
||||
let mut out = vec![];
|
||||
for face in PlanarFace::ALL {
|
||||
if !list.iter().any(|g| g.face == face) {
|
||||
continue;
|
||||
}
|
||||
let on_mesh = if id == ROTATE {
|
||||
vectorcraft_three_d::plane_mesh_face(bounds, view)
|
||||
} else {
|
||||
vectorcraft_three_d::extrude_mesh_face(bounds, extrude_options(p), view, face)
|
||||
};
|
||||
let Some(on_mesh) = on_mesh else { continue };
|
||||
let (mut taken, mut left, mut art) = (Mesh::default(), Mesh::default(), vec![]);
|
||||
for t in &rest.triangles {
|
||||
let corner = |i: u32| rest.positions.get(i as usize).copied().zip(rest.normals.get(i as usize).copied());
|
||||
let Some(corners) = t.iter().map(|&i| corner(i)).collect::<Option<Vec<_>>>() else { continue };
|
||||
let points: Option<Vec<Point>> = corners.iter().map(|(m, n)| on_mesh.art_point(*m, *n)).collect();
|
||||
let into = match points {
|
||||
Some(points) => {
|
||||
art.extend(points);
|
||||
&mut taken
|
||||
}
|
||||
None => &mut left,
|
||||
};
|
||||
let base = into.positions.len() as u32;
|
||||
for (m, n) in corners {
|
||||
into.positions.push(m);
|
||||
into.normals.push(n);
|
||||
}
|
||||
into.triangles.push([base, base + 1, base + 2]);
|
||||
}
|
||||
rest = left;
|
||||
if !taken.is_empty() {
|
||||
let graphics = list.iter().filter(|g| g.face == face).cloned().collect();
|
||||
let graphics = MeshGraphics { face, graphics, center: bounds.center(), art, opacity, object: 1.0 };
|
||||
out.push(SolidMesh { mesh: taken, color, graphics: Some(graphics) });
|
||||
}
|
||||
}
|
||||
if !rest.is_empty() {
|
||||
out.insert(0, SolidMesh::plain(rest, color));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The color a mesh of `paint` at `opacity` takes ([`SolidMesh::color`]).
|
||||
@@ -2363,13 +2428,18 @@ fn meshes_for(fx: &Effect, shapes: &[Profile], total: &mut usize, limit: usize)
|
||||
let p = crate::merged_params(&fx.id, &fx.params);
|
||||
let view = view_options(&p);
|
||||
let mut out = vec![];
|
||||
let mut keep = |out: &mut Vec<SolidMesh>, mesh: Mesh, color: [f32; 4]| keep_mesh(out, total, SolidMesh { mesh, color }, limit);
|
||||
// A solid's parts with and without graphics count together against the limit.
|
||||
let mut keep = |out: &mut Vec<SolidMesh>, mesh: Mesh, (paint, opacity): (&Paint, f32), bounds: Rect| {
|
||||
split_graphics(&fx.id, &p, bounds, mesh, (mesh_color(paint, opacity), opacity))
|
||||
.into_iter()
|
||||
.try_for_each(|part| keep_mesh(out, total, part, limit))
|
||||
};
|
||||
if is_plane(&fx.id) {
|
||||
for s in shapes {
|
||||
for item in &s.items {
|
||||
let (paint, opacity, _) = paint_of(item, s.opacity);
|
||||
let (area, rule) = region(&s.path, s.rule, item);
|
||||
keep(&mut out, vectorcraft_three_d::plane_mesh(&area, rule, b, view)?, mesh_color(&paint, opacity))?;
|
||||
keep(&mut out, vectorcraft_three_d::plane_mesh(&area, rule, b, view)?, (&paint, opacity), b)?;
|
||||
}
|
||||
}
|
||||
return Ok(out);
|
||||
@@ -2406,7 +2476,7 @@ fn meshes_for(fx: &Effect, shapes: &[Profile], total: &mut usize, limit: usize)
|
||||
match solid.mesh() {
|
||||
Ok(mesh) => {
|
||||
let (paint, opacity, _) = paint_of(item, *member);
|
||||
keep(&mut out, mesh, mesh_color(&paint, opacity))?;
|
||||
keep(&mut out, mesh, (&paint, opacity), bounds)?;
|
||||
}
|
||||
Err(_) if matches!(item, AppearanceItem::Stroke(_)) => {}
|
||||
Err(e) => return Err(e),
|
||||
@@ -2494,6 +2564,9 @@ fn meshes_within(doc: Option<&Document>, n: &Node, total: &mut usize, limit: usi
|
||||
.filter(|m| !m.mesh.is_empty())
|
||||
.map(|mut m| {
|
||||
m.color[3] *= n.opacity.clamp(0.0, 1.0);
|
||||
if let Some(g) = &mut m.graphics {
|
||||
g.object *= n.opacity.clamp(0.0, 1.0);
|
||||
}
|
||||
m
|
||||
})
|
||||
.collect();
|
||||
|
||||
@@ -519,6 +519,71 @@ pub(super) fn face_art(
|
||||
Some(Node::new(id, NodeKind::Group { children: vec![Arc::new(clip), Arc::new(Node::group(id, children))], clip: true }))
|
||||
}
|
||||
|
||||
/// The graphics on one planar face of a solid's mesh ([`super::SolidMesh`]): those mapped onto
|
||||
/// `face`, placed about `center` (the center of the bounds the solids were built with), and the
|
||||
/// point of the art's plane that each corner of the mesh shows (document coordinates of the art
|
||||
/// before its 3D effect, y down).
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct MeshGraphics {
|
||||
pub face: PlanarFace,
|
||||
pub graphics: Vec<MappedGraphic>,
|
||||
pub center: Point,
|
||||
/// One for each position of the mesh.
|
||||
pub art: Vec<Point>,
|
||||
/// The opacity of the fill or stroke the face is painted with, which the graphics take too, as
|
||||
/// the canvas draws them; neither a gradient's stops nor the object's own opacity is in it.
|
||||
pub opacity: f32,
|
||||
/// The opacity of the object the face belongs to, which applies to the face and its graphics
|
||||
/// together.
|
||||
pub object: f32,
|
||||
}
|
||||
|
||||
impl MeshGraphics {
|
||||
/// The bounds of the art points of the mesh's corners; `None` without corners.
|
||||
pub fn art_bounds(&self) -> Option<Rect> {
|
||||
let first = *self.art.first()?;
|
||||
Some(self.art.iter().fold(Rect::from_points(first, first), |r, p| r.union_pt(*p)))
|
||||
}
|
||||
}
|
||||
|
||||
/// The art `graphics` draws on its face, flat in the art's plane, unshaded and unclipped: each
|
||||
/// graphic's fills and stroke outlines at its place ([`MappedGraphic`]), back to front, as one
|
||||
/// group of objects with id `id`. A graphic whose symbol `doc` does not have, or whose art is past
|
||||
/// the limits of [`pieces_of`], is left out, as the canvas leaves it out. `Ok(None)` when nothing
|
||||
/// is drawn; an error when the graphics' art draws more than [`MAX_ELEMENTS`] path elements
|
||||
/// together.
|
||||
pub fn mesh_graphics_art(doc: &Document, id: NodeId, graphics: &MeshGraphics) -> Result<Option<Node>, String> {
|
||||
let mut children = vec![];
|
||||
let mut elements = 0usize;
|
||||
for g in graphics.graphics.iter().filter(|g| g.face == graphics.face) {
|
||||
let Some(symbol) = doc.symbols.iter().find(|s| s.name == g.symbol) else { continue };
|
||||
let Ok(pieces) = pieces_of(doc, symbol) else { continue };
|
||||
let Some(bounds) = pieces.iter().filter_map(|p| p.path.bounds()).reduce(|a, b| a.union(b)) else { continue };
|
||||
let place = g.placement(bounds, graphics.center);
|
||||
for piece in pieces {
|
||||
elements = elements.saturating_add(drawn_elements(&piece.path, 1));
|
||||
if elements > MAX_ELEMENTS {
|
||||
return Err("The graphics are too complex: simplify the symbols' art".into());
|
||||
}
|
||||
let mut paint = piece.paint;
|
||||
if let Paint::Pattern { xf, .. } = &mut paint {
|
||||
*xf = place * *xf;
|
||||
}
|
||||
let mut fill = FillLayer::new(paint);
|
||||
fill.opacity = piece.opacity;
|
||||
fill.blend = piece.blend;
|
||||
let mut appearance = Appearance { items: vec![AppearanceItem::Fill(fill)], ..Default::default() };
|
||||
appearance.transform_gradients(place);
|
||||
let mut node = Node::path(id, piece.path.transformed(place), appearance);
|
||||
if let NodeKind::Path { rule, .. } = &mut node.kind {
|
||||
*rule = piece.rule;
|
||||
}
|
||||
children.push(Arc::new(node));
|
||||
}
|
||||
}
|
||||
Ok((!children.is_empty()).then(|| Node::group(id, children)))
|
||||
}
|
||||
|
||||
/// One area of a graphic placed on Revolve's unrolled side surface, cut into straight pieces.
|
||||
struct Unrolled {
|
||||
polygons: Vec<Vec<Point>>,
|
||||
|
||||
@@ -86,6 +86,48 @@ fn a_graphic_is_drawn_on_the_front_cap_at_its_offset_size_and_turn() {
|
||||
assert!((b.width() - 10.0 * 2f64.sqrt()).abs() < 1e-6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_mesh_carries_its_caps_graphics_flat_in_the_arts_plane() {
|
||||
let d = document();
|
||||
let graphics =
|
||||
json!([{"symbol": "Mark", "x": 20.0, "y": -10.0, "scale": 200.0}, {"symbol": "Mark", "face": "back", "x": 20.0, "y": -10.0, "scale": 200.0}]);
|
||||
// Turned, so the caps' corners in the mesh are not the art's.
|
||||
let n = object(EXTRUDE, json!({"rotationX": -20.0, "rotationY": 35.0, "rotationZ": 10.0, "graphics": graphics}));
|
||||
let parts = super::super::three_d_meshes_in(Some(&d), &n).unwrap();
|
||||
// The walls first, then the front cap and the back cap, each two triangles.
|
||||
assert_eq!(
|
||||
parts.iter().map(|p| p.graphics.as_ref().map(|g| g.face)).collect::<Vec<_>>(),
|
||||
[None, Some(PlanarFace::Front), Some(PlanarFace::Back)]
|
||||
);
|
||||
let total: usize = parts.iter().map(|p| p.mesh.triangles.len()).sum();
|
||||
let plain = super::super::three_d_meshes_in(Some(&d), &object(EXTRUDE, json!({"rotationX": -20.0, "rotationY": 35.0, "rotationZ": 10.0})));
|
||||
assert_eq!(total, plain.as_ref().map_or(0, |p| p.iter().map(|p| p.mesh.triangles.len()).sum()), "no triangle is lost or doubled");
|
||||
assert!(plain.unwrap().iter().all(|p| p.graphics.is_none()));
|
||||
// The art points of each cap's corners are the art's own square; the graphic is drawn flat at
|
||||
// its place, mirrored on the back so it reads from behind.
|
||||
for (part, drawn) in parts[1..].iter().zip([Rect::new(60.0, 30.0, 80.0, 50.0), Rect::new(20.0, 30.0, 40.0, 50.0)]) {
|
||||
let Some(g) = &part.graphics else { panic!("no graphics") };
|
||||
assert_eq!(g.art.len(), part.mesh.positions.len());
|
||||
assert!(close(g.art_bounds().unwrap(), Rect::new(0.0, 0.0, 100.0, 100.0)), "{:?}", g.art_bounds());
|
||||
assert_eq!(g.graphics.len(), 1);
|
||||
let art = mesh_graphics_art(&d, NodeId(9), g).unwrap().unwrap();
|
||||
let paths: Vec<(PathData, Paint)> = art
|
||||
.children()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(|c| Some((c.path_data()?.clone(), c.appearance.items.first()?.paint().clone())))
|
||||
.collect();
|
||||
assert!(close(bounds_of(&paths), drawn), "{:?}: {:?}", g.face, bounds_of(&paths));
|
||||
assert_eq!(paths[0].1, Paint::solid(red()), "unshaded");
|
||||
}
|
||||
// A plane is all one face; a graphic whose symbol is gone draws nothing.
|
||||
let n = object(ROTATE, json!({"rotationY": 35.0, "graphics": [{"symbol": "Gone"}]}));
|
||||
let parts = super::super::three_d_meshes_in(Some(&d), &n).unwrap();
|
||||
assert_eq!(parts.len(), 1);
|
||||
let Some(g) = &parts[0].graphics else { panic!("no graphics") };
|
||||
assert_eq!(mesh_graphics_art(&d, NodeId(9), g), Ok(None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn without_the_document_or_its_symbol_nothing_is_drawn() {
|
||||
let n = object(EXTRUDE, json!({"graphics": [{"symbol": "Mark"}]}));
|
||||
@@ -563,6 +605,15 @@ fn art_nested_too_deep_is_refused_and_not_drawn() {
|
||||
// A loaded file draws its other graphics.
|
||||
let both = object(EXTRUDE, json!({"graphics": [{"symbol": "Deep"}, {"symbol": "Mark"}]}));
|
||||
assert_eq!(graphics_in(&solid_art_in(Some(&d), &both).unwrap()).len(), 1);
|
||||
// A mesh's graphics leave it out as well and draw the others.
|
||||
let parts = super::super::three_d_meshes_in(Some(&d), &both).unwrap();
|
||||
let Some(g) = parts.iter().find_map(|p| p.graphics.as_ref()) else { panic!("no graphics") };
|
||||
let art = mesh_graphics_art(&d, NodeId(9), g).unwrap().unwrap();
|
||||
assert_eq!(art.children().map_or(0, |c| c.len()), 1);
|
||||
let deep = object(EXTRUDE, json!({"graphics": [{"symbol": "Deep"}]}));
|
||||
let parts = super::super::three_d_meshes_in(Some(&d), &deep).unwrap();
|
||||
let Some(g) = parts.iter().find_map(|p| p.graphics.as_ref()) else { panic!("no graphics") };
|
||||
assert_eq!(mesh_graphics_art(&d, NodeId(9), g), Ok(None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -238,7 +238,7 @@ fn meshes_built_apart(fx: &Effect, shapes: &[Profile], total: &mut usize, limit:
|
||||
match mesh {
|
||||
Ok(mesh) => {
|
||||
let (paint, opacity, _) = paint_of(item, *opacity);
|
||||
keep_mesh(&mut out, total, SolidMesh { mesh, color: mesh_color(&paint, opacity) }, limit)?;
|
||||
keep_mesh(&mut out, total, SolidMesh::plain(mesh, mesh_color(&paint, opacity)), limit)?;
|
||||
}
|
||||
Err(_) if matches!(item, AppearanceItem::Stroke(_)) => {}
|
||||
Err(e) => return Err(e),
|
||||
|
||||
@@ -1687,6 +1687,27 @@ fn twist_turns_clockwise_for_positive_angles() {
|
||||
assert!(turned(-45.0).y < 49.5, "{:?}", turned(-45.0));
|
||||
}
|
||||
|
||||
/// Twist turns a line into a smooth spiral: the points it adds join their pieces without a kink,
|
||||
/// however far it turns (#7069).
|
||||
#[test]
|
||||
fn twist_joins_its_pieces_smoothly() {
|
||||
let line = PathData::single(SubPath::polyline(&[Point::new(40.0, 30.0), Point::new(60.0, 30.0)], false));
|
||||
let bounds = Rect::new(40.0, 30.0, 60.0, 30.0);
|
||||
for angle in [90.0, 400.0, -720.0] {
|
||||
let out = apply_geometry(&[fx("distort.twist", json!({"angle": angle}))], &line, bounds);
|
||||
let anchors = &out.subpaths[0].anchors;
|
||||
assert!(anchors.len() > 8, "{angle}°: {} anchors", anchors.len());
|
||||
for a in anchors.iter().skip(1).take(anchors.len() - 2) {
|
||||
let (into, out) = (a.p - a.h_in, a.h_out - a.p);
|
||||
if into.hypot() < 1e-9 || out.hypot() < 1e-9 {
|
||||
continue;
|
||||
}
|
||||
let kink = (into.x * out.y - into.y * out.x).atan2(into.dot(out)).to_degrees().abs();
|
||||
assert!(kink < 1.0, "{angle}°: a kink of {kink:.1}° at {:?}", a.p);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn twist_fixes_the_outer_circle_and_rotates_inside() {
|
||||
let out = run("distort.twist", json!({"angle": 0}), &square());
|
||||
|
||||
@@ -129,9 +129,10 @@ fn rasterize_before_a_transform_keeps_its_options() {
|
||||
assert_eq!(crate::rasterize_stage(&effects), Some(vec![1]));
|
||||
}
|
||||
|
||||
/// The Transform effects after the last Rasterize effect move its image when, from the first of
|
||||
/// them on, every visible effect is a Transform effect that moves the art once. Hidden ones, and
|
||||
/// ones with Transform Objects off, leave the image where it is.
|
||||
/// The Transform effects after the last Rasterize effect move or copy its image when, from the
|
||||
/// first of them on, every visible effect is a Transform effect that does not move at random and at
|
||||
/// most one of them makes copies. Hidden ones, and ones with Transform Objects off, leave the image
|
||||
/// where it is.
|
||||
#[test]
|
||||
fn rasterize_following_ignores_hidden_and_objects_off() {
|
||||
let rasterize = || fx(crate::RASTERIZE, json!({}));
|
||||
@@ -150,9 +151,16 @@ fn rasterize_following_ignores_hidden_and_objects_off() {
|
||||
// the image back.
|
||||
(vec![rasterize(), roughen.clone(), shadow.clone(), scale()], Some(vec![3])),
|
||||
(vec![rasterize(), scale(), roughen], None),
|
||||
(vec![rasterize(), scale(), shadow], None),
|
||||
(vec![rasterize(), transform(json!({"scaleH": 200, "copies": 2}))], None),
|
||||
(vec![rasterize(), scale(), shadow.clone()], None),
|
||||
// Each copy carries the image, even of a Transform effect that only copies in place.
|
||||
(vec![rasterize(), transform(json!({"scaleH": 200, "copies": 2}))], Some(vec![1])),
|
||||
(vec![rasterize(), transform(json!({"copies": 2}))], Some(vec![1])),
|
||||
(vec![rasterize(), transform(json!({"moveH": 10, "copies": 2})), scale()], Some(vec![1, 2])),
|
||||
(vec![rasterize(), transform(json!({"moveH": 10, "copies": 2, "objects": false}))], None),
|
||||
(vec![rasterize(), transform(json!({"moveH": 10, "copies": 2})), transform(json!({"moveV": 10, "copies": 3}))], None),
|
||||
(vec![rasterize(), transform(json!({"moveH": 10, "copies": 2})), shadow], None),
|
||||
(vec![rasterize(), transform(json!({"scaleH": 200, "random": true}))], None),
|
||||
(vec![rasterize(), transform(json!({"scaleH": 200, "copies": 2, "random": true}))], None),
|
||||
// The Transform effect before the Rasterize effect moves the art.
|
||||
(vec![scale(), rasterize()], None),
|
||||
(vec![scale(), rasterize(), rasterize(), scale()], Some(vec![3])),
|
||||
@@ -173,16 +181,62 @@ fn rasterize_following_ignores_hidden_and_objects_off() {
|
||||
fn the_image_moves_by_each_transform_about_the_art_it_takes() {
|
||||
let staged = shapes::rectangle(Rect::new(10.0, 10.0, 30.0, 30.0));
|
||||
let effects = [fx(crate::RASTERIZE, json!({})), transform(json!({"scaleH": 200, "scaleV": 200})), transform(json!({"moveH": 5}))];
|
||||
let map = crate::stage_map(&effects, &[1, 2], &staged).unwrap();
|
||||
let maps = crate::stage_maps(&effects, &[1, 2], &staged).unwrap();
|
||||
assert_eq!(maps.len(), 1);
|
||||
// Twice the size about the center (20, 20), then 5 pt to the right.
|
||||
let want = Affine::translate((5.0, 0.0)) * Affine::translate((20.0, 20.0)) * Affine::scale(2.0) * Affine::translate((-20.0, -20.0));
|
||||
assert!(map.as_coeffs().iter().zip(want.as_coeffs()).all(|(a, b)| (a - b).abs() < 1e-9), "{map:?}");
|
||||
assert!(same_map(maps[0], want), "{maps:?}");
|
||||
// The second Transform effect turns about the center of what the first one made.
|
||||
let effects = [fx(crate::RASTERIZE, json!({})), transform(json!({"moveH": 100})), transform(json!({"rotate": 90}))];
|
||||
let map = crate::stage_map(&effects, &[1, 2], &staged).unwrap();
|
||||
let c = map * Point::new(20.0, 20.0);
|
||||
let maps = crate::stage_maps(&effects, &[1, 2], &staged).unwrap();
|
||||
let c = maps[0] * Point::new(20.0, 20.0);
|
||||
assert!((c.x - 120.0).abs() < 1e-9 && (c.y - 20.0).abs() < 1e-9, "{c:?}");
|
||||
assert_eq!(crate::stage_map(&effects, &[1, 2], &PathData::default()), None);
|
||||
assert_eq!(crate::stage_maps(&effects, &[1, 2], &PathData::default()), None);
|
||||
}
|
||||
|
||||
/// Is `a` `b`, each coefficient within 1e-9?
|
||||
fn same_map(a: Affine, b: Affine) -> bool {
|
||||
a.as_coeffs().iter().zip(b.as_coeffs()).all(|(a, b)| (a - b).abs() < 1e-9)
|
||||
}
|
||||
|
||||
/// Are `maps` `want`, in order?
|
||||
fn same_maps(maps: &[Affine], want: &[Affine]) -> bool {
|
||||
maps.len() == want.len() && maps.iter().zip(want).all(|(m, w)| same_map(*m, *w))
|
||||
}
|
||||
|
||||
/// A Transform effect with copies places the image once for the original and once for each copy,
|
||||
/// copy `k` through its map `k` times about the art before it, the last copy lowest and the
|
||||
/// original on top. A Transform effect after it moves every placement, about the bounds of all the
|
||||
/// copies.
|
||||
#[test]
|
||||
fn each_copy_carries_the_image() {
|
||||
let staged = shapes::rectangle(Rect::new(10.0, 10.0, 30.0, 30.0));
|
||||
let rasterize = fx(crate::RASTERIZE, json!({}));
|
||||
let effects = [rasterize.clone(), transform(json!({"moveH": 100, "copies": 2}))];
|
||||
let maps = crate::stage_maps(&effects, &[1], &staged).unwrap();
|
||||
let want = [Affine::translate((200.0, 0.0)), Affine::translate((100.0, 0.0)), Affine::IDENTITY];
|
||||
assert!(same_maps(&maps, &want), "{maps:?}");
|
||||
// Turned 90° about the center (20, 20) each time: copy 2 turns 180°.
|
||||
let effects = [rasterize.clone(), transform(json!({"rotate": 90, "copies": 2}))];
|
||||
let maps = crate::stage_maps(&effects, &[1], &staged).unwrap();
|
||||
let turn = |deg: f64| Affine::translate((20.0, 20.0)) * Affine::rotate(-deg.to_radians()) * Affine::translate((-20.0, -20.0));
|
||||
let want = [turn(180.0), turn(90.0), Affine::IDENTITY];
|
||||
assert!(same_maps(&maps, &want), "{maps:?}");
|
||||
// A scale after the copies doubles every placement about the center of all three, (120, 20).
|
||||
let effects = [rasterize.clone(), transform(json!({"moveH": 100, "copies": 2})), transform(json!({"scaleH": 200, "scaleV": 200}))];
|
||||
let maps = crate::stage_maps(&effects, &[1, 2], &staged).unwrap();
|
||||
let scale = Affine::translate((120.0, 20.0)) * Affine::scale(2.0) * Affine::translate((-120.0, -20.0));
|
||||
let want = [scale * Affine::translate((200.0, 0.0)), scale * Affine::translate((100.0, 0.0)), scale];
|
||||
assert!(same_maps(&maps, &want), "{maps:?}");
|
||||
// A move before the copies moves the art they copy.
|
||||
let effects = [rasterize.clone(), transform(json!({"moveV": 5})), transform(json!({"moveH": 100, "copies": 1}))];
|
||||
let maps = crate::stage_maps(&effects, &[1, 2], &staged).unwrap();
|
||||
let want = [Affine::translate((100.0, 5.0)), Affine::translate((0.0, 5.0))];
|
||||
assert!(same_maps(&maps, &want), "{maps:?}");
|
||||
// Copies stop where the geometry pass stops them: none past its reach of 1e9 pt.
|
||||
let effects = [rasterize, transform(json!({"moveH": 1.0e7, "copies": 1000}))];
|
||||
let maps = crate::stage_maps(&effects, &[1], &staged).unwrap();
|
||||
assert_eq!(maps.len(), 100, "{}", maps.len());
|
||||
}
|
||||
|
||||
/// An SVG filter keeps its options: it paints in its own user space.
|
||||
@@ -781,7 +835,7 @@ fn a_groups_transform_moves_its_members_shadows() {
|
||||
}
|
||||
|
||||
/// A group's Transform effect that makes copies or moves at random leaves its members' shadows as
|
||||
/// they are, as it leaves the shadows listed before it in its own effects.
|
||||
/// they are.
|
||||
#[test]
|
||||
fn a_groups_copying_transform_leaves_its_members_shadows() {
|
||||
for params in [json!({"scaleH": 200, "scaleV": 200, "copies": 1}), json!({"scaleH": 200, "scaleV": 200, "random": true})] {
|
||||
@@ -792,6 +846,204 @@ fn a_groups_copying_transform_leaves_its_members_shadows() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A layer of `members` with `effects` of its own.
|
||||
fn layer(id: u64, members: Vec<Node>, effects: Vec<Effect>) -> Node {
|
||||
let mut l = Node::layer(NodeId(id), "Layer", vectorcraft_doc::LayerColor::Preset(0));
|
||||
if let Some(ch) = l.children_mut() {
|
||||
*ch = members.into_iter().map(std::sync::Arc::new).collect();
|
||||
}
|
||||
l.appearance.effects = effects;
|
||||
l
|
||||
}
|
||||
|
||||
/// The offset and blur of the Drop Shadow that each member of `art` draws of its own, in order.
|
||||
fn copy_shadows(art: &Node) -> Vec<(f64, f64, f64)> {
|
||||
art.children().into_iter().flatten().map(|c| drawn_shadow(&c.appearance.effects)).collect()
|
||||
}
|
||||
|
||||
fn close_all(a: &[(f64, f64, f64)], b: &[(f64, f64, f64)]) -> bool {
|
||||
a.len() == b.len() && a.iter().zip(b).all(|(x, y)| close(*x, *y))
|
||||
}
|
||||
|
||||
/// A group's or layer's Transform effect that makes copies gives each copy the shadow listed
|
||||
/// before it, moved, turned, reflected and scaled with that copy, the last copy lowest: drawn and
|
||||
/// baked. Each copy is a group holding all the members, which carry no shadow of their own, and
|
||||
/// the art paints none around all the copies. With Scale Strokes & Effects on, the shadow is not
|
||||
/// scaled a second time. A layer's art stays a layer.
|
||||
#[test]
|
||||
fn each_copy_of_a_groups_or_layers_transform_effect_carries_the_shadow_listed_before_it() {
|
||||
let cases = [
|
||||
(json!({"moveH": 100, "copies": 2}), vec![(10.0, 0.0, 4.0); 3]),
|
||||
// A turn of 90° counterclockwise on screen takes an offset to the right to one upward.
|
||||
(json!({"rotate": 90, "copies": 2}), vec![(-10.0, 0.0, 4.0), (0.0, -10.0, 4.0), (10.0, 0.0, 4.0)]),
|
||||
(json!({"reflectX": true, "moveH": 100, "copies": 1}), vec![(-10.0, 0.0, 4.0), (10.0, 0.0, 4.0)]),
|
||||
(json!({"scaleH": 200, "scaleV": 200, "moveH": 100, "copies": 1}), vec![(20.0, 0.0, 8.0), (10.0, 0.0, 4.0)]),
|
||||
(json!({"scaleH": 200, "scaleV": 200, "moveH": 100, "copies": 1, "strokes": true}), vec![(20.0, 0.0, 8.0), (10.0, 0.0, 4.0)]),
|
||||
];
|
||||
for (params, want) in cases {
|
||||
let offsets: Vec<(f64, f64)> = want.iter().map(|w| (w.0, w.1)).collect();
|
||||
for container in ["group", "layer"] {
|
||||
let members = vec![square(101, vec![]), square(102, vec![])];
|
||||
let effects = vec![shadow(10.0, 0.0, 4.0), transform(params.clone())];
|
||||
let n = if container == "group" { group(100, members, effects) } else { layer(100, members, effects) };
|
||||
assert!(crate::outer_effects(&n).iter().all(|e| e.id != "stylize.dropShadow"), "{params}: {container}");
|
||||
let art = crate::evaluate_container(None, &n).unwrap();
|
||||
assert_eq!(matches!(art.kind, vectorcraft_doc::NodeKind::Layer { .. }), container == "layer", "{params}: {container}");
|
||||
assert!(raster_effects(&art.appearance.effects).is_empty(), "{params}: {container} {:?}", art.appearance.effects);
|
||||
let drawn = copy_shadows(&art);
|
||||
assert!(close_all(&drawn, &want), "{params}: {container} {drawn:?}");
|
||||
assert_eq!(shadows_in(&art).len(), want.len(), "{params}: {container}: the members draw none");
|
||||
for c in art.children().into_iter().flatten() {
|
||||
assert!(matches!(c.kind, vectorcraft_doc::NodeKind::Group { .. }) && paths_in(c) == 2, "{params}: {container} {c:?}");
|
||||
}
|
||||
let b = baked(n);
|
||||
assert!(near(&shadows_in(&b), &offsets), "{params}: {container} baked {:?}", shadows_in(&b));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A group's copying Transform effect leaves its members' own shadows on each copy as they are,
|
||||
/// and a shadow listed after it paints once around all the copies. A clip group's copies each clip
|
||||
/// and carry the shadow, and the art clips nothing. A Transform effect that makes no copies, or has
|
||||
/// Transform Objects off, leaves the group's shadows on the group.
|
||||
#[test]
|
||||
fn a_groups_copying_transform_leaves_member_and_later_shadows_where_they_paint() {
|
||||
let g = group(
|
||||
110,
|
||||
vec![square(111, vec![shadow(5.0, 5.0, 0.0)]), square(112, vec![])],
|
||||
vec![shadow(10.0, 0.0, 0.0), transform(json!({"rotate": 90, "copies": 1})), shadow(0.0, 5.0, 0.0)],
|
||||
);
|
||||
assert_eq!(crate::outer_effects(&g).len(), 2);
|
||||
let art = crate::evaluate_container(None, &g).unwrap();
|
||||
assert!(near(&shadows_in(&art), &[(0.0, 5.0), (0.0, -10.0), (5.0, 5.0), (10.0, 0.0), (5.0, 5.0)]), "{:?}", shadows_in(&art));
|
||||
|
||||
let mut clip = square(121, vec![]);
|
||||
if let vectorcraft_doc::NodeKind::Path { clipping, .. } = &mut clip.kind {
|
||||
*clipping = true;
|
||||
}
|
||||
let mut g = group(120, vec![clip, square(122, vec![])], vec![shadow(10.0, 0.0, 0.0), transform(json!({"moveH": 100, "copies": 1}))]);
|
||||
if let vectorcraft_doc::NodeKind::Group { clip, .. } = &mut g.kind {
|
||||
*clip = true;
|
||||
}
|
||||
let art = crate::evaluate_container(None, &g).unwrap();
|
||||
assert!(!art.clips());
|
||||
assert!(art.children().into_iter().flatten().all(|c| c.clips()), "{art:?}");
|
||||
assert!(close_all(©_shadows(&art), &[(10.0, 0.0, 0.0), (10.0, 0.0, 0.0)]), "{:?}", copy_shadows(&art));
|
||||
|
||||
for params in [json!({"rotate": 90}), json!({"rotate": 90, "copies": 1, "objects": false})] {
|
||||
let g = group(130, vec![square(131, vec![]), square(132, vec![])], vec![shadow(10.0, 0.0, 0.0), transform(params.clone())]);
|
||||
assert_eq!(crate::outer_effects(&g).len(), 2, "{params}");
|
||||
let art = crate::evaluate_container(None, &g).unwrap();
|
||||
assert_eq!(raster_effects(&art.appearance.effects).len(), 1, "{params}: the group keeps its shadow");
|
||||
}
|
||||
}
|
||||
|
||||
/// Copies of a group that stop at the effect budget each keep their shadow: no copy goes without
|
||||
/// one, and no shadow is left without its copy.
|
||||
#[test]
|
||||
fn a_groups_copies_past_the_budget_each_keep_their_shadow() {
|
||||
let g = group(140, vec![path_node(141, wavy(30_000), vec![])], vec![shadow(1.0, 0.5, 0.0), transform(json!({"moveV": 50, "copies": 1000}))]);
|
||||
let art = crate::evaluate_container(None, &g).unwrap();
|
||||
let paths = paths_in(&art);
|
||||
assert!(paths > 1 && paths < 1001, "{paths}");
|
||||
assert_eq!(shadows_in(&art).len(), paths);
|
||||
}
|
||||
|
||||
/// A layer's ruler guides stay once above the copies of its Transform effect, and carry no shadow.
|
||||
#[test]
|
||||
fn a_layers_guides_stay_once_above_copies_that_carry_its_shadow() {
|
||||
let guide = Node::new(NodeId(152), vectorcraft_doc::NodeKind::RulerGuide { vertical: true, pos: 3.0, artboard: None });
|
||||
let l = layer(150, vec![square(151, vec![]), guide], vec![shadow(10.0, 0.0, 0.0), transform(json!({"moveH": 100, "copies": 2}))]);
|
||||
let art = crate::evaluate_container(None, &l).unwrap();
|
||||
let ch = art.children().unwrap();
|
||||
assert_eq!(ch.len(), 4, "three copies, then the guide");
|
||||
assert!(ch[3].is_ruler_guide() && ch.iter().filter(|c| c.is_ruler_guide()).count() == 1);
|
||||
assert_eq!(shadows_in(&art).len(), 3);
|
||||
}
|
||||
|
||||
/// The bounds of every node with `id` under `art`, in order.
|
||||
fn bounds_of(art: &Node, id: u64) -> Vec<Rect> {
|
||||
let mut out = vec![];
|
||||
art.walk(&mut |m| {
|
||||
if m.id == NodeId(id)
|
||||
&& let Some(b) = m.geometric_bounds()
|
||||
{
|
||||
out.push(b);
|
||||
}
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
fn rects_near(a: &[Rect], b: &[Rect]) -> bool {
|
||||
let near = |p: f64, q: f64| (p - q).abs() < 1e-6;
|
||||
a.len() == b.len() && a.iter().zip(b).all(|(p, q)| near(p.x0, q.x0) && near(p.y0, q.y0) && near(p.x1, q.x1) && near(p.y1, q.y1))
|
||||
}
|
||||
|
||||
/// A group with a fill of its own and only a shadow before its copying Transform effect applies
|
||||
/// its members' own effects before it copies them, as a group without a fill does: a member's own
|
||||
/// move is turned with each copy.
|
||||
#[test]
|
||||
fn a_painted_groups_copies_take_their_members_own_effects_first() {
|
||||
let members = || vec![square(171, vec![transform(json!({"moveH": 40}))]), square(172, vec![])];
|
||||
let effects = || vec![shadow(10.0, 0.0, 0.0), transform(json!({"rotate": 90, "copies": 1}))];
|
||||
let plain = crate::evaluate_container(None, &group(170, members(), effects())).unwrap();
|
||||
let mut painted = group(170, members(), effects());
|
||||
*painted.appearance = Appearance::basic(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), Paint::None, 0.0);
|
||||
painted.appearance.effects = effects();
|
||||
let art = crate::evaluate_container(None, &painted).unwrap();
|
||||
let (want, got) = (bounds_of(&plain, 171), bounds_of(&art, 171));
|
||||
assert!(!want.is_empty());
|
||||
assert!(rects_near(&got, &want), "{got:?} {want:?}");
|
||||
}
|
||||
|
||||
/// A layer's copies are made about the bounds of its visible members, as the layer measures them:
|
||||
/// a hidden member does not move the center that a reflected copy turns about.
|
||||
#[test]
|
||||
fn a_layers_copies_leave_its_hidden_members_out_of_their_reference() {
|
||||
let mut hidden = path_node(182, shapes::rectangle(Rect::new(1000.0, 0.0, 1050.0, 50.0)), vec![]);
|
||||
hidden.visible = false;
|
||||
let l = layer(180, vec![square(181, vec![]), hidden], vec![shadow(10.0, 0.0, 0.0), transform(json!({"reflectX": true, "copies": 1}))]);
|
||||
let art = crate::evaluate_container(None, &l).unwrap();
|
||||
let got = bounds_of(&art, 181);
|
||||
assert!(rects_near(&got, &[Rect::new(0.0, 0.0, 50.0, 50.0); 2]), "{got:?}");
|
||||
}
|
||||
|
||||
/// A shadow carried by the copies of an earlier copying Transform effect of a group turns with each
|
||||
/// copy of a later one, drawn and baked.
|
||||
#[test]
|
||||
fn a_groups_later_copying_transform_turns_the_shadows_of_earlier_copies() {
|
||||
let g = || {
|
||||
group(
|
||||
190,
|
||||
vec![square(191, vec![])],
|
||||
vec![shadow(10.0, 0.0, 0.0), transform(json!({"moveH": 100, "copies": 1})), transform(json!({"rotate": 90, "copies": 1}))],
|
||||
)
|
||||
};
|
||||
let want = [(0.0, -10.0), (0.0, -10.0), (10.0, 0.0), (10.0, 0.0)];
|
||||
let art = crate::evaluate_container(None, &g()).unwrap();
|
||||
assert!(near(&shadows_in(&art), &want), "{:?}", shadows_in(&art));
|
||||
let b = baked(g());
|
||||
assert!(near(&shadows_in(&b), &want), "baked {:?}", shadows_in(&b));
|
||||
}
|
||||
|
||||
/// A group holding type whose Transform effect only moves its copies, baked for export, gives each
|
||||
/// copy the shadow listed before that effect, as the canvas draws it, rather than keeping the type
|
||||
/// as type under one shadow around all the copies. Built without fonts, type lays out no glyphs
|
||||
/// and the test is skipped.
|
||||
#[test]
|
||||
fn a_baked_group_with_type_keeps_a_shadow_on_each_copy() {
|
||||
use vectorcraft_doc::text::{CharStyle, TextObject};
|
||||
let style = CharStyle { size: 40.0, fill: Paint::solid(Color::BLACK), ..Default::default() };
|
||||
let words = Node::new(NodeId(161), vectorcraft_doc::NodeKind::Text(Box::new(TextObject::point(Point::new(5.0, 60.0), "IIII", style))));
|
||||
if !crate::outline_text(&words).is_some_and(|o| paths_in(&o) > 0) {
|
||||
eprintln!("skipped: built without fonts (enable vectorcraft-text's bundled-fonts to run it)");
|
||||
return;
|
||||
}
|
||||
let g = group(160, vec![words, square(162, vec![])], vec![shadow(10.0, 0.0, 0.0), transform(json!({"moveH": 150, "copies": 1}))]);
|
||||
let b = baked(g);
|
||||
assert!(near(&shadows_in(&b), &[(10.0, 0.0), (10.0, 0.0)]), "{:?}", shadows_in(&b));
|
||||
}
|
||||
|
||||
/// The Transform effects inside a group apply before the group's: a member's own turn of 90°
|
||||
/// applies to its shadow before the group's uneven scale does, for the member's own shadow, its
|
||||
/// fill's shadow, and the shadow of a member of a nested group that has the turn.
|
||||
|
||||
@@ -71,7 +71,7 @@ pub fn seg_cubic(sp: &SubPath, i: usize) -> CubicBez {
|
||||
|
||||
/// Non-linear path mapping (shared with live envelopes in `vectorcraft-doc`), and the split of
|
||||
/// segments into pieces within an anchor budget.
|
||||
pub use vectorcraft_doc::live::{fit_piece, map_nonlinear_within, pieces};
|
||||
pub use vectorcraft_doc::live::{fit_piece, map_nonlinear_within, map_smooth_within, pieces};
|
||||
|
||||
/// About how many lines the renderer flattens `path` into at 1 px/pt: one for a straight
|
||||
/// segment, and for a curve the count Wang's formula gives at vello's tolerance of 0.25 px,
|
||||
|
||||
@@ -47,6 +47,7 @@ vectorcraft-js = { workspace = true }
|
||||
vectorcraft-apischema = { workspace = true }
|
||||
image = { workspace = true }
|
||||
craft-image-codecs = { workspace = true }
|
||||
tiff = { workspace = true }
|
||||
jxl-oxide = { workspace = true }
|
||||
jxl-color = { workspace = true }
|
||||
jxl-grid = { workspace = true }
|
||||
@@ -69,8 +70,9 @@ log = { workspace = true }
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
rustix = { workspace = true, features = ["std", "process"] }
|
||||
|
||||
# Whether a recovery area's lock file is still the one that was opened (`FolderStore::still_named`).
|
||||
# Already in Cargo.lock (walkdir), so this adds no new crate.
|
||||
# Whether a recovery area's lock file is still the one that was opened (`FolderStore::still_named`),
|
||||
# and whether two paths a script names are one file (`script::files`). Already in Cargo.lock
|
||||
# (walkdir), so this adds no new crate.
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
same-file = "1.0.6"
|
||||
|
||||
@@ -88,7 +90,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 +99,8 @@ proptest = { workspace = true }
|
||||
vectorcraft-text = { workspace = true, features = ["test-fonts"] }
|
||||
# How many times an open reads a PDF.
|
||||
vectorcraft-pdf = { workspace = true, features = ["read-count"] }
|
||||
# How many times the symbol list is read to find symbols by name.
|
||||
vectorcraft-doc = { workspace = true, features = ["symbol-read-count"] }
|
||||
wat = { workspace = true }
|
||||
# Zstandard streams for the Illustrator editing data fuzz tests.
|
||||
ruzstd = { workspace = true }
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
//! `cargo run --release -p vectorcraft-engine --example cut_path_select_bench` prints the time
|
||||
//! Cut Path at Selected Anchor Points takes to select the cut ends, on synthetic documents of 500,
|
||||
//! 2,000 and 5,000 open paths of 10 anchors each with the 8 anchors between the ends of each
|
||||
//! direct-selected, and on one path of 2,000 open subpaths selected the same way. For each it times two ways of building the same
|
||||
//! selection from the cut ends: clearing the selection and adding each path in turn (each add looks
|
||||
//! through the paths already added), and one `Selection::set` call followed by the anchors. It
|
||||
//! checks that both give the same selection, every field, before it times them, and then times the
|
||||
//! whole command once per run on the 2,000-path document.
|
||||
//! `ITERS` sets the runs per row (default 7); the two ways run in alternating order, each run
|
||||
//! builds the selection 20 times, and each row is the median time of one build. On Linux the times are the CPU time of the main thread, which runs everything, in
|
||||
//! ms; elsewhere they are wall times.
|
||||
// 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::hint::black_box;
|
||||
use std::time::Instant;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, Document, Node, NodeId, Selection};
|
||||
use vectorcraft_engine::Session;
|
||||
use vectorcraft_geom::{Anchor, PathData, Point, SubPath};
|
||||
|
||||
/// The anchors of each path, or of each subpath of the one compound path.
|
||||
const ANCHORS: usize = 10;
|
||||
|
||||
/// The builds of the selection in each timed run; a row gives the time of one build.
|
||||
const REPS: usize = 20;
|
||||
|
||||
/// What the command selects for one cut end: the path and its anchor (subpath, anchor).
|
||||
type Pick = (NodeId, (usize, usize));
|
||||
|
||||
/// A way of building the selection from the cut ends.
|
||||
type Rebuild = fn(&mut Selection, &[Pick]);
|
||||
|
||||
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 CPU time of the calling thread in ns, from `/proc/thread-self/schedstat` (Linux only).
|
||||
fn thread_cpu_ns() -> Option<u64> {
|
||||
std::fs::read_to_string("/proc/thread-self/schedstat").ok()?.split_whitespace().next()?.parse().ok()
|
||||
}
|
||||
|
||||
/// The time `f` takes, in ms: CPU time where the system reports it, wall time otherwise.
|
||||
fn measure(f: impl FnOnce()) -> f64 {
|
||||
match thread_cpu_ns() {
|
||||
Some(start) => {
|
||||
f();
|
||||
thread_cpu_ns().map_or(f64::NAN, |end| end.saturating_sub(start) as f64 / 1e6)
|
||||
}
|
||||
None => {
|
||||
let t = Instant::now();
|
||||
f();
|
||||
t.elapsed().as_secs_f64() * 1000.0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The selection built by clearing it and adding each path in turn.
|
||||
fn one_by_one(sel: &mut Selection, picked: &[Pick]) {
|
||||
sel.clear();
|
||||
for (id, a) in picked {
|
||||
sel.add(*id);
|
||||
sel.anchors.entry(*id).or_default().insert(*a);
|
||||
}
|
||||
}
|
||||
|
||||
/// The selection built with one `Selection::set` call, as the command builds it.
|
||||
fn one_call(sel: &mut Selection, picked: &[Pick]) {
|
||||
sel.set(picked.iter().map(|(id, _)| *id));
|
||||
for (id, a) in picked {
|
||||
sel.anchors.entry(*id).or_default().insert(*a);
|
||||
}
|
||||
}
|
||||
|
||||
fn exec(s: &mut Session, cmd: &str, p: Value) -> Value {
|
||||
s.execute(cmd, &p).unwrap_or_else(|e| panic!("{cmd}: {e}"))
|
||||
}
|
||||
|
||||
/// An open subpath of [`ANCHORS`] corner anchors 10 pt apart along row `row`.
|
||||
fn row(row: usize) -> SubPath {
|
||||
let y = row as f64 * 20.0;
|
||||
SubPath::new((0..ANCHORS).map(|i| Anchor::corner(Point::new(i as f64 * 10.0, y))).collect(), false)
|
||||
}
|
||||
|
||||
/// A session with the paths in `paths` and every anchor of theirs but the two ends of each
|
||||
/// subpath direct-selected (a path with all its anchors selected counts as selected whole).
|
||||
fn fixture(paths: Vec<PathData>) -> Session {
|
||||
let mut doc = Document::new(1600.0, 1200.0);
|
||||
let l = doc.layers.first().map(|l| l.id);
|
||||
let mut items = vec![];
|
||||
for pd in paths {
|
||||
let id = doc.alloc_id();
|
||||
let refs: Vec<[usize; 2]> =
|
||||
pd.subpaths.iter().enumerate().flat_map(|(si, sp)| (1..sp.anchors.len().saturating_sub(1)).map(move |ai| [si, ai])).collect();
|
||||
doc.insert(l, usize::MAX, Node::path(id, pd, Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0))).unwrap();
|
||||
items.push(json!({"id": id.0, "anchors": refs}));
|
||||
}
|
||||
let mut s = Session::new();
|
||||
s.add_document(doc, None);
|
||||
exec(&mut s, "select.anchorsMany", json!({"items": items}));
|
||||
s
|
||||
}
|
||||
|
||||
/// The cut ends the command selects, in the order it selects them: read back from the selection it
|
||||
/// leaves, which holds each cut path once in that order.
|
||||
fn picked_after_cut(s: &Session) -> Vec<Pick> {
|
||||
let sel = &s.doc().unwrap().selection;
|
||||
sel.objects.iter().flat_map(|id| sel.anchors[id].iter().map(move |a| (*id, *a))).collect()
|
||||
}
|
||||
|
||||
fn bench(name: &str, paths: impl Fn() -> Vec<PathData>) {
|
||||
let mut s = fixture(paths());
|
||||
exec(&mut s, "path.cutAtAnchors", json!({}));
|
||||
let picked = picked_after_cut(&s);
|
||||
let mut start = Selection::default();
|
||||
one_by_one(&mut start, &[(NodeId(u64::MAX), (0, 3))]);
|
||||
let (mut a, mut b) = (start.clone(), start.clone());
|
||||
one_by_one(&mut a, &picked);
|
||||
one_call(&mut b, &picked);
|
||||
assert_eq!(a, b, "both ways give the same selection");
|
||||
assert_eq!(b, s.doc().unwrap().selection, "the command gives that selection");
|
||||
let (mut old, mut new) = (vec![], vec![]);
|
||||
for i in 0..iters() {
|
||||
let run = |f: Rebuild, out: &mut Vec<f64>| {
|
||||
let ms = measure(|| {
|
||||
for _ in 0..REPS {
|
||||
let mut sel = start.clone();
|
||||
f(&mut sel, black_box(&picked));
|
||||
black_box(&sel);
|
||||
}
|
||||
});
|
||||
out.push(ms / REPS as f64);
|
||||
};
|
||||
if i % 2 == 0 {
|
||||
run(one_by_one, &mut old);
|
||||
run(one_call, &mut new);
|
||||
} else {
|
||||
run(one_call, &mut new);
|
||||
run(one_by_one, &mut old);
|
||||
}
|
||||
}
|
||||
let (old, new) = (median(old), median(new));
|
||||
println!(" {name:<44} {:>7} {:>6} {old:>12.3} {new:>12.3} {:>8.1}x", picked.len(), b.objects.len(), old / new);
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let unit = if thread_cpu_ns().is_some() { "CPU ms" } else { "wall ms" };
|
||||
println!(" {:<44} {:>7} {:>6} {:>12} {:>12} {:>9}", "document", "picked", "ids", format!("add, {unit}"), format!("set, {unit}"), "speedup");
|
||||
for n in [500, 2_000, 5_000] {
|
||||
bench(&format!("{n} open paths, {ANCHORS} anchors each"), || (0..n).map(|i| PathData::single(row(i))).collect());
|
||||
}
|
||||
bench("one path of 2,000 open subpaths", || vec![PathData::new((0..2_000).map(row).collect())]);
|
||||
let whole: Vec<f64> = (0..iters())
|
||||
.map(|_| {
|
||||
let mut s = fixture((0..2_000).map(|i| PathData::single(row(i))).collect());
|
||||
measure(|| drop(black_box(exec(&mut s, "path.cutAtAnchors", json!({})))))
|
||||
})
|
||||
.collect();
|
||||
println!(" path.cutAtAnchors, 2,000 open paths, whole command: {:.3} {unit}", median(whole));
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
//! `cargo run --release -p vectorcraft-engine --example direction_handles_bench` prints the time
|
||||
//! Select › Object › Direction Handles takes to select every path of documents of 2,000, 10,000 and
|
||||
//! 20,000 rectangles, spread over two layers with one group. For each size it times, on the same
|
||||
//! paths and anchors, the selection built one path at a time (a clear, then an add per path) and
|
||||
//! the selection built with one `Selection::set` call, checks that the two are equal, and then
|
||||
//! times the whole `select.object.directionHandles` command.
|
||||
//! On Linux each row is the thread's CPU time, read from `/proc/thread-self/schedstat`; elsewhere
|
||||
//! it is wall time, and the first line says which. `ITERS` sets the runs per row (default 7); each
|
||||
//! row is the median in ms. A run of the two selection rows repeats the selection 1,000,000 / paths
|
||||
//! times and gives the time of one.
|
||||
// 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::BTreeSet;
|
||||
use std::hint::black_box;
|
||||
use std::time::Instant;
|
||||
|
||||
use serde_json::json;
|
||||
use vectorcraft_color::Color;
|
||||
use vectorcraft_doc::{Document, NodeId, Selection};
|
||||
use vectorcraft_engine::Session;
|
||||
use vectorcraft_geom::Rect;
|
||||
use vectorcraft_testkit::fixtures::DocBuilder;
|
||||
|
||||
type Items = Vec<(NodeId, BTreeSet<(usize, usize)>)>;
|
||||
|
||||
fn iters() -> usize {
|
||||
std::env::var("ITERS").ok().and_then(|v| v.parse().ok()).unwrap_or(7)
|
||||
}
|
||||
|
||||
/// The thread's CPU time in ns, or `None` where `/proc/thread-self/schedstat` cannot be read.
|
||||
fn cpu_ns() -> Option<u64> {
|
||||
std::fs::read_to_string("/proc/thread-self/schedstat").ok()?.split_whitespace().next()?.parse().ok()
|
||||
}
|
||||
|
||||
/// The time `f` takes in ms: CPU time when [`cpu_ns`] reads, wall time otherwise.
|
||||
fn ms(f: impl FnOnce()) -> f64 {
|
||||
let (cpu, wall) = (cpu_ns(), Instant::now());
|
||||
f();
|
||||
match (cpu, cpu_ns()) {
|
||||
(Some(a), Some(b)) => (b - a) as f64 / 1e6,
|
||||
_ => wall.elapsed().as_secs_f64() * 1000.0,
|
||||
}
|
||||
}
|
||||
|
||||
fn median(mut v: Vec<f64>) -> f64 {
|
||||
v.sort_by(f64::total_cmp);
|
||||
v[v.len() / 2]
|
||||
}
|
||||
|
||||
/// `n` 10 pt squares: a tenth of them in one group and the rest loose, half on each of two layers.
|
||||
fn document(n: usize) -> Document {
|
||||
let mut b = DocBuilder::new(4000.0, 4000.0);
|
||||
let square = |b: &mut DocBuilder, i: usize| {
|
||||
let (x, y) = ((i % 200) as f64 * 12.0, (i / 200) as f64 * 12.0);
|
||||
b.rect_node(Rect::new(x, y, x + 10.0, y + 10.0), Color::rgb(0.2, 0.4, 0.6))
|
||||
};
|
||||
let grouped = n / 10;
|
||||
let kids = (0..grouped).map(|i| square(&mut b, i)).collect();
|
||||
b.group(kids, false);
|
||||
for i in grouped..n {
|
||||
if i == n / 2 {
|
||||
b.layer("Layer 2");
|
||||
}
|
||||
let node = square(&mut b, i);
|
||||
b.add(node);
|
||||
}
|
||||
b.build()
|
||||
}
|
||||
|
||||
/// Selects `items` one path at a time: a clear, then an add and an anchor insert per path.
|
||||
fn one_by_one(sel: &mut Selection, items: Items) {
|
||||
sel.clear();
|
||||
for (id, refs) in items {
|
||||
sel.add(id);
|
||||
sel.anchors.insert(id, refs);
|
||||
}
|
||||
}
|
||||
|
||||
/// Selects `items` with one `Selection::set` call and one extend of the anchors.
|
||||
fn with_set(sel: &mut Selection, items: Items) {
|
||||
sel.set(items.iter().map(|(id, _)| *id));
|
||||
sel.anchors.extend(items);
|
||||
}
|
||||
|
||||
fn row(name: &str, ms: f64) {
|
||||
println!(" {name:<44} {ms:>10.3} ms");
|
||||
}
|
||||
|
||||
fn bench(n: usize) {
|
||||
println!("{n} paths");
|
||||
let mut s = Session::new();
|
||||
s.add_document(document(n), None);
|
||||
s.execute("select.all", &json!({})).unwrap();
|
||||
let start = s.doc().unwrap().selection.clone();
|
||||
s.execute("select.object.directionHandles", &json!({})).unwrap();
|
||||
let command = s.doc().unwrap().selection.clone();
|
||||
// The paths and anchors the command selects, in its order.
|
||||
let items: Items = command.objects.iter().map(|id| (*id, command.anchors[id].clone())).collect();
|
||||
assert_eq!(items.len(), n);
|
||||
|
||||
// Each run selects `reps` times, on copies made before the clock starts, and gives the time of one.
|
||||
let reps = (1_000_000 / n).max(1);
|
||||
let time = |f: fn(&mut Selection, Items)| -> (f64, Selection) {
|
||||
let mut last = Selection::default();
|
||||
let runs = (0..iters())
|
||||
.map(|_| {
|
||||
let mut work: Vec<(Selection, Items)> = (0..reps).map(|_| (start.clone(), items.clone())).collect();
|
||||
let t = ms(|| {
|
||||
for (sel, it) in &mut work {
|
||||
f(sel, black_box(std::mem::take(it)));
|
||||
}
|
||||
});
|
||||
last = work.pop().unwrap().0;
|
||||
t / reps as f64
|
||||
})
|
||||
.collect();
|
||||
(median(runs), last)
|
||||
};
|
||||
let (old, a) = time(one_by_one);
|
||||
let (new, b) = time(with_set);
|
||||
assert_eq!(a, b, "both ways give the same selection");
|
||||
let mut want = start.clone();
|
||||
with_set(&mut want, items.clone());
|
||||
assert_eq!(want.objects, command.objects);
|
||||
assert_eq!(want.anchors, command.anchors);
|
||||
row("selection, one add per path", old);
|
||||
row("selection, one set call", new);
|
||||
println!(" {:<44} {:>10.1}x", "ratio", old / new);
|
||||
|
||||
let runs = (0..iters())
|
||||
.map(|_| {
|
||||
s.execute("select.all", &json!({})).unwrap();
|
||||
ms(|| drop(black_box(s.execute("select.object.directionHandles", &json!({})).unwrap())))
|
||||
})
|
||||
.collect();
|
||||
row("select.object.directionHandles, whole command", median(runs));
|
||||
}
|
||||
|
||||
fn main() {
|
||||
println!("{}", if cpu_ns().is_some() { "thread CPU time, median of runs" } else { "wall time, median of runs" });
|
||||
for n in [2_000, 10_000, 20_000] {
|
||||
bench(n);
|
||||
}
|
||||
}
|
||||
@@ -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)));
|
||||
}
|
||||
}
|
||||
@@ -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};
|
||||
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
),
|
||||
|
||||
@@ -4,6 +4,8 @@
|
||||
//! be edited, selected or not. What it removes is worked out by
|
||||
//! [`vectorcraft_tools::addons::trim::plan`], which the tool also uses to show it beforehand.
|
||||
|
||||
use std::collections::HashSet;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{NodeId, NodeKind};
|
||||
use vectorcraft_geom::{Point, Rect};
|
||||
@@ -33,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
|
||||
)]
|
||||
@@ -100,20 +102,21 @@ fn trim(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
compounds.dedup();
|
||||
let mut beside = Beside::replacing(d, &trimmed);
|
||||
let mut all = vec![];
|
||||
// The selection is read through a set and changed once at the end, so a trim of many
|
||||
// paths does not go through the selected objects once per path and per piece.
|
||||
let mut selected_ids: HashSet<NodeId> = sel.objects.iter().copied().collect();
|
||||
let mut joining: Vec<NodeId> = vec![];
|
||||
let mut gone: Vec<NodeId> = vec![];
|
||||
for (id, pieces) in plan {
|
||||
let selected = sel.contains(id);
|
||||
let selected = selected_ids.contains(&id);
|
||||
sel.anchors.remove(&id);
|
||||
sel.segments.remove(&id);
|
||||
let made = replace_with_pieces(d, &mut beside, id, pieces)?;
|
||||
// The pieces of a selected path are selected; what was not selected stays so.
|
||||
if made.is_empty() {
|
||||
sel.remove(id);
|
||||
gone.push(id);
|
||||
} else if selected {
|
||||
for n in &made {
|
||||
if !sel.contains(*n) {
|
||||
sel.add(*n);
|
||||
}
|
||||
}
|
||||
joining.extend(made.iter().copied().filter(|n| selected_ids.insert(*n)));
|
||||
}
|
||||
all.extend(made);
|
||||
}
|
||||
@@ -121,9 +124,15 @@ fn trim(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
for c in compounds {
|
||||
if d.node(c).is_some_and(|n| n.children().is_some_and(|ch| ch.is_empty())) {
|
||||
d.remove(c)?;
|
||||
sel.remove(c);
|
||||
gone.push(c);
|
||||
}
|
||||
}
|
||||
sel.remove_all(gone);
|
||||
if let Some((first, rest)) = joining.split_first() {
|
||||
// `add` clears what any change to the object selection clears; the rest are new ids.
|
||||
sel.add(*first);
|
||||
sel.objects.extend_from_slice(rest);
|
||||
}
|
||||
Ok(all)
|
||||
})?;
|
||||
Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "removed": removed }))
|
||||
|
||||
@@ -2,8 +2,9 @@
|
||||
//! one undo step, and what takes no part.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{NodeId, NodeKind};
|
||||
use vectorcraft_doc::{NodeId, NodeKind, Selection};
|
||||
use vectorcraft_geom::{PathData, Point};
|
||||
use vectorcraft_tools::addons::trim::plan::{self, Limits, Stretches};
|
||||
|
||||
use crate::Session;
|
||||
|
||||
@@ -420,6 +421,139 @@ fn the_selection_stays_as_it_was_and_the_pieces_of_a_selected_path_are_selected(
|
||||
assert!(s.doc().unwrap().selection.is_empty(), "a removed path leaves the selection");
|
||||
}
|
||||
|
||||
/// Run the command with `p`, and check that it leaves the selection exactly as changing it one
|
||||
/// id at a time does: for each trimmed path in the plan's order, its anchors and segments let go,
|
||||
/// a path with no pieces left removed, and each piece of a selected path added; then each emptied
|
||||
/// compound path removed. Returns the selection.
|
||||
fn same_selection_as_one_id_at_a_time(s: &mut Session, p: Value) -> Selection {
|
||||
let st = s.doc().unwrap();
|
||||
let pick = super::pick(&p).unwrap();
|
||||
let root = crate::cmd::ordinary_isolation(st);
|
||||
let plan: Vec<(NodeId, usize)> =
|
||||
plan::plan(&st.doc, root, &pick, Limits::COMMAND, &mut Stretches::default()).unwrap().into_iter().map(|t| (t.id, t.pieces.len())).collect();
|
||||
let mut compounds: Vec<NodeId> = plan
|
||||
.iter()
|
||||
.filter_map(|(id, _)| st.doc.parent_of(*id))
|
||||
.filter(|c| matches!(st.doc.node(*c).map(|n| &n.kind), Some(NodeKind::Compound { .. })))
|
||||
.collect();
|
||||
compounds.dedup();
|
||||
let mut want = st.selection.clone();
|
||||
let made = ids(&s.execute(TRIM, &p).unwrap());
|
||||
assert_eq!(made.len(), plan.iter().map(|(_, n)| n).sum::<usize>());
|
||||
let mut made = made.into_iter();
|
||||
for (id, n) in plan {
|
||||
let selected = want.contains(id);
|
||||
want.anchors.remove(&id);
|
||||
want.segments.remove(&id);
|
||||
let pieces: Vec<NodeId> = made.by_ref().take(n).collect();
|
||||
if pieces.is_empty() {
|
||||
want.remove(id);
|
||||
} else if selected {
|
||||
for piece in pieces {
|
||||
if !want.contains(piece) {
|
||||
want.add(piece);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let st = s.doc().unwrap();
|
||||
for c in compounds {
|
||||
if st.doc.node(c).is_none() {
|
||||
want.remove(c);
|
||||
}
|
||||
}
|
||||
want.prune(&st.doc);
|
||||
assert_eq!(st.selection, want);
|
||||
st.selection.clone()
|
||||
}
|
||||
|
||||
/// Two lines across split by a rectangle, one of them selected; a selected line nothing crosses
|
||||
/// and a selected compound path of two such lines, which the rectangle removes whole; and a
|
||||
/// selected line elsewhere with an anchor and a segment direct-selected. Returns (the selected
|
||||
/// line across, the line removed whole, the compound path, the line elsewhere).
|
||||
fn trim_scene(s: &mut Session) -> (NodeId, NodeId, NodeId, NodeId) {
|
||||
let (h, ..) = across_and_uprights(s);
|
||||
line(s, &[(0.0, 120.0), (300.0, 120.0)], false);
|
||||
let alone = line(s, &[(145.0, 200.0), (155.0, 200.0)], false);
|
||||
let c1 = line(s, &[(145.0, 170.0), (155.0, 170.0)], false);
|
||||
let c2 = line(s, &[(145.0, 180.0), (155.0, 180.0)], false);
|
||||
s.execute("select.set", &json!({"ids": [c1.0, c2.0]})).unwrap();
|
||||
let compound = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
let elsewhere = line(s, &[(0.0, 250.0), (10.0, 250.0), (20.0, 250.0)], false);
|
||||
s.execute("select.set", &json!({"ids": [elsewhere.0, h.0, alone.0, compound.0]})).unwrap();
|
||||
s.edit("direct", |_, sel| {
|
||||
sel.anchors.insert(elsewhere, [(0, 1)].into());
|
||||
sel.anchors.insert(h, [(0, 0)].into());
|
||||
sel.segments.insert(elsewhere, [(0, 0)].into());
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
(h, alone, compound, elsewhere)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_selection_after_a_trim_is_the_one_changing_it_one_id_at_a_time_gives() {
|
||||
// A removed key object stops being the key.
|
||||
let mut s = session();
|
||||
let (h, alone, compound, elsewhere) = trim_scene(&mut s);
|
||||
s.edit("key", |_, sel| {
|
||||
sel.key = Some(alone);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let sel = same_selection_as_one_id_at_a_time(&mut s, json!({"rect": [140, 90, 20, 120]}));
|
||||
assert_eq!(sel.key, None);
|
||||
assert!(!sel.contains(alone) && !sel.contains(compound));
|
||||
assert_eq!(&sel.objects[..2], [elsewhere, h]);
|
||||
assert_eq!(sel.objects.len(), 3, "{:?}", sel.objects);
|
||||
assert!(sel.anchors.contains_key(&elsewhere) && sel.segments.contains_key(&elsewhere) && !sel.anchors.contains_key(&h));
|
||||
// A key object that keeps its first piece stays the key.
|
||||
let mut s = session();
|
||||
let (h, alone, compound, _) = trim_scene(&mut s);
|
||||
s.edit("key", |_, sel| {
|
||||
sel.key = Some(h);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let sel = same_selection_as_one_id_at_a_time(&mut s, json!({"rect": [140, 90, 20, 120]}));
|
||||
assert_eq!(sel.key, Some(h));
|
||||
assert!(!sel.contains(alone) && !sel.contains(compound));
|
||||
// Trimming only paths that are not selected leaves a targeted object targeted.
|
||||
let mut s = session();
|
||||
let (h, _, _, elsewhere) = trim_scene(&mut s);
|
||||
s.execute("select.set", &json!({"ids": [elsewhere.0]})).unwrap();
|
||||
s.edit("target", |_, sel| {
|
||||
sel.target = Some(elsewhere);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let sel = same_selection_as_one_id_at_a_time(&mut s, json!({"rect": [140, 90, 20, 40]}));
|
||||
assert_eq!((sel.objects.as_slice(), sel.target), ([elsewhere].as_slice(), Some(elsewhere)));
|
||||
assert!(exists(&s, h));
|
||||
// A selected path that gains a piece changes the object selection, which lets go of the target.
|
||||
let mut s = session();
|
||||
let (h, _, _, elsewhere) = trim_scene(&mut s);
|
||||
s.execute("select.set", &json!({"ids": [elsewhere.0, h.0]})).unwrap();
|
||||
s.edit("target", |_, sel| {
|
||||
sel.target = Some(elsewhere);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let sel = same_selection_as_one_id_at_a_time(&mut s, json!({"rect": [140, 90, 20, 40]}));
|
||||
assert_eq!((sel.objects.len(), sel.target), (3, None));
|
||||
// So does a selected path that is removed whole.
|
||||
let mut s = session();
|
||||
let (_, alone, _, elsewhere) = trim_scene(&mut s);
|
||||
s.execute("select.set", &json!({"ids": [elsewhere.0, alone.0]})).unwrap();
|
||||
s.edit("target", |_, sel| {
|
||||
sel.target = Some(elsewhere);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let sel = same_selection_as_one_id_at_a_time(&mut s, json!({"rect": [140, 190, 20, 20]}));
|
||||
assert_eq!((sel.objects.as_slice(), sel.target), ([elsewhere].as_slice(), None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn many_paths_far_from_the_trimmed_one_cost_no_crossing_search() {
|
||||
let mut s = session();
|
||||
@@ -648,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");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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()) }))
|
||||
}
|
||||
@@ -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");
|
||||
}
|
||||
@@ -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)")))?;
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -1,19 +1,21 @@
|
||||
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 ----------
|
||||
|
||||
/// Brushable nodes (paths and compound paths) under `ids`.
|
||||
/// Brushable nodes (paths and compound paths) under `ids`, in walk order, each listed once where it is first reached.
|
||||
pub(crate) fn brush_targets(d: &Document, ids: &[NodeId]) -> Vec<NodeId> {
|
||||
let mut out = vec![];
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
for id in ids {
|
||||
let Some(n) = d.node(*id) else { continue };
|
||||
n.walk(&mut |c| {
|
||||
let own = matches!(c.kind, NodeKind::Path { guide: false, clipping: false, .. } | NodeKind::Compound { .. });
|
||||
let in_compound = d.parent_of(c.id).and_then(|p| d.node(p)).is_some_and(|p| matches!(p.kind, NodeKind::Compound { .. }));
|
||||
if own && !in_compound && !out.contains(&c.id) {
|
||||
if own && !in_compound && seen.insert(c.id) {
|
||||
out.push(c.id);
|
||||
}
|
||||
});
|
||||
@@ -56,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();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -84,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();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -128,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();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -493,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 ¶ms {
|
||||
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, ¶ms, &mut merged);
|
||||
keep_largest_width(b, &was, ¶ms, &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"];
|
||||
@@ -748,3 +917,92 @@ pub(super) fn brush_freehand(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let checked = crate::schemas::check(spec, p, s.replaying())?;
|
||||
crate::cmd::draw2::freehand_brushed(s, checked.as_ref().unwrap_or(p), name.as_deref())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use vectorcraft_doc::Appearance;
|
||||
use vectorcraft_geom::PathData;
|
||||
|
||||
/// The collector with a linear search of its output, kept to compare results with.
|
||||
fn listed_targets(d: &Document, ids: &[NodeId]) -> Vec<NodeId> {
|
||||
let mut out = vec![];
|
||||
for id in ids {
|
||||
let Some(n) = d.node(*id) else { continue };
|
||||
n.walk(&mut |c| {
|
||||
let own = matches!(c.kind, NodeKind::Path { guide: false, clipping: false, .. } | NodeKind::Compound { .. });
|
||||
let in_compound = d.parent_of(c.id).and_then(|p| d.node(p)).is_some_and(|p| matches!(p.kind, NodeKind::Compound { .. }));
|
||||
if own && !in_compound && !out.contains(&c.id) {
|
||||
out.push(c.id);
|
||||
}
|
||||
});
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn path(d: &mut Document) -> Node {
|
||||
Node::path(d.alloc_id(), PathData::default(), Appearance::default())
|
||||
}
|
||||
|
||||
fn compound(d: &mut Document, children: Vec<Node>) -> Node {
|
||||
Node::new(d.alloc_id(), NodeKind::Compound { children: children.into_iter().map(Arc::new).collect(), rule: Default::default() })
|
||||
}
|
||||
|
||||
fn add(d: &mut Document, node: Node) -> NodeId {
|
||||
let layer = d.layers.first().map(|l| l.id);
|
||||
d.insert(layer, usize::MAX, node).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn brush_targets_list_each_target_once_in_first_reached_order() {
|
||||
let mut d = Document::new(400.0, 300.0);
|
||||
let a = path(&mut d);
|
||||
let a = add(&mut d, a);
|
||||
let mut guide = path(&mut d);
|
||||
if let NodeKind::Path { guide: g, .. } = &mut guide.kind {
|
||||
*g = true;
|
||||
}
|
||||
let guide = add(&mut d, guide);
|
||||
let mut clip = path(&mut d);
|
||||
if let NodeKind::Path { clipping, .. } = &mut clip.kind {
|
||||
*clipping = true;
|
||||
}
|
||||
let clip = add(&mut d, clip);
|
||||
// A group holding a path and a compound path of two members.
|
||||
let p1 = path(&mut d);
|
||||
let p1_id = p1.id;
|
||||
let (m1, m2) = (path(&mut d), path(&mut d));
|
||||
let m1_id = m1.id;
|
||||
let cp1 = compound(&mut d, vec![m1, m2]);
|
||||
let cp1_id = cp1.id;
|
||||
let group = Node::group(d.alloc_id(), vec![Arc::new(p1), Arc::new(cp1)]);
|
||||
let group = add(&mut d, group);
|
||||
// A compound path holding a compound path.
|
||||
let m3 = path(&mut d);
|
||||
let cp3 = compound(&mut d, vec![m3]);
|
||||
let cp3_id = cp3.id;
|
||||
let cp2 = compound(&mut d, vec![cp3]);
|
||||
let cp2 = add(&mut d, cp2);
|
||||
|
||||
let ids = [cp1_id, a, group, p1_id, a, guide, clip, m1_id, cp2, cp3_id, NodeId(u64::MAX)];
|
||||
let got = brush_targets(&d, &ids);
|
||||
assert_eq!(got, [cp1_id, a, p1_id, cp2], "repeats keep their first place; guides, clipping paths and compound members are left out");
|
||||
assert_eq!(got, listed_targets(&d, &ids));
|
||||
assert!(brush_targets(&d, &[]).is_empty());
|
||||
|
||||
// Many paths in groups, each group listed with some of its members.
|
||||
let mut ids = vec![];
|
||||
for _ in 0..50 {
|
||||
let members: Vec<Node> = (0..20).map(|_| path(&mut d)).collect();
|
||||
let member_ids: Vec<NodeId> = members.iter().map(|m| m.id).collect();
|
||||
let g = Node::group(d.alloc_id(), members.into_iter().map(Arc::new).collect());
|
||||
let g = add(&mut d, g);
|
||||
ids.push(member_ids[7]);
|
||||
ids.push(g);
|
||||
ids.push(member_ids[3]);
|
||||
}
|
||||
let got = brush_targets(&d, &ids);
|
||||
assert_eq!(got.len(), 50 * 20);
|
||||
assert_eq!(got, listed_targets(&d, &ids));
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
use super::{
|
||||
Appearance, AppearanceItem, Arc, Beside, Document, EDGE_NAME, EngineError, FACE_NAME, GapOptions, GapSize, LIVE_PAINT_NAME, Node, NodeId,
|
||||
PathData, Point, Rect, Result, SOURCES_NAME, Selection, Session, SubPath, Value, b, bad, build_children, edge_near, face_at, finite,
|
||||
fit_to_old_edge, ids_json, is_live_paint, json, number_or, object_param, paint_from, po, point_param, repaint_from, replace_roots, root_ids,
|
||||
source_nodes, source_shapes, switch_or,
|
||||
PathData, Point, Rect, Result, Selection, Session, SubPath, Value, b, bad, build_children, edge_near, face_at, finite, fit_to_old_edge, ids_json,
|
||||
is_live_paint, json, number_or, object_param, paint_from, po, point_param, repaint_from, replace_roots, root_ids, source_nodes, source_shapes,
|
||||
switch_or,
|
||||
};
|
||||
|
||||
/// `options` as stored on a Live Paint group: none for the defaults.
|
||||
@@ -53,6 +53,27 @@ fn make_live(d: &mut Document, sel: &mut Selection, roots: &[NodeId]) -> Result<
|
||||
Ok((gid, nf, ne))
|
||||
}
|
||||
|
||||
/// The children of Live Paint group `g` besides its sources group ([`b::sources`]) and its faces and
|
||||
/// edges (paths named [`FACE_NAME`] or [`EDGE_NAME`]), back to front: objects drawn in it in
|
||||
/// isolation mode. A group or other object named like a part is one of them.
|
||||
fn others_in(g: &Node) -> impl Iterator<Item = &Arc<Node>> {
|
||||
let src = b::sources(g).map(|s| s.id);
|
||||
g.children()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter(move |c| Some(c.id) != src && !(c.path_data().is_some() && matches!(c.name.as_deref(), Some(FACE_NAME | EDGE_NAME))))
|
||||
}
|
||||
|
||||
/// Make `parts` (a sources group, faces and edges made again) the children of Live Paint group `g`,
|
||||
/// with its other children ([`others_in`]) that are not among `gone` kept in front of them, in their
|
||||
/// order.
|
||||
fn set_parts(g: &mut Node, mut parts: Vec<Arc<Node>>, gone: &[NodeId]) {
|
||||
parts.extend(others_in(g).filter(|c| !gone.contains(&c.id)).cloned());
|
||||
if let Some(ch) = g.children_mut() {
|
||||
*ch = parts;
|
||||
}
|
||||
}
|
||||
|
||||
/// Select `ids` alone, without an undo step, when they are not selected that way already.
|
||||
fn select_only(s: &mut Session, ids: &[NodeId]) -> Result<()> {
|
||||
let st = s.doc()?;
|
||||
@@ -134,9 +155,15 @@ fn merge_live(d: &mut Document, sel: &mut Selection, roots: &[NodeId]) -> Result
|
||||
b::faces(&old).iter().filter(|f| draws(f)).filter_map(|f| Some((po::interior_point(f.path_data()?)?, Carried::of(f)))).collect();
|
||||
let old_parts = old.clone();
|
||||
let mut sources = source_nodes(&old);
|
||||
// The objects drawn in the other Live Paint groups besides their parts stay in the merged group.
|
||||
let mut others = vec![];
|
||||
for r in roots {
|
||||
if *r != target {
|
||||
sources.extend(source_nodes(d.node(*r).ok_or(EngineError::NoNode(*r))?));
|
||||
let n = d.node(*r).ok_or(EngineError::NoNode(*r))?;
|
||||
sources.extend(source_nodes(n));
|
||||
if is_live_paint(n) {
|
||||
others.extend(others_in(n).cloned());
|
||||
}
|
||||
}
|
||||
}
|
||||
// Merge applies the Gap Options' merge rules to the groups' options, bottom-most first.
|
||||
@@ -146,8 +173,9 @@ fn merge_live(d: &mut Document, sel: &mut Selection, roots: &[NodeId]) -> Result
|
||||
// The group keeps its name, lock, visibility, transparency, appearance, opacity mask, graphic
|
||||
// style link and the rest; its children are made again and its Gap Options set to the merged ones.
|
||||
let mut g = old;
|
||||
set_parts(&mut g, children, roots);
|
||||
if let Some(ch) = g.children_mut() {
|
||||
*ch = children;
|
||||
ch.extend(others);
|
||||
}
|
||||
g.extras_mut().live_paint_gaps = stored_gap_options(options);
|
||||
for (pt, carried) in keep_faces {
|
||||
@@ -199,6 +227,38 @@ pub(super) fn lp_merge(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "id": id.0, "faces": faces, "edges": edges }))
|
||||
}
|
||||
|
||||
/// The Live Paint group whose drawn art is added when isolation mode leaves `isolated`: the innermost
|
||||
/// Live Paint group that is `isolated` or holds it, such as a group drawn in an isolated Live Paint
|
||||
/// group and then isolated itself. None when `isolated` is not in a Live Paint group.
|
||||
pub(crate) fn isolated_live_paint(d: &Document, isolated: NodeId) -> Option<NodeId> {
|
||||
d.ancestry(isolated)?.into_iter().rev().find(|id| d.node(*id).is_some_and(is_live_paint))
|
||||
}
|
||||
|
||||
/// The children of Live Paint group `g` besides its parts ([`others_in`]) that Live Paint takes
|
||||
/// ([`b::live_paint_takes`]) and that are shown and unlocked with everything in them, back to
|
||||
/// front: the paths drawn in it in isolation mode.
|
||||
fn drawn_in(g: &Node) -> Vec<NodeId> {
|
||||
fn open(n: &Node) -> bool {
|
||||
n.visible && !n.locked && n.children().is_none_or(|ch| ch.iter().all(|c| open(c)))
|
||||
}
|
||||
others_in(g).filter(|c| open(c) && b::live_paint_takes(c)).map(|c| c.id).collect()
|
||||
}
|
||||
|
||||
/// Leaving isolation mode in Live Paint group `g` adds the paths drawn in it to the group as
|
||||
/// `livePaint.merge` does, in one "Merge Live Paint" undo step; → whether any were added. Type,
|
||||
/// images, other objects Live Paint does not take, and hidden or locked objects stay where they
|
||||
/// are. With nothing to add, or when `g` is not a Live Paint group, nothing changes and no undo
|
||||
/// step is recorded.
|
||||
pub(crate) fn merge_drawn_in_isolation(s: &mut Session, g: NodeId) -> Result<bool> {
|
||||
let drawn = s.doc()?.doc.node(g).filter(|n| is_live_paint(n)).map(drawn_in).unwrap_or_default();
|
||||
if drawn.is_empty() {
|
||||
return Ok(false);
|
||||
}
|
||||
let roots: Vec<NodeId> = std::iter::once(g).chain(drawn).collect();
|
||||
s.edit("Merge Live Paint", |d, sel| merge_live(d, sel, &roots))?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
fn live_targets(s: &Session, p: &Value) -> Result<Vec<NodeId>> {
|
||||
let d = &s.doc()?.doc;
|
||||
let ids = root_ids(s, p)?;
|
||||
@@ -216,7 +276,8 @@ pub(super) fn lp_release(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut released = Beside::replacing(d, &targets);
|
||||
for g in &targets {
|
||||
let n = d.node(*g).cloned().ok_or(EngineError::NoNode(*g))?;
|
||||
let srcs: Vec<Node> = source_nodes(&n).iter().map(|c| (**c).clone()).collect();
|
||||
// The objects drawn in the group besides its parts are released in front of its paths.
|
||||
let srcs: Vec<Node> = source_nodes(&n).iter().chain(others_in(&n)).map(|c| (**c).clone()).collect();
|
||||
out.extend(srcs.iter().map(|c| c.id));
|
||||
released.put(d, *g, srcs)?;
|
||||
}
|
||||
@@ -245,10 +306,12 @@ pub(super) fn lp_expand(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
e.trace = None;
|
||||
e.live_paint_gaps = None;
|
||||
}
|
||||
// Objects drawn in the group ([`others_in`]) stay, whatever they are named.
|
||||
let src = b::sources(n).map(|c| c.id);
|
||||
if let Some(ch) = n.children_mut() {
|
||||
ch.retain(|c| match c.name.as_deref() {
|
||||
Some(SOURCES_NAME) => false,
|
||||
Some(FACE_NAME | EDGE_NAME) => draws(c),
|
||||
_ if Some(c.id) == src => false,
|
||||
Some(FACE_NAME | EDGE_NAME) if c.path_data().is_some() => draws(c),
|
||||
_ => true,
|
||||
});
|
||||
}
|
||||
@@ -354,9 +417,7 @@ pub(super) fn lp_gap_options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// The faces change only with what paint stops at, or with new paths.
|
||||
if added > 0 || options.max_gap() != old.gap_options().max_gap() {
|
||||
let (children, _, _) = build_children(d, sources, options.max_gap())?;
|
||||
if let Some(ch) = n.children_mut() {
|
||||
*ch = children;
|
||||
}
|
||||
set_parts(&mut n, children, &[]);
|
||||
repaint_from(&mut n, &old);
|
||||
}
|
||||
n.extras_mut().live_paint_gaps = stored_gap_options(options);
|
||||
|
||||
@@ -209,7 +209,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Load Metafile into Clipboard",
|
||||
[],
|
||||
None,
|
||||
"{dataBase64 (EMF or WMF bytes), center?: [x, y]} replace the clipboard with the picture's objects (paths, clipping groups, images, point type; the images they use), centred on `center` (default: the first artboard) → {count, warnings}; records VectorCraft doesn't read are skipped with one warning; then run edit.paste",
|
||||
"{dataBase64 (EMF or WMF bytes), center?: [x, y]} replace the clipboard with the picture's objects (paths, clipping groups, images, point type; the images they use), centred on `center` (default: the first artboard) → {count, warnings}; records VectorCraft doesn't read are skipped with one warning; a picture cut short by a reader limit, images and pattern brushes that can't be read, clips that can't be applied and raster operations other than a plain copy each add a warning; then run edit.paste",
|
||||
has_doc,
|
||||
import_emf
|
||||
),
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
|
||||
+129
-22
@@ -53,12 +53,29 @@ 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
|
||||
),
|
||||
cmd!(
|
||||
"shape.circleThroughPoints",
|
||||
"Circle Through Points",
|
||||
[],
|
||||
None,
|
||||
"{points?: [[x, y], [x, y], [x, y]] (left out: the three selected anchor points, where a path selected whole counts all its anchors and selected segments' ends do not count)} → {id, cx, cy, radius}: a circle with the current paint whose edge passes through the three points, not pixel-aligned even while Align New Objects to Pixel Grid is on; two points that are the same or three on one line are an error, and nothing is drawn",
|
||||
has_doc,
|
||||
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",
|
||||
@@ -116,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)
|
||||
@@ -131,14 +141,22 @@ pub(crate) fn add_look(s: &mut Session, label: &str, kind: NodeKind, look: NewAr
|
||||
/// [`add_look`] that selects the new object only when `select` is set; otherwise the selection
|
||||
/// stays as it was.
|
||||
pub(crate) fn insert_look(s: &mut Session, label: &str, kind: NodeKind, look: NewArt, name: Option<String>, select: bool) -> Result<Value> {
|
||||
insert_look_turned(s, label, kind, look, name, select, 0.0)
|
||||
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);
|
||||
insert_look_turned(s, label, kind, look, None, true, bbox_turn(rotation))
|
||||
insert_look_turned(s, label, kind, look, None, true, bbox_turn(rotation), true)
|
||||
}
|
||||
|
||||
/// [`add_art`] for an object whose geometry must stay where it was computed: it is not
|
||||
/// pixel-aligned, even while the document's Align New Objects to Pixel Grid is on.
|
||||
fn add_art_unaligned(s: &mut Session, label: &str, kind: NodeKind) -> Result<Value> {
|
||||
let look = s.new_art_look(s.paint.fill.clone(), s.paint.stroke.clone(), s.paint.stroke_width);
|
||||
insert_look_turned(s, label, kind, look, None, true, 0.0, false)
|
||||
}
|
||||
|
||||
/// The bounding-box angle (counter-clockwise, as `Node::bbox_angle` and the Rotate tool keep it)
|
||||
@@ -162,8 +180,10 @@ fn constrained_turn(s: &Session, rotation: f64) -> f64 {
|
||||
}
|
||||
}
|
||||
|
||||
/// [`insert_look`] with the new object's bounding box turned to `bbox_angle`. A new path or
|
||||
/// compound path is pixel-aligned while the document's Align New Objects to Pixel Grid is on.
|
||||
/// [`insert_look`] with the new object's bounding box turned to `bbox_angle`. With `align`, a new
|
||||
/// path or compound path is pixel-aligned while the document's Align New Objects to Pixel Grid is
|
||||
/// on.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn insert_look_turned(
|
||||
s: &mut Session,
|
||||
label: &str,
|
||||
@@ -172,6 +192,7 @@ fn insert_look_turned(
|
||||
name: Option<String>,
|
||||
select: bool,
|
||||
bbox_angle: f64,
|
||||
align: bool,
|
||||
) -> Result<Value> {
|
||||
let parent = s.doc()?.target_parent()?;
|
||||
let mode = s.draw_mode;
|
||||
@@ -181,7 +202,9 @@ fn insert_look_turned(
|
||||
let id = d.alloc_id();
|
||||
let mut n = Node::new(id, kind);
|
||||
look.apply(d, &mut n);
|
||||
super::object::align_new_object(d, &mut n);
|
||||
if align {
|
||||
super::object::align_new_object(d, &mut n);
|
||||
}
|
||||
n.name = name;
|
||||
n.bbox_angle = bbox_angle;
|
||||
let mut into = None;
|
||||
@@ -300,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;
|
||||
@@ -316,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") => {
|
||||
@@ -390,6 +413,71 @@ fn ellipse(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
add_art_turned(s, "Ellipse", path_kind(live.to_path(), Some(live)), rotation)
|
||||
}
|
||||
|
||||
/// A live ellipse whose edge passes through three points: `points`, or the three selected anchor
|
||||
/// points ([`selected_anchor_points`]). One undo step, named as an Ellipse tool drag is.
|
||||
fn circle_through_points(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "shape.circleThroughPoints";
|
||||
let points = match p.get("points").filter(|v| !v.is_null()) {
|
||||
Some(v) => three_points(v).ok_or_else(|| bad(C, "`points` must be three [x, y] pairs of numbers"))?,
|
||||
None => selected_anchor_points(s)?.ok_or_else(|| bad(C, "direct-select three anchor points, or give `points`"))?,
|
||||
};
|
||||
let [a, b, c] = points;
|
||||
let (center, radius) = shapes::circle_through(a, b, c)
|
||||
.ok_or_else(|| bad(C, "no circle passes through these points: two are the same or all three lie on one line"))?;
|
||||
let r = Rect::new(center.x - radius, center.y - radius, center.x + radius, center.y + radius);
|
||||
let live = LiveShape::Ellipse { w: r.width(), h: r.height(), pie: (0.0, 360.0), xf: Affine::translate(r.origin().to_vec2()) };
|
||||
// Not pixel-aligned: the circle stays through the points.
|
||||
let mut out = add_art_unaligned(s, "Ellipse", path_kind(live.to_path(), Some(live)))?;
|
||||
out["cx"] = json!(center.x);
|
||||
out["cy"] = json!(center.y);
|
||||
out["radius"] = json!(radius);
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The three points `[[x, y], [x, y], [x, y]]` holds, each pair two finite numbers.
|
||||
fn three_points(v: &Value) -> Option<[Point; 3]> {
|
||||
let pair = |v: &Value| match v.as_array().map(Vec::as_slice) {
|
||||
Some([x, y]) => x.as_f64().zip(y.as_f64()).filter(|(x, y)| x.is_finite() && y.is_finite()).map(|(x, y)| Point::new(x, y)),
|
||||
_ => None,
|
||||
};
|
||||
match v.as_array().map(Vec::as_slice) {
|
||||
Some([a, b, c]) => Some([pair(a)?, pair(b)?, pair(c)?]),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The positions of the selected anchor points, when there are exactly three. They are counted as
|
||||
/// the other anchor commands count them ([`super::path::anchor_targets`]): a selected path with
|
||||
/// anchors picked by Direct Selection gives those, and a path selected whole gives all of its own.
|
||||
/// A selected segment's ends are not selected anchor points, so a selection with segments gives
|
||||
/// none; so does a selection holding an object that is not a path, or an anchor that is gone.
|
||||
fn selected_anchor_points(s: &Session) -> Result<Option<[Point; 3]>> {
|
||||
let st = s.doc()?;
|
||||
if st.selection.segments.values().any(|set| !set.is_empty()) {
|
||||
return Ok(None);
|
||||
}
|
||||
let mut points = Vec::with_capacity(4);
|
||||
for id in &st.selection.objects {
|
||||
let Some(pd) = st.doc.node(*id).and_then(|n| n.path_data()) else { return Ok(None) };
|
||||
match st.selection.anchors.get(id) {
|
||||
Some(set) => {
|
||||
for &(si, ai) in set.iter().take(4) {
|
||||
let Some(a) = pd.subpaths.get(si).and_then(|sp| sp.anchors.get(ai)) else { return Ok(None) };
|
||||
points.push(a.p);
|
||||
}
|
||||
}
|
||||
None => points.extend(pd.anchors().take(4).map(|(_, _, a)| a.p)),
|
||||
}
|
||||
if points.len() > 3 {
|
||||
return Ok(None);
|
||||
}
|
||||
}
|
||||
Ok(match points.as_slice() {
|
||||
&[a, b, c] => Some([a, b, c]),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
/// The whole-number count `p` gives for `key` (`5` or `5.0`), or `default` when it is left out or
|
||||
/// null. A fraction, a negative, a non-finite or a non-number is an error rather than the default.
|
||||
fn count_or(p: &Value, key: &str, default: u64, cmd: &str) -> Result<u64> {
|
||||
@@ -479,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;
|
||||
@@ -494,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));
|
||||
@@ -581,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(
|
||||
@@ -590,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> {
|
||||
@@ -651,7 +757,7 @@ fn arc(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if s.paint.stroke.is_none() { vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK) } else { s.paint.stroke.clone() },
|
||||
s.paint.stroke_width.max(0.1),
|
||||
);
|
||||
insert_look_turned(s, "Arc", path_kind(path, None), look, None, true, bbox_angle)
|
||||
insert_look_turned(s, "Arc", path_kind(path, None), look, None, true, bbox_angle, true)
|
||||
}
|
||||
|
||||
/// The grid `paths` (bottom first) as one selected group in the new-art stroke, filled with the
|
||||
@@ -831,7 +937,8 @@ fn text_create(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// Lays the text out (and sizes an Auto Size frame).
|
||||
super::typecmd::refresh_bounds(&mut t);
|
||||
}
|
||||
let made = insert_look_turned(s, "Type", NodeKind::Text(Box::new(t)), NewArt::plain(Appearance::default()), None, true, bbox_turn(rotation))?;
|
||||
let made =
|
||||
insert_look_turned(s, "Type", NodeKind::Text(Box::new(t)), NewArt::plain(Appearance::default()), None, true, bbox_turn(rotation), true)?;
|
||||
let id = made.get("id").and_then(Value::as_u64).map(NodeId);
|
||||
let made = super::typecmd::with_bounds(s, id, made);
|
||||
let mut made = super::typecmd::with_overflow(s, id.as_slice(), made);
|
||||
|
||||
@@ -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, §ions) }));
|
||||
}
|
||||
@@ -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]
|
||||
|
||||
@@ -6,7 +6,7 @@ use std::collections::{BTreeSet, HashMap, HashSet};
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{CharStyle, Guide, Node, NodeId, NodeKind, SavedSelection, TextKind};
|
||||
use vectorcraft_doc::{CharStyle, Guide, Node, NodeId, NodeKind, SavedSelection, Selection, TextKind};
|
||||
use vectorcraft_geom::Vec2;
|
||||
|
||||
use super::edit::selected_roots;
|
||||
@@ -495,16 +495,17 @@ fn direction_handles(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
let total: usize = items.iter().map(|x| x.1.len()).sum();
|
||||
s.select(|_, sel| {
|
||||
sel.clear();
|
||||
for (id, refs) in items {
|
||||
sel.add(id);
|
||||
sel.anchors.insert(id, refs);
|
||||
}
|
||||
})?;
|
||||
s.select(|_, sel| select_anchors(sel, items))?;
|
||||
Ok(json!({ "anchors": total }))
|
||||
}
|
||||
|
||||
/// Replaces `sel` with the paths of `items` in order, each once, and direct-selects the anchors
|
||||
/// listed with each path. A path listed twice keeps its first place and its last anchor set.
|
||||
fn select_anchors(sel: &mut Selection, items: Vec<(NodeId, BTreeSet<(usize, usize)>)>) {
|
||||
sel.set(items.iter().map(|(id, _)| *id));
|
||||
sel.anchors.extend(items);
|
||||
}
|
||||
|
||||
fn save_selection(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "select.save";
|
||||
let st = s.doc()?;
|
||||
@@ -1026,3 +1027,6 @@ fn close_all(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
}
|
||||
Ok(json!({ "closed": n }))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,68 @@
|
||||
//! The selection that Select ▸ Object ▸ Direction Handles builds.
|
||||
|
||||
use std::collections::{BTreeSet, HashSet};
|
||||
use std::sync::Arc;
|
||||
|
||||
use vectorcraft_doc::{NodeId, Selection, SymbolPart};
|
||||
|
||||
use super::select_anchors;
|
||||
|
||||
type Items = Vec<(NodeId, BTreeSet<(usize, usize)>)>;
|
||||
|
||||
/// Selects `items` one path at a time: a clear, then an add and an anchor insert per path.
|
||||
fn one_by_one(sel: &mut Selection, items: Items) {
|
||||
sel.clear();
|
||||
for (id, refs) in items {
|
||||
sel.add(id);
|
||||
sel.anchors.insert(id, refs);
|
||||
}
|
||||
}
|
||||
|
||||
/// A selection with every field set, as one left by earlier selecting.
|
||||
fn busy() -> Selection {
|
||||
let mut sel = Selection::default();
|
||||
sel.set([NodeId(90), NodeId(91)]);
|
||||
sel.anchors.insert(NodeId(90), BTreeSet::from([(0, 0)]));
|
||||
sel.segments.insert(NodeId(91), BTreeSet::from([(0, 1)]));
|
||||
sel.key = Some(NodeId(91));
|
||||
sel.target = Some(NodeId(92));
|
||||
sel.slices = vec![NodeId(93)];
|
||||
sel.guides = vec![NodeId(94)];
|
||||
sel.key_guide = Some(NodeId(94));
|
||||
sel.key_anchor = Some((NodeId(90), (0, 0)));
|
||||
sel.symbol_part = Some(SymbolPart { instance: NodeId(95), path: vec![0, 1] });
|
||||
sel.on_path_member = Some(NodeId(96));
|
||||
sel.new_art = Arc::new(HashSet::from([NodeId(97)]));
|
||||
sel
|
||||
}
|
||||
|
||||
fn refs(n: usize) -> BTreeSet<(usize, usize)> {
|
||||
(0..n).map(|i| (0, i)).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn select_anchors_gives_the_selection_one_by_one_selecting_gives() {
|
||||
let cases: Vec<Items> = vec![
|
||||
vec![],
|
||||
vec![(NodeId(1), refs(4))],
|
||||
(1..=500).map(|i| (NodeId(i), refs(4))).collect(),
|
||||
// A path listed again keeps its first place and its last anchors.
|
||||
vec![(NodeId(3), refs(1)), (NodeId(1), refs(4)), (NodeId(3), refs(2)), (NodeId(2), BTreeSet::new()), (NodeId(1), refs(3))],
|
||||
];
|
||||
for items in cases {
|
||||
for start in [Selection::default(), busy()] {
|
||||
let (mut want, mut got) = (start.clone(), start);
|
||||
one_by_one(&mut want, items.clone());
|
||||
select_anchors(&mut got, items.clone());
|
||||
assert_eq!(got, want, "{items:?}");
|
||||
}
|
||||
}
|
||||
let mut got = busy();
|
||||
select_anchors(&mut got, vec![(NodeId(3), refs(1)), (NodeId(1), refs(4)), (NodeId(3), refs(2))]);
|
||||
assert_eq!(got.objects, vec![NodeId(3), NodeId(1)]);
|
||||
assert_eq!(got.anchors[&NodeId(3)], refs(2));
|
||||
assert!(got.segments.is_empty() && got.slices.is_empty() && got.guides.is_empty());
|
||||
assert_eq!((got.key, got.target, got.key_guide, got.key_anchor, got.on_path_member), (None, None, None, None, None));
|
||||
assert!(got.symbol_part.is_none());
|
||||
assert_eq!(*got.new_art, HashSet::from([NodeId(97)]), "selecting leaves the new-art list alone");
|
||||
}
|
||||
@@ -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
|
||||
),
|
||||
|
||||
@@ -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)) {
|
||||
|
||||
@@ -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)),
|
||||
|
||||
@@ -399,9 +399,7 @@ fn select_found(s: &mut Session, p: &Value, ids: &[NodeId]) -> Result<Value> {
|
||||
let compound = |n: &Node| matches!(n.kind, vectorcraft_doc::NodeKind::Compound { .. });
|
||||
let members = st.isolation.and_then(|i| st.doc.ancestry(i)).is_some_and(|a| a.iter().any(|i| st.doc.node(*i).is_some_and(compound)));
|
||||
let found: BTreeSet<NodeId> = ids.iter().copied().collect();
|
||||
super::select::select_where(s, "document.find", p, |d, n| {
|
||||
found.contains(&n.id) && (members || !d.parent_of(n.id).and_then(|p| d.node(p)).is_some_and(compound))
|
||||
})
|
||||
super::select::select_where(s, "document.find", p, |_, n, parent| found.contains(&n.id) && (members || !parent.is_some_and(compound)))
|
||||
}
|
||||
|
||||
/// Render an artboard at an image's size, drawn as a PNG export draws it (linked images and placed
|
||||
@@ -1189,9 +1187,7 @@ fn clear(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
d.retain_guides(sel, |g| !g.id.is_some_and(|id| gone.contains(&id)));
|
||||
}
|
||||
if is_explicit {
|
||||
for id in &ids {
|
||||
sel.remove(*id);
|
||||
}
|
||||
sel.remove_all(ids.iter().copied());
|
||||
sel.prune(d);
|
||||
} else {
|
||||
sel.clear();
|
||||
|
||||
@@ -1040,7 +1040,8 @@ impl RasterBudget {
|
||||
/// of their own. Random in a Transform effect takes its seed from the id, and the canvas draws the
|
||||
/// pieces with the ids they have before that. `kept` gets the new id of each object in them that
|
||||
/// had an id `skip` lists before. Returns what each of those other members' expansions lists, by
|
||||
/// the member's new id.
|
||||
/// the member's new id. `Err` when such a member still holds a random Transform effect after the
|
||||
/// raster budget left part of it as it is: its new ids would give that effect another seed.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn expand_pieces(
|
||||
d: &mut Document,
|
||||
@@ -1051,7 +1052,7 @@ fn expand_pieces(
|
||||
kept: &mut Vec<NodeId>,
|
||||
stroke_art: effects::StrokeArt,
|
||||
raster: &mut RasterBudget,
|
||||
) -> std::collections::HashMap<NodeId, Vec<Listed>> {
|
||||
) -> std::result::Result<std::collections::HashMap<NodeId, Vec<Listed>>, OverBudget> {
|
||||
let id = m.id;
|
||||
let mut seen = std::collections::HashSet::from([id]);
|
||||
let mut expanded = std::collections::HashMap::new();
|
||||
@@ -1065,7 +1066,12 @@ fn expand_pieces(
|
||||
if all || c.id == id {
|
||||
effects::expand_art(d, c, stroke_art);
|
||||
} else if has_seeded(c) && repeats_an_id(c, &seen) {
|
||||
listed = Some(expand_in_place(d, c, brushes, skip, raster));
|
||||
let left = raster.left;
|
||||
let expanded = expand_in_place(d, c, brushes, skip, raster);
|
||||
if raster.left > left && has_seeded(c) {
|
||||
return Err(OverBudget);
|
||||
}
|
||||
listed = Some(expanded);
|
||||
}
|
||||
let mut was = vec![];
|
||||
if !skip.is_empty() {
|
||||
@@ -1086,7 +1092,7 @@ fn expand_pieces(
|
||||
expanded.insert(c.id, listed);
|
||||
}
|
||||
}
|
||||
expanded
|
||||
Ok(expanded)
|
||||
}
|
||||
|
||||
/// `m`, the art a 3D effect expanded into, with each object in it that has effects of its own (a
|
||||
@@ -1238,6 +1244,82 @@ fn expand_node_except(
|
||||
}
|
||||
}
|
||||
|
||||
/// Replace `n`, a group or layer whose Transform effect's copies each carry the raster effects
|
||||
/// listed before it ([`effects::outer_effects`]), with its art ([`effects::evaluate_container`]):
|
||||
/// the copies become groups of their own with those effects, and they and what they hold get ids
|
||||
/// of their own, so they expand as its members do; the raster effects after the Transform effect
|
||||
/// stay on `n`. A copy that repeats an id ([`repeats_an_id`]) and holds a random Transform effect
|
||||
/// ([`has_seeded`]) expands before its ids change ([`expand_in_place`]), as [`expand_pieces`] does,
|
||||
/// and `members` gets what that expansion lists, by the copy's new id. `kept` gets the new id of
|
||||
/// each copy of an object `skip` lists, and `out` gets `n` unless `listed` says it is there.
|
||||
/// Returns whether `n` changed; any other object stays as it is. `Err`, with `n` as it is, when
|
||||
/// such a copy still holds a random Transform effect after the raster budget left part of it as
|
||||
/// it is: its new ids would give that effect another seed.
|
||||
fn copies_carrying_raster(
|
||||
d: &mut Document,
|
||||
n: &mut Node,
|
||||
(brushes, skip): (&[vectorcraft_brush::Brush], &[NodeId]),
|
||||
kept: &mut Vec<NodeId>,
|
||||
members: &mut std::collections::HashMap<NodeId, Vec<Listed>>,
|
||||
(out, listed): (&mut Vec<Listed>, &mut bool),
|
||||
raster: &mut RasterBudget,
|
||||
) -> std::result::Result<bool, OverBudget> {
|
||||
if !carries_copies(n) {
|
||||
return Ok(false);
|
||||
}
|
||||
let Some(mut m) = effects::evaluate_container(Some(&*d), n) else { return Ok(false) };
|
||||
let mut seen = std::collections::HashSet::from([n.id]);
|
||||
for c in m.children_mut().into_iter().flatten().filter(|c| !c.is_ruler_guide()) {
|
||||
let c = Arc::make_mut(c);
|
||||
let left = raster.left;
|
||||
let mut expanded = (has_seeded(c) && repeats_an_id(c, &seen)).then(|| expand_in_place(d, c, brushes, skip, raster));
|
||||
if expanded.is_some() && raster.left > left && has_seeded(c) {
|
||||
return Err(OverBudget);
|
||||
}
|
||||
let mut was = vec![];
|
||||
if !skip.is_empty() {
|
||||
c.walk(&mut |n| was.push(n.id));
|
||||
}
|
||||
fresh_ids_listed(d, c, &mut seen, expanded.as_deref_mut().unwrap_or_default());
|
||||
// A copy of an object `skip` lists is left as it is too.
|
||||
let mut at = 0;
|
||||
c.walk(&mut |n| {
|
||||
if was.get(at).is_some_and(|old| *old != n.id && skip.contains(old)) {
|
||||
kept.push(n.id);
|
||||
}
|
||||
at += 1;
|
||||
});
|
||||
if let Some(expanded) = expanded {
|
||||
members.insert(c.id, expanded);
|
||||
}
|
||||
}
|
||||
if !*listed {
|
||||
out.push((n.id, 0));
|
||||
*listed = true;
|
||||
}
|
||||
*n = m;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// Is `n` a group or layer whose Transform effect's copies each carry the raster effects listed
|
||||
/// before it ([`copies_carrying_raster`])?
|
||||
fn carries_copies(n: &Node) -> bool {
|
||||
is_container(n) && effects::outer_effects(n).len() != n.appearance.effects.len()
|
||||
}
|
||||
|
||||
/// Does `n`, something in it, or the art of the symbol it places when a color adjustment makes it
|
||||
/// that art, hold a random Transform effect ([`has_seeded`])? The raster budget can then leave `n`
|
||||
/// as it is after part of it expanded ([`expand_pieces`], Crop Marks).
|
||||
fn holds_seeded(d: &Document, n: &Node) -> bool {
|
||||
has_seeded(n)
|
||||
|| match &n.kind {
|
||||
NodeKind::SymbolInstance { symbol, .. } if effects::has_adjustment(n) => {
|
||||
d.symbols.iter().find(|s| s.name == *symbol).is_some_and(|s| has_seeded(&s.art))
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// [`expand_node`] of `n`, which need not be in `d`: `n` with its appearance expanded, `None` when
|
||||
/// it has nothing to expand. `out` gets the objects whose appearance expands, by places in the walk
|
||||
/// of the expanded `n`, `n`'s first when its own does. The objects `skip` lists are not expanded.
|
||||
@@ -1267,10 +1349,23 @@ fn expanded_node(
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
// The embedded images before the adjustment, when the raster budget may yet leave `n` as it
|
||||
// is: the recolored copies the adjustment adds then go again.
|
||||
let images_before = (effects::has_adjustment(&n) && !rasterfx::raster_fx(&n).is_empty())
|
||||
// The embedded images before the adjustment and the expansions of the copies
|
||||
// ([`copies_carrying_raster`]) and of the members that hold a random Transform effect, when the
|
||||
// raster budget may yet leave `n` as it is: the recolored copies and the images those add then
|
||||
// go again.
|
||||
let images_before = ((effects::has_adjustment(&n) && !rasterfx::raster_fx(&n).is_empty()) || carries_copies(&n) || holds_seeded(d, &n))
|
||||
.then(|| d.images.keys().cloned().collect::<std::collections::HashSet<_>>());
|
||||
// What the raster budget had left before those expansions: it gets back what they took.
|
||||
let budget_before = (raster.images, raster.pixels);
|
||||
// `n` stays as it is: `out` lists nothing of it, and the document and the raster budget lose
|
||||
// what expanding it added and took.
|
||||
let leave = |d: &mut Document, out: &mut Vec<Listed>, raster: &mut RasterBudget| {
|
||||
out.truncate(listed_before);
|
||||
if let Some(keys) = &images_before {
|
||||
d.images.retain(|k, _| keys.contains(k));
|
||||
}
|
||||
(raster.images, raster.pixels) = budget_before;
|
||||
};
|
||||
if effects::has_adjustment(&n)
|
||||
&& let Some(m) = effects::adjust_in_document(d, &n, symbol_art)
|
||||
{
|
||||
@@ -1286,14 +1381,21 @@ fn expanded_node(
|
||||
let container = is_container(&n);
|
||||
// Crop Marks: the object and its marks become a group. The object expands on its own first,
|
||||
// with `id`: the canvas draws it with that id, which Random in a Transform effect takes its
|
||||
// seed from. Then the object and the marks get ids of their own.
|
||||
// seed from. Then the object and the marks get ids of their own. When the raster budget leaves
|
||||
// a random Transform effect in the object, `n` stays as it is: new ids would give that effect
|
||||
// another seed.
|
||||
if let Some(mut m) = effects::crop_marks_art(&n) {
|
||||
let mut seen = std::collections::HashSet::from([id]);
|
||||
let mut expanded = vec![];
|
||||
for (i, c) in m.children_mut().into_iter().flatten().enumerate() {
|
||||
let c = Arc::make_mut(c);
|
||||
if i == 0 {
|
||||
let left = raster.left;
|
||||
expanded = expand_in_place(d, c, brushes, skip, raster);
|
||||
if raster.left > left && has_seeded(c) {
|
||||
leave(d, out, raster);
|
||||
return None;
|
||||
}
|
||||
fresh_ids_listed(d, c, &mut seen, &mut expanded);
|
||||
} else {
|
||||
effects::fresh_ids(d, c, &mut seen);
|
||||
@@ -1316,23 +1418,27 @@ fn expanded_node(
|
||||
}
|
||||
return Some(m);
|
||||
}
|
||||
// New ids of the copies of objects `skip` lists among the members.
|
||||
let mut kept = vec![];
|
||||
// Members of a group or layer that `expand_pieces` or `copies_carrying_raster` expanded, by id,
|
||||
// with what their expansion lists.
|
||||
let mut members = std::collections::HashMap::new();
|
||||
let copies = copies_carrying_raster(d, &mut n, (brushes, skip), &mut kept, &mut members, (out, &mut listed_n), raster);
|
||||
// Raster effects whose image would go past the budget stay: so does the object, with what is
|
||||
// inside it and its color adjustments (a symbol instance stays an instance of its symbol).
|
||||
let Ok(image) = raster_image(d, &n, raster) else {
|
||||
out.truncate(listed_before);
|
||||
if let Some(keys) = images_before {
|
||||
d.images.retain(|k, _| keys.contains(k));
|
||||
}
|
||||
// inside it and its color adjustments (a symbol instance stays an instance of its symbol), and
|
||||
// so does a group or layer whose copies or members keep a random Transform effect the budget
|
||||
// left.
|
||||
let Ok(image) = copies.and_then(|copied| {
|
||||
changed |= copied;
|
||||
raster_image(d, &n, raster)
|
||||
}) else {
|
||||
leave(d, out, raster);
|
||||
return None;
|
||||
};
|
||||
let mut v = n.clone();
|
||||
rasterfx::strip_raster(&mut v, false);
|
||||
let mut stroke_art =
|
||||
|d: &mut Document, path: &PathData, rule: FillRule, st: &StrokeLayer| super::pathops::outlined_stroke(d, brushes, path, rule, st);
|
||||
// Members of a group or layer that `expand_pieces` expanded, by id, with what their expansion lists.
|
||||
let mut members = std::collections::HashMap::new();
|
||||
// New ids of the copies of objects `skip` lists among those members.
|
||||
let mut kept = vec![];
|
||||
let expanded = match image {
|
||||
// Blur, feather and inner glow change the object itself: it becomes the image (a layer
|
||||
// keeps it as its only member).
|
||||
@@ -1340,18 +1446,20 @@ fn expanded_node(
|
||||
image => {
|
||||
let m = if (container || matches!(n.kind, NodeKind::Text(_))) && (effects::has_solid(&v) || effects::has_revolve(&v)) {
|
||||
// A 3D effect on a group or layer, or on type: the shaded faces of its solids.
|
||||
effects::expand_leaf(d, &v, &mut stroke_art)
|
||||
Ok::<_, OverBudget>(effects::expand_leaf(d, &v, &mut stroke_art))
|
||||
} else if container {
|
||||
// A group's or layer's own fills and strokes become art among its members.
|
||||
effects::evaluate_container(Some(&*d), &v).map(|mut m| {
|
||||
members = expand_pieces(d, &mut m, false, brushes, skip, &mut kept, &mut stroke_art, raster);
|
||||
m
|
||||
})
|
||||
effects::evaluate_container(Some(&*d), &v)
|
||||
.map(|mut m| {
|
||||
members.extend(expand_pieces(d, &mut m, false, brushes, skip, &mut kept, &mut stroke_art, raster)?);
|
||||
Ok(m)
|
||||
})
|
||||
.transpose()
|
||||
} else if matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. })
|
||||
&& !effects::has_transform_art(&v)
|
||||
&& !effects::has_transform_copies(&v)
|
||||
{
|
||||
effects::expand_leaf(d, &v, &mut stroke_art)
|
||||
Ok(effects::expand_leaf(d, &v, &mut stroke_art))
|
||||
} else {
|
||||
// Type, images, symbol instances, live objects (and paths whose Transform effect copies
|
||||
// them, each copy an object of its own, or changes their fills and strokes): through
|
||||
@@ -1367,12 +1475,18 @@ fn expanded_node(
|
||||
let row_raster = image.is_some() && effects::has_instance_row_raster(&n);
|
||||
let outlined = effects::expand_outlined(Some(&*d), &v, symbol.as_ref())
|
||||
.or_else(|| if row_raster { effects::instance_as_art(Some(&*d), &v, symbol.as_ref()) } else { None });
|
||||
outlined.map(|mut m| {
|
||||
let mut budget = vectorcraft_doc::MAX_SYMBOL_NODES;
|
||||
expand_nested_instances(d, &mut m, 1, &mut budget, raster);
|
||||
expand_pieces(d, &mut m, true, brushes, skip, &mut kept, &mut stroke_art, raster);
|
||||
m
|
||||
})
|
||||
outlined
|
||||
.map(|mut m| {
|
||||
let mut budget = vectorcraft_doc::MAX_SYMBOL_NODES;
|
||||
expand_nested_instances(d, &mut m, 1, &mut budget, raster);
|
||||
expand_pieces(d, &mut m, true, brushes, skip, &mut kept, &mut stroke_art, raster)?;
|
||||
Ok(m)
|
||||
})
|
||||
.transpose()
|
||||
};
|
||||
let Ok(m) = m else {
|
||||
leave(d, out, raster);
|
||||
return None;
|
||||
};
|
||||
// A 3D effect's shadow blurred by the light's Softness keeps its blur in the art: it
|
||||
// expands in turn, to an image.
|
||||
|
||||
@@ -1150,3 +1150,129 @@ fn an_image_past_the_pixels_left_stays_unmade() {
|
||||
let mut budget = super::RasterBudget { images: 0, pixels, left: 0 };
|
||||
assert!(super::raster_image(&mut d, &n, &mut budget).is_err(), "no image is left");
|
||||
}
|
||||
|
||||
/// A group whose Transform effect's copies each carry the drop shadow listed before it, with a
|
||||
/// symbol instance whose random Transform effect takes its seed from the instance's id, stays as it
|
||||
/// is when the raster budget has no image left for a copy's shadow, with none left or with one for
|
||||
/// the first copy's: the copies keep the ids their random moves are drawn with, the group draws as
|
||||
/// before, and the document holds no image the first copy's expansion made, nor the budget its
|
||||
/// charge.
|
||||
#[test]
|
||||
fn copies_the_raster_budget_leaves_keep_their_random_moves() {
|
||||
let (mut s, id) = session_with_rect();
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
let id = NodeId(s.execute("symbol.new", &json!({"name": "Box"})).unwrap()["id"].as_u64().unwrap());
|
||||
let random = json!({"moveH": 40, "moveV": 40, "random": true});
|
||||
s.execute("effect.apply", &json!({"ids": [id.0], "effect": "distort.transform", "params": random})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
let shadow = json!({"x": 10, "y": 0, "blur": 0, "opacity": 100, "mode": "normal", "color": "#00ff00"});
|
||||
s.execute("effect.apply", &json!({"ids": [g.0], "effect": "stylize.dropShadow", "params": shadow})).unwrap();
|
||||
s.execute("effect.apply", &json!({"ids": [g.0], "effect": "distort.transform", "params": {"moveV": 150, "copies": 1}})).unwrap();
|
||||
let draw = |d: &vectorcraft_doc::Document| {
|
||||
vectorcraft_render::Renderer::new().render(d, 400, 400, vectorcraft_geom::Affine::IDENTITY, &Default::default()).pixels
|
||||
};
|
||||
for images in [0, 1] {
|
||||
let mut d = s.doc().unwrap().doc.as_ref().clone();
|
||||
let before = d.node(g).cloned().unwrap();
|
||||
assert!(effects::outer_effects(&before).len() < before.appearance.effects.len(), "each copy carries the shadow");
|
||||
let (drawn, keys) = (draw(&d), d.images.keys().cloned().collect::<Vec<_>>());
|
||||
|
||||
let mut budget = super::RasterBudget { images, pixels: u64::MAX, left: 0 };
|
||||
let mut out = vec![];
|
||||
super::expand_node(&mut d, g, &[], &mut out, &mut budget);
|
||||
assert!(budget.left > 0, "{images}: a copy's shadow is left");
|
||||
assert!(out.is_empty(), "{images}: nothing expands: {out:?}");
|
||||
assert_eq!(d.node(g), Some(&before), "{images}: the group stays as it is");
|
||||
assert!(draw(&d) == drawn, "{images}: the group draws as before");
|
||||
assert_eq!(d.images.keys().cloned().collect::<Vec<_>>(), keys, "{images}: no image is added");
|
||||
assert_eq!((budget.images, budget.pixels), (images, u64::MAX), "{images}: the budget gets back what the copies took");
|
||||
}
|
||||
}
|
||||
|
||||
/// A group whose Transform effect copies its symbol instance, which has a drop shadow and a random
|
||||
/// Transform effect that takes its seed from the instance's id: each copy's instance has that id.
|
||||
/// When the raster budget has no image left for a copy's shadow, with none left or with one for the
|
||||
/// first copy's, the group stays as it is: the copies keep the ids their random moves are drawn
|
||||
/// with, the group draws as before, and the document holds no image the first copy's expansion
|
||||
/// made, nor the budget its charge. With the whole budget, the group expands and each object gets
|
||||
/// an id of its own.
|
||||
#[test]
|
||||
fn a_member_the_raster_budget_leaves_keeps_its_random_move() {
|
||||
let (mut s, id) = session_with_rect();
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
let id = NodeId(s.execute("symbol.new", &json!({"name": "Box"})).unwrap()["id"].as_u64().unwrap());
|
||||
let shadow = json!({"x": 10, "y": 0, "blur": 0, "opacity": 100, "mode": "normal", "color": "#00ff00"});
|
||||
s.execute("effect.apply", &json!({"ids": [id.0], "effect": "stylize.dropShadow", "params": shadow})).unwrap();
|
||||
let random = json!({"moveH": 40, "moveV": 40, "random": true});
|
||||
s.execute("effect.apply", &json!({"ids": [id.0], "effect": "distort.transform", "params": random})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("effect.apply", &json!({"ids": [g.0], "effect": "distort.transform", "params": {"moveV": 150, "copies": 1}})).unwrap();
|
||||
let draw = |d: &vectorcraft_doc::Document| {
|
||||
vectorcraft_render::Renderer::new().render(d, 400, 400, vectorcraft_geom::Affine::IDENTITY, &Default::default()).pixels
|
||||
};
|
||||
for images in [0, 1, 1_024] {
|
||||
let mut d = s.doc().unwrap().doc.as_ref().clone();
|
||||
let before = d.node(g).cloned().unwrap();
|
||||
assert!(effects::outer_effects(&before).len() == before.appearance.effects.len(), "the copies carry no shadow of the group's");
|
||||
let art = effects::evaluate_container(Some(&d), &before).unwrap();
|
||||
let mut instances = 0;
|
||||
art.walk(&mut |n| instances += usize::from(n.id == id && super::has_seeded(n)));
|
||||
assert!(instances >= 2, "{images}: each copy's instance has the id and its random effect: {instances}");
|
||||
let (drawn, keys) = (draw(&d), d.images.keys().cloned().collect::<Vec<_>>());
|
||||
|
||||
let mut budget = super::RasterBudget { images, pixels: u64::MAX, left: 0 };
|
||||
let mut out = vec![];
|
||||
super::expand_node(&mut d, g, &[], &mut out, &mut budget);
|
||||
if images < 2 {
|
||||
assert!(budget.left > 0, "{images}: a shadow is left");
|
||||
assert!(out.is_empty(), "{images}: nothing expands: {out:?}");
|
||||
assert_eq!(d.node(g), Some(&before), "{images}: the group stays as it is");
|
||||
assert!(draw(&d) == drawn, "{images}: the group draws as before");
|
||||
assert_eq!(d.images.keys().cloned().collect::<Vec<_>>(), keys, "{images}: no image is added");
|
||||
assert_eq!((budget.images, budget.pixels), (images, u64::MAX), "{images}: the budget gets back what the copies took");
|
||||
} else {
|
||||
assert_eq!(budget.left, 0, "no shadow is left");
|
||||
assert!(!out.is_empty(), "the group expands");
|
||||
let (mut ids, mut count, mut seeded) = (std::collections::HashSet::new(), 0, false);
|
||||
d.node(g).unwrap().walk(&mut |n| {
|
||||
ids.insert(n.id);
|
||||
count += 1;
|
||||
seeded |= super::has_seeded(n);
|
||||
});
|
||||
assert_eq!(ids.len(), count, "each object has an id of its own");
|
||||
assert!(!seeded, "no random Transform effect is left");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An object with Crop Marks, a drop shadow and a random Transform effect that takes its seed from
|
||||
/// the object's id stays as it is when the raster budget has no image left for its shadow: the
|
||||
/// object keeps its id and its random move, and draws as before.
|
||||
#[test]
|
||||
fn crop_marks_the_raster_budget_leaves_keep_their_random_move() {
|
||||
let (mut s, id) = session_with_rect();
|
||||
let shadow = json!({"x": 10, "y": 0, "blur": 0, "opacity": 100, "mode": "normal", "color": "#00ff00"});
|
||||
s.execute("effect.apply", &json!({"ids": [id.0], "effect": "stylize.dropShadow", "params": shadow})).unwrap();
|
||||
let random = json!({"moveH": 40, "moveV": 40, "random": true});
|
||||
s.execute("effect.apply", &json!({"ids": [id.0], "effect": "distort.transform", "params": random})).unwrap();
|
||||
s.execute("effect.apply", &json!({"ids": [id.0], "effect": "cropMarks", "params": {}})).unwrap();
|
||||
let draw = |d: &vectorcraft_doc::Document| {
|
||||
vectorcraft_render::Renderer::new().render(d, 400, 400, vectorcraft_geom::Affine::IDENTITY, &Default::default()).pixels
|
||||
};
|
||||
let mut d = s.doc().unwrap().doc.as_ref().clone();
|
||||
let before = d.node(id).cloned().unwrap();
|
||||
assert!(effects::crop_marks_art(&before).is_some(), "the object has crop marks");
|
||||
let (drawn, keys) = (draw(&d), d.images.keys().cloned().collect::<Vec<_>>());
|
||||
|
||||
let mut budget = super::RasterBudget { images: 0, pixels: u64::MAX, left: 0 };
|
||||
let mut out = vec![];
|
||||
super::expand_node(&mut d, id, &[], &mut out, &mut budget);
|
||||
assert!(budget.left > 0, "the shadow is left");
|
||||
assert!(out.is_empty(), "nothing expands: {out:?}");
|
||||
assert_eq!(d.node(id), Some(&before), "the object stays as it is");
|
||||
assert!(draw(&d) == drawn, "the object draws as before");
|
||||
assert_eq!(d.images.keys().cloned().collect::<Vec<_>>(), keys, "no image is added");
|
||||
assert_eq!((budget.images, budget.pixels), (0, u64::MAX), "the budget is as it was");
|
||||
}
|
||||
@@ -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)))
|
||||
}
|
||||
|
||||
@@ -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")))]
|
||||
|
||||
@@ -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<()> {
|
||||
|
||||
@@ -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
|
||||
),
|
||||
@@ -36,7 +36,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Export Document",
|
||||
[],
|
||||
None,
|
||||
"{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin.<plug-in id>, which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; pdf/ai: of the layers the file draws, without editing data, with a warning, and ai refuses pdfCompatible: false; SVG has it as an SVG option), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as <stem>.html / <stem>.map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: lossy WebP isn't available yet: written lossless, with a warning), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts, variableData} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), …hpgl writes a plot of the artboard as pen moves for plotters and cutters (each visible path once along its line in plotter units; useArtboards: true one file per chosen artboard, false the bounds of the art it plots, without placed images, unpainted paths and art at 0% opacity), hpglVersion?: hpgl (default: IN, SP, PU, PD) | hpgl2 (also NP and PC pen colors, each pen's paths as one encoded polyline PE), curveTolerance?: 0.1 (points, 0.01 to 10), pens?: [\"#rrggbb\"…] (pen 1 first, up to 255; each path takes the nearest; default a pen per color in the order the art first draws in it, numbered alike in every file), origin?: bottomLeft (default) | center, sortPaths?: false (each pen's next path the nearest), insideFirst?: false (a path after the pen's paths that lie inside it), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-bit alpha, 24, 32 with alpha), colorModel?: rgb|cmyk|gray (psd), layers?: true (each top-level layer a pixel layer with its opacity and blend mod
Line truncated
|
||||
"{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin.<plug-in id>, which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; pdf/ai: of the layers the file draws, without editing data, with a warning, and ai refuses pdfCompatible: false; SVG has it as an SVG option), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as <stem>.html / <stem>.map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: every pixel kept exactly; false writes lossy WebP, a smaller file that loses some detail), quality?: 90 (webp with lossless: false: 0–100, higher keeps more detail in a larger file; more than 100 is refused), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts, variableData} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), …hpgl writes a plot of the artboard as pen moves for plotters and cutters (each visible path once along its line in plotter units; useArtboards: true one file per chosen artboard, false the bounds of the art it plots, without placed images, unpainted paths and art at 0% opacity), hpglVersion?: hpgl (default: IN, SP, PU, PD) | hpgl2 (also NP and PC pen colors, each pen's paths as one encoded polyline PE), curveTolerance?: 0.1 (points, 0.01 to 10), pens?: [\"#rrggbb\"…] (pen 1 first, up to 255; each path takes the nearest; default a pen per color in the order the art first draws in it, numbered alike in every file), origin?: bottomLeft (default) | center, sortPaths?: false (each pen's next path the nearest), insideFirst?: false (a path after the pen's paths that lie inside it), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-b
Line truncated
|
||||
has_doc,
|
||||
export::export
|
||||
),
|
||||
@@ -54,7 +54,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Export for Screens",
|
||||
["File", "Export"],
|
||||
None,
|
||||
"{folder?, zip?: false (one .zip of every file, each deflated or stored, whichever is smaller: no folder → {name, dataBase64, bytes, files: [name…]}; with a folder it is written there → {path, bytes, files}), artboard?: index | artboards?: [index…] | range?: \"1-3\" (default all), assets?: [asset id…] (instead of artboards: each asset's art alone, cropped to its bounds and named after the asset; see assets.list), layers?: [layer id…] (instead of artboards: each layer's art alone, sublayers included, named after the layer), selection?: one|each (instead of artboards: the selected art as one file, or a file per selected object, named after it), fullDocument?: false (one file per format instead: a PDF of every artboard, other formats the bounds of all visible art, named after the document), includeBleed?: false (artboards grown by the document's bleed), includeArtboardFill?: true (Include Artboard Fill: each artboard's background color behind its art; false leaves it out), pdfs?: multiple|single (Export PDFs As: with several artboards, single writes them as the pages of one PDF per PDF row, named after the document; refused with assets, layers or selection: each), exportPreset?: (a preset of document.exportPresets.list: its settings, under these params), subfolders?: false (each row's files in a sub-folder: its folder, else its size for raster (1x, 2x, 100w…) or its format (SVG, PDF)), folders?: none|rows (as subfolders)|format (a folder per extension: png, svg, pdf…)|item (a folder per artboard, asset, layer or object)|itemFormat (item/extension) (default: rows with subfolders or a preset, else none), name?: (a file name pattern instead of the item's name, with <filename> for the document, <name> for the artboard, asset, layer or object, <index> from 1, #### for the counter zero-padded to the run of #, <format>, <scale>, <suffix> (else the row's suffix ends the name), YYYYMMDD, YYYY-MM-DD, YYYY, <date>, <time>, <YYYY>, <MM>, <DD>, <hh>, <mm> and <ss>; a trailing .ext is dropped, as in `COMPANY-Logo-<filename>-####-YYYYMMDD`; different files it names alike get -2, -3…), counterStart?: 1, counterPer?: item (every file of an item has its number)|file, date?: YYYY-MM-DD (the date the pattern uses; default today, UTC), preset?: mobile (PNG 1x, 2x, 3x) | density (PNG 0.75x–4x in ldpi…xxxhdpi sub-folders) instead of formats (turns subfolders on), formats?: [{format: png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft, scale?: 1 | \"2x\" | \"100w\" | \"100h\" | \"72ppi\", width?: px | height?: px | ppi? (raster only; width, then height, then ppi win over scale), suffix?: (raster default: @2x, @100w, @100h, none at 1x; vector formats drop size suffixes), folder?: (its sub-folder), quality?: (jpg 0–100), …the format's options (antiAlias, background, preset (pdf)…)}], settings?: {png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft: {…options for every row of that format}} (rows' own options win), prefix?, antiAlias?: none|art|type (raster rows without their own), openLocation?: (remembered; the app shows the files after exporting)} one file per artboard and format (a PDF holds its artboard alone; artboards with the same name, in any case, get -2, -3…; an unnamed one is Artboard-N; a row whose file would take a name another row's file has, in any case, gets -2, -3… too, and identical rows write one file; row folders that differ only in case are one folder, spelled as the first row spells it) → {files: [path…]} (into the folder of exportPreset, outside the automation read roots: no ZIP path, and files relative to that folder); no folder → {files: [{name, dataBase64}]} (names include sub-folders: 2x/Icon@2x.png); every reply has warnings: [the encoders' warnings for the files, each once: an image that couldn't be decoded, type written in the fallback font…]. eps, ai and vectorcraft rows write a document of the item alone (its one artboard). The params (but zip and assets) are remembered in the document (document.exportSettings; not an undo step). A key it doesn't take, a key no format takes in a format row or in settings, settings for a format it doesn't write, and an unknown key inside a PDF, EPS or SVG option's object, are refused; a key only another format takes in a row or in settings is not used, and warnings name it as given (formats[0].quality; a key in settings only when no row of that format reads it; not a key of an exportPreset). Under automation read roots, an svg or svgz row, and a row whose files carry the native document (vectorcraft, eps, ai but a version 7 file, a pdf with preserveEditing on that holds every artboard of the document it is written from), is refused, before the folder is made or any file is written, while the document links a JavaScript file outside them, or while the row's file would name a linked image's file outside them, as document.export refuses it",
|
||||
"{folder?, zip?: false (one .zip of every file, each deflated or stored, whichever is smaller: no folder → {name, dataBase64, bytes, files: [name…]}; with a folder it is written there → {path, bytes, files}), artboard?: index | artboards?: [index…] | range?: \"1-3\" (default all), assets?: [asset id…] (instead of artboards: each asset's art alone, cropped to its bounds and named after the asset; see assets.list), layers?: [layer id…] (instead of artboards: each layer's art alone, sublayers included, named after the layer), selection?: one|each (instead of artboards: the selected art as one file, or a file per selected object, named after it), fullDocument?: false (one file per format instead: a PDF of every artboard, other formats the bounds of all visible art, named after the document), includeBleed?: false (artboards grown by the document's bleed; a PDF page keeps the artboard as its TrimBox and puts its row's bleed around it once, the document's bleed when the row sets none and its preset gives none or 0), includeArtboardFill?: true (Include Artboard Fill: each artboard's background color behind its art; false leaves it out), pdfs?: multiple|single (Export PDFs As: with several artboards, single writes them as the pages of one PDF per PDF row, named after the document; refused with assets, layers or selection: each), exportPreset?: (a preset of document.exportPresets.list: its settings, under these params), subfolders?: false (each row's files in a sub-folder: its folder, else its size for raster (1x, 2x, 100w…) or its format (SVG, PDF)), folders?: none|rows (as subfolders)|format (a folder per extension: png, svg, pdf…)|item (a folder per artboard, asset, layer or object)|itemFormat (item/extension) (default: rows with subfolders or a preset, else none), name?: (a file name pattern instead of the item's name, with <filename> for the document, <name> for the artboard, asset, layer or object, <index> from 1, #### for the counter zero-padded to the run of #, <format>, <scale>, <suffix> (else the row's suffix ends the name), YYYYMMDD, YYYY-MM-DD, YYYY, <date>, <time>, <YYYY>, <MM>, <DD>, <hh>, <mm> and <ss>; a trailing .ext is dropped, as in `COMPANY-Logo-<filename>-####-YYYYMMDD`; different files it names alike get -2, -3…), counterStart?: 1, counterPer?: item (every file of an item has its number)|file, date?: YYYY-MM-DD (the date the pattern uses; default today, UTC), preset?: mobile (PNG 1x, 2x, 3x) | density (PNG 0.75x–4x in ldpi…xxxhdpi sub-folders) instead of formats (turns subfolders on), formats?: [{format: png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft, scale?: 1 | \"2x\" | \"100w\" | \"100h\" | \"72ppi\", width?: px | height?: px | ppi? (raster only; width, then height, then ppi win over scale), suffix?: (raster default: @2x, @100w, @100h, none at 1x; vector formats drop size suffixes), folder?: (its sub-folder), quality?: (jpg 0–100; webp 0–100 with lossless: false), …the format's options (antiAlias, background, preset (pdf)…)}], settings?: {png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft: {…options for every row of that format}} (rows' own options win), prefix?, antiAlias?: none|art|type (raster rows without their own), openLocation?: (remembered; the app shows the files after exporting)} one file per artboard and format (a PDF holds its artboard alone; artboards with the same name, in any case, get -2, -3…; an unnamed one is Artboard-N; a row whose file would take a name another row's file has, in any case, gets -2, -3… too, and identical rows write one file; row folders that differ only in case are one folder, spelled as the first row spells it) → {files: [path…]} (into the folder of exportPreset, outside the automation read roots: no ZIP path, and files relative to that folder); no folder → {files: [{name, dataBase64}]} (names include sub-folders: 2x/Icon@2x.png); every reply has warnings: [the encoders' warnings for the files, each once: an image that couldn't be decoded, type written in the fallback font…]. eps, ai and vectorcraft rows write a document of the item alone (its one artboard). The params (but zip and assets) are remembered in the document (document.exportSettings; not an undo step). A key it doesn't take, a key no format takes in a format row or in settings, settings for a format it doesn't write, and an unknown key inside a PDF, EPS or SVG option's object, are refused; a key only another format takes in a row or in settings is not used, and warnings name it as given (formats[0].quality; a key in settings only when no row of that format reads it; not a key of an exportPreset). Under automation read roots, an svg or svgz row, and a row whose files carry the native document (vectorcraft, eps, ai but a version 7 file, a pdf with preserveEditing on that holds every artboard of the document it is written from), is refused, before the folder is made or any file is written, while t
Line truncated
|
||||
has_doc,
|
||||
screens::export_for_screens
|
||||
),
|
||||
|
||||
@@ -241,7 +241,8 @@ struct RasterOptions {
|
||||
width: Option<f64>,
|
||||
/// The height of each file in pixels (wins over `ppi` and `scale`).
|
||||
height: Option<f64>,
|
||||
quality: Option<u8>,
|
||||
/// JPEG and lossy WebP quality, read by [`RasterOptions::quality`].
|
||||
quality: Option<Value>,
|
||||
background: Option<Value>,
|
||||
anti_alias: Option<String>,
|
||||
interlaced: Option<bool>,
|
||||
@@ -281,6 +282,19 @@ fn clamped_ppi(ppi: f64) -> f64 {
|
||||
}
|
||||
|
||||
impl RasterOptions {
|
||||
/// `quality` as given: `None` when absent or null, else a whole number 0–255 (JPEG caps it at
|
||||
/// 100; WebP refuses more than 100), or an error naming it.
|
||||
fn quality(&self) -> Result<Option<u8>> {
|
||||
match &self.quality {
|
||||
None | Some(Value::Null) => Ok(None),
|
||||
Some(v) => v
|
||||
.as_u64()
|
||||
.and_then(|q| u8::try_from(q).ok())
|
||||
.map(Some)
|
||||
.ok_or_else(|| bad(C, format!("quality must be a whole number from 0 to 100, not {v}"))),
|
||||
}
|
||||
}
|
||||
|
||||
/// The pixel size each file is scaled to: `width`, else `height`; `None` when neither is set.
|
||||
fn pixel_size(&self) -> Result<Option<ScreenSize>> {
|
||||
let checked = |key: &str, n: f64| {
|
||||
@@ -311,7 +325,8 @@ impl RasterOptions {
|
||||
},
|
||||
anti_alias: self.anti_alias.as_deref().map(anti_alias).transpose().map_err(|e| bad(C, e))?.unwrap_or_default(),
|
||||
interlaced: self.interlaced.unwrap_or(false),
|
||||
quality: self.quality.unwrap_or(90).min(100),
|
||||
quality: self.quality()?.unwrap_or(90).min(100),
|
||||
webp_lossless: self.lossless.unwrap_or(true),
|
||||
jpeg: JpegOptions {
|
||||
color_model,
|
||||
method: parse(self.method.as_deref(), jpeg::Method::from_id, "method", "baseline, optimized or progressive")?,
|
||||
@@ -1136,6 +1151,11 @@ fn encode_files(doc: &Document, f: &Format, p: &Value) -> Result<Encoded> {
|
||||
"psd" => RasterFormat::Psd,
|
||||
_ => RasterFormat::WebP,
|
||||
};
|
||||
if format == RasterFormat::WebP
|
||||
&& let Some(q) = o.quality()?.filter(|q| *q > 100)
|
||||
{
|
||||
return Err(bad(C, format!("quality {q}: WebP quality is 0–100")));
|
||||
}
|
||||
check_options(format, &settings)?;
|
||||
// Use Artboards: one file per chosen artboard (default all); else the one chosen.
|
||||
let chosen = match use_artboards {
|
||||
@@ -1182,9 +1202,6 @@ fn encode_files(doc: &Document, f: &Format, p: &Value) -> Result<Encoded> {
|
||||
}
|
||||
let regions: Vec<Rect> = enc.files.iter().filter_map(|(b, _)| b.and_then(|b| doc.artboards.get(b))).map(|a| a.rect).collect();
|
||||
enc.warnings.extend(crate::cmd::fonts::export_overflow_warning(doc, &doc.layers, Some(®ions)));
|
||||
if format == RasterFormat::WebP && o.lossless == Some(false) {
|
||||
enc.setting_notes.push("lossy WebP isn't available yet: the file is lossless (exact, but larger)".into());
|
||||
}
|
||||
return Ok(enc);
|
||||
}
|
||||
_ => return Err(bad(C, format!("no encoder for {} yet", f.label))),
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -211,17 +211,11 @@ fn selected_part(n: &Arc<Node>, keep: &HashSet<NodeId>, holders: &HashSet<NodeId
|
||||
/// its own art, not a whole document of artboards. `renderer` measures the 3D art, and keeps it for
|
||||
/// the next artboard of the same document.
|
||||
pub(super) fn art_over(doc: &Document, rect: vectorcraft_geom::Rect, renderer: &mut vectorcraft_render::Renderer) -> Document {
|
||||
fn kept(
|
||||
n: &Arc<Node>,
|
||||
doc: &Document,
|
||||
symbols: &SymbolBoxes,
|
||||
rect: vectorcraft_geom::Rect,
|
||||
renderer: &mut vectorcraft_render::Renderer,
|
||||
) -> Option<Arc<Node>> {
|
||||
fn kept(n: &Arc<Node>, symbols: &SymbolBoxes, rect: vectorcraft_geom::Rect, renderer: &mut vectorcraft_render::Renderer) -> Option<Arc<Node>> {
|
||||
if matches!(n.kind, NodeKind::Layer { clip: false, .. }) {
|
||||
let mut layer = Node::clone(n);
|
||||
let children = layer.children_mut()?;
|
||||
*children = children.iter().filter_map(|c| kept(c, doc, symbols, rect, renderer)).collect();
|
||||
*children = children.iter().filter_map(|c| kept(c, symbols, rect, renderer)).collect();
|
||||
return Some(Arc::new(layer));
|
||||
}
|
||||
// A group that doesn't clip keeps only its members over the artboard, so art gathered in one
|
||||
@@ -230,20 +224,21 @@ pub(super) fn art_over(doc: &Document, rect: vectorcraft_geom::Rect, renderer: &
|
||||
if matches!(n.kind, NodeKind::Group { clip: false, .. }) && n.appearance.effects.is_empty() {
|
||||
let mut group = Node::clone(n);
|
||||
let children = group.children_mut()?;
|
||||
*children = children.iter().filter_map(|c| kept(c, doc, symbols, rect, renderer)).collect();
|
||||
*children = children.iter().filter_map(|c| kept(c, symbols, rect, renderer)).collect();
|
||||
return (!children.is_empty()).then(|| Arc::new(group));
|
||||
}
|
||||
let over = |b: vectorcraft_geom::Rect| b.x0 <= rect.x1 && rect.x0 <= b.x1 && b.y0 <= rect.y1 && rect.y0 <= b.y1;
|
||||
let mut holds_instance = false;
|
||||
n.walk(&mut |c| holds_instance |= matches!(c.kind, NodeKind::SymbolInstance { .. }));
|
||||
let painted = || holds_instance && vectorcraft_render::painted_bounds(doc, n).is_some_and(over);
|
||||
// Measured in boxes of its own, which find symbols through the same index.
|
||||
let painted = || holds_instance && vectorcraft_render::painted_bounds_with(&symbols.unmeasured(), n).is_some_and(over);
|
||||
let reach = vectorcraft_brush::reach_within(n);
|
||||
let brushed = |b: vectorcraft_geom::Rect| over(if reach > 0.0 { b.inflate(reach, reach) } else { b });
|
||||
(n.visual_bounds_with(symbols).is_none_or(brushed) || renderer.effect_bounds(symbols, n).is_some_and(brushed) || painted()).then(|| n.clone())
|
||||
}
|
||||
let symbols = doc.symbol_boxes().with_brush_art();
|
||||
let mut d = doc.clone();
|
||||
d.layers = doc.layers.iter().filter_map(|l| kept(l, doc, &symbols, rect, renderer)).collect();
|
||||
d.layers = doc.layers.iter().filter_map(|l| kept(l, &symbols, rect, renderer)).collect();
|
||||
d
|
||||
}
|
||||
|
||||
|
||||
@@ -206,11 +206,15 @@ const LOSSLESS: FormatOption = FormatOption {
|
||||
name: "lossless",
|
||||
ty: "boolean",
|
||||
default: "true",
|
||||
description: "lossless WebP; false asks for lossy, which isn't available yet (written lossless, with a warning)",
|
||||
description: "lossless WebP (every pixel kept exactly); false writes lossy WebP at quality: a smaller file that loses some detail",
|
||||
};
|
||||
|
||||
const WEBP_QUALITY: FormatOption =
|
||||
FormatOption { name: "quality", ty: "integer", default: "90", description: "lossy quality 0–100 (for when lossy WebP is available)" };
|
||||
const WEBP_QUALITY: FormatOption = FormatOption {
|
||||
name: "quality",
|
||||
ty: "integer",
|
||||
default: "90",
|
||||
description: "lossy WebP quality 0–100 (with lossless false; higher keeps more detail in a larger file; more than 100 is refused)",
|
||||
};
|
||||
|
||||
/// The options of the palette formats (PNG-8, GIF).
|
||||
const PALETTE_OPTIONS: &[FormatOption] = &[
|
||||
@@ -834,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,
|
||||
|
||||
@@ -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).
|
||||
@@ -286,16 +285,24 @@ fn editing_copy(opened: &vectorcraft_pdf::Opened, opts: &LoadOptions) -> Option<
|
||||
|
||||
/// A `.ai`, or a PDF saved with the editing data, whose PDF part can't be read (`e`, the import's
|
||||
/// error) from the editor's own copy of its art alone, as a file saved without PDF compatibility
|
||||
/// is read, its first note saying why: `None` when pages are picked, layers or the editing data
|
||||
/// are off, or the file has no editing data that reads. Its type is outlines when `opts` asks.
|
||||
fn without_pdf_part(bytes: &[u8], opts: &LoadOptions, e: &EngineError) -> Option<(Document, Vec<String>)> {
|
||||
/// is read, its first note saying why. Else `e`: as it is when pages are picked, layers or the
|
||||
/// editing data are off, or the file has no editing data, and followed by why when the file has
|
||||
/// editing data that can't be read. Its type is outlines when `opts` asks.
|
||||
fn without_pdf_part(bytes: &[u8], opts: &LoadOptions, e: EngineError) -> Result<(Document, Vec<String>)> {
|
||||
if opts.pages.is_some() || !opts.layers || !opts.editing_data {
|
||||
return None;
|
||||
return Err(e);
|
||||
}
|
||||
let read = vectorcraft_pdf::read_illustrator_data_without_pdf_part(bytes, opts.password.as_deref())
|
||||
.and_then(|private| private.map(|p| vectorcraft_eps::ai_alone_on_page(&p.data, p.trim, p.user_unit, opts.legacy_names)).transpose());
|
||||
match read {
|
||||
Ok(Some((doc, warnings))) => {
|
||||
let notes =
|
||||
std::iter::once(format!("the PDF part couldn't be read ({e}): the file opened from its editing data")).chain(warnings).collect();
|
||||
Ok(outlined_if_asked(doc, notes, opts))
|
||||
}
|
||||
Ok(None) => Err(e),
|
||||
Err(why) => Err(err(format!("{e}; its editing data couldn't be read either ({why})"))),
|
||||
}
|
||||
let private = vectorcraft_pdf::illustrator_data_without_pdf_part(bytes, opts.password.as_deref())?;
|
||||
let (doc, warnings) = vectorcraft_eps::ai_alone_on_page(&private.data, private.trim, private.user_unit, opts.legacy_names).ok()?;
|
||||
let notes = std::iter::once(format!("the PDF part couldn't be read ({e}): the file opened from its editing data")).chain(warnings).collect();
|
||||
Some(outlined_if_asked(doc, notes, opts))
|
||||
}
|
||||
|
||||
/// Is `w` a note on the PDF part as a page, which says nothing was skipped: that the art off the
|
||||
@@ -497,7 +504,7 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
|
||||
.inspect(|_| editing_data = true),
|
||||
// A PDF part that can't be read (a stream the import refuses): the editing copy
|
||||
// alone where it reads, else the error.
|
||||
Err(e) => without_pdf_part(bytes, opts, &e).inspect(|_| editing_data = true).ok_or(e),
|
||||
Err(e) => without_pdf_part(bytes, opts, e).inspect(|_| editing_data = true),
|
||||
}
|
||||
})?;
|
||||
// The File Info of a file read from its pages or its editing copy.
|
||||
@@ -929,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
|
||||
@@ -953,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)));
|
||||
@@ -1165,6 +1186,31 @@ pub(crate) fn png_clip(png: &[u8]) -> Option<vectorcraft_geom::PathData> {
|
||||
vectorcraft_geom::path::with_anchor_budget(vectorcraft_geom::path::MAX_READ_ANCHORS, || serde_json::from_slice(json).ok())
|
||||
}
|
||||
|
||||
/// The imported clipping-path marker in a stored PNG or CMYK TIFF, within the path budget.
|
||||
pub(crate) fn image_clip(blob: &ImageBlob) -> Option<vectorcraft_geom::PathData> {
|
||||
if blob.mime == "image/png" {
|
||||
return png_clip(&blob.bytes);
|
||||
}
|
||||
if blob.mime != "image/tiff" {
|
||||
return None;
|
||||
}
|
||||
use tiff::tags::{Tag, Type, ValueBuffer};
|
||||
let mut d = tiff::decoder::Decoder::new(std::io::Cursor::new(blob.bytes.as_slice())).ok()?;
|
||||
let mut ifd = d.image_ifd();
|
||||
let entry = ifd.find_entry(Tag::ImageDescription)?;
|
||||
if entry.field_type() != Type::ASCII || entry.count() > (MAX_PNG_CLIP + CLIP_KEYWORD.len() + 2) as u64 {
|
||||
return None;
|
||||
}
|
||||
let mut buf = ValueBuffer::empty(Type::ASCII);
|
||||
ifd.find_tag_buf(Tag::ImageDescription, &mut buf).ok()??;
|
||||
let json = buf.as_bytes().strip_prefix(CLIP_KEYWORD.as_bytes())?.strip_prefix(b"\n")?;
|
||||
let json = json.strip_suffix(b"\0").unwrap_or(json);
|
||||
if json.len() > MAX_PNG_CLIP {
|
||||
return None;
|
||||
}
|
||||
vectorcraft_geom::path::with_anchor_budget(vectorcraft_geom::path::MAX_READ_ANCHORS, || serde_json::from_slice(json).ok())
|
||||
}
|
||||
|
||||
/// An image as a document of its physical size at the resolution it declares (as Place sizes it;
|
||||
/// 72 ppi, 1 px = 1 pt, when it declares none), the image named after the file.
|
||||
pub(super) fn raster_doc(name: &str, bytes: &[u8]) -> Result<Document> {
|
||||
|
||||
@@ -9,13 +9,24 @@
|
||||
//! as their specifications ask; MTL colors are the display colors. Materials are two-sided, since
|
||||
//! an open solid or a turned plane is seen from both sides.
|
||||
//!
|
||||
//! The graphics mapped onto a face of a solid ([`textures`]) are a PNG picture of that face: its
|
||||
//! color with the graphics drawn over it, flat and unshaded, which the face's own mesh shows through
|
||||
//! texture coordinates and a material of its own. glTF embeds each PNG as a data URI, USDZ stores it
|
||||
//! after the layer, and OBJ and USDA name PNG files written beside them (`<name>-texture-1.png`…).
|
||||
//!
|
||||
//! Formats: glTF 2.0 <https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html>, USD
|
||||
//! <https://openusd.org/release/index.html> (USDZ: <https://openusd.org/release/spec_usdz.html>).
|
||||
//! <https://openusd.org/release/index.html> (USDZ: <https://openusd.org/release/spec_usdz.html>;
|
||||
//! textures: <https://openusd.org/release/spec_usdpreviewsurface.html>), OBJ and MTL
|
||||
//! <https://www.loc.gov/preservation/digital/formats/fdd/fdd000508.shtml>.
|
||||
|
||||
use std::fmt::Write as _;
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_render::effects::SolidMesh;
|
||||
use vectorcraft_doc::color::{Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, Document, Node, NodeId};
|
||||
use vectorcraft_geom::{Affine, Rect};
|
||||
use vectorcraft_render::effects::{MeshGraphics, SolidMesh};
|
||||
|
||||
/// The formats a 3D asset exports to, as `assets.set3DFormat` names them: USDA first, the default.
|
||||
pub const FORMATS_3D: [&str; 4] = ["usda", "usdz", "gltf", "obj"];
|
||||
@@ -23,6 +34,12 @@ pub const FORMATS_3D: [&str; 4] = ["usda", "usdz", "gltf", "obj"];
|
||||
pub const DEFAULT_FORMAT_3D: &str = "usda";
|
||||
/// The meters in a point (1/72 inch).
|
||||
const METERS_PER_POINT: f64 = 0.0254 / 72.0;
|
||||
/// The pixels along the longer side of a face's texture, unless `assets.export3D` is given another
|
||||
/// size, and the sizes it takes.
|
||||
pub(crate) const TEXTURE_SIZE: u32 = 1024;
|
||||
pub(crate) const TEXTURE_SIZES: (u32, u32) = (128, 4096);
|
||||
/// The most texture pixels one export draws, all its assets together.
|
||||
pub(crate) const MAX_TEXTURE_PIXELS: u64 = 4 * 4096 * 4096;
|
||||
|
||||
/// The label of `format` for menus: `USDA`, `USDZ`, `glTF`, `OBJ`.
|
||||
pub fn format_3d_label(format: &str) -> &'static str {
|
||||
@@ -40,14 +57,44 @@ fn obj_stem(stem: &str) -> String {
|
||||
stem.chars().map(|c| if c.is_whitespace() || c == '#' { '_' } else { c }).collect()
|
||||
}
|
||||
|
||||
/// The names of the files [`mesh_files`] writes for `stem` in `format`.
|
||||
pub(crate) fn mesh_file_names(stem: &str, format: &str) -> Result<Vec<String>, String> {
|
||||
/// The name of texture `k` (from 0) of the object named `stem`: whitespace, `#` and `@` become `_`,
|
||||
/// so an MTL `map_Kd` line and a USD asset path name it as one word.
|
||||
fn texture_name(stem: &str, k: usize) -> String {
|
||||
format!("{}-texture-{}.png", texture_stem(stem), k + 1)
|
||||
}
|
||||
|
||||
/// The name of the opacity map of texture `k` (from 0) of the object named `stem`, as
|
||||
/// [`texture_name`] names the texture.
|
||||
fn opacity_name(stem: &str, k: usize) -> String {
|
||||
format!("{}-texture-{}-opacity.png", texture_stem(stem), k + 1)
|
||||
}
|
||||
|
||||
/// `stem` with whitespace, `#` and `@` turned into `_`, for the names of its textures.
|
||||
fn texture_stem(stem: &str) -> String {
|
||||
stem.chars().map(|c| if c.is_whitespace() || c == '#' || c == '@' { '_' } else { c }).collect()
|
||||
}
|
||||
|
||||
/// The names of the files [`mesh_files`] writes for `stem` in `format` with the textures `images`
|
||||
/// ([`image_maps`]: for each, whether it has an opacity map): OBJ and USDA name a PNG file for each
|
||||
/// texture after them, and OBJ also one for each opacity map, after its texture; glTF and USDZ hold
|
||||
/// theirs.
|
||||
pub(crate) fn mesh_file_names(stem: &str, format: &str, images: &[bool]) -> Result<Vec<String>, String> {
|
||||
let beside = |mut names: Vec<String>, stem: &str, maps: bool| {
|
||||
for (k, map) in images.iter().enumerate() {
|
||||
names.push(texture_name(stem, k));
|
||||
if maps && *map {
|
||||
names.push(opacity_name(stem, k));
|
||||
}
|
||||
}
|
||||
names
|
||||
};
|
||||
match format {
|
||||
"obj" => {
|
||||
let stem = obj_stem(stem);
|
||||
Ok(vec![format!("{stem}.obj"), format!("{stem}.mtl")])
|
||||
Ok(beside(vec![format!("{stem}.obj"), format!("{stem}.mtl")], &stem, true))
|
||||
}
|
||||
"gltf" | "usda" | "usdz" => Ok(vec![format!("{stem}.{format}")]),
|
||||
"usda" => Ok(beside(vec![format!("{stem}.usda")], stem, false)),
|
||||
"gltf" | "usdz" => Ok(vec![format!("{stem}.{format}")]),
|
||||
_ => {
|
||||
let key = "format";
|
||||
Err(format!("`{key}` must be one of {}", FORMATS_3D.join(", ")))
|
||||
@@ -55,35 +102,109 @@ pub(crate) fn mesh_file_names(stem: &str, format: &str) -> Result<Vec<String>, S
|
||||
}
|
||||
}
|
||||
|
||||
/// A picture painted on one part of a 3D object ([`SolidMesh`]): a PNG, and for each corner of the
|
||||
/// part's mesh where it falls on the picture (0 to 1 across from the left, 0 to 1 down from the
|
||||
/// top). `opacity` is a grayscale PNG of the picture's alpha when some of it is not opaque.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub(crate) struct Texture {
|
||||
pub png: Arc<Vec<u8>>,
|
||||
pub opacity: Option<Arc<Vec<u8>>>,
|
||||
pub uv: Vec<[f64; 2]>,
|
||||
}
|
||||
|
||||
/// A distinct picture of a 3D object: the PNG and its opacity map.
|
||||
type Picture = (Arc<Vec<u8>>, Option<Arc<Vec<u8>>>);
|
||||
|
||||
/// The distinct pictures of `textures` in order of first use, and the index among them of each
|
||||
/// part's (`None` for a part without one).
|
||||
fn images(parts: usize, textures: &[Option<Texture>]) -> (Vec<Picture>, Vec<Option<usize>>) {
|
||||
let mut out: Vec<Picture> = vec![];
|
||||
let index = (0..parts)
|
||||
.map(|k| {
|
||||
let t = textures.get(k)?.as_ref()?;
|
||||
Some(out.iter().position(|(p, _)| Arc::ptr_eq(p, &t.png) || p == &t.png).unwrap_or_else(|| {
|
||||
out.push((t.png.clone(), t.opacity.clone()));
|
||||
out.len() - 1
|
||||
}))
|
||||
})
|
||||
.collect();
|
||||
(out, index)
|
||||
}
|
||||
|
||||
/// For each distinct picture of `textures`, whether it has an opacity map ([`mesh_file_names`]).
|
||||
pub(crate) fn image_maps(textures: &[Option<Texture>]) -> Vec<bool> {
|
||||
images(textures.len(), textures).0.iter().map(|(_, map)| map.is_some()).collect()
|
||||
}
|
||||
|
||||
/// The files of a 3D object named `stem` in `format` ([`FORMATS_3D`]): `(file name, bytes)`, the
|
||||
/// OBJ with its MTL after it.
|
||||
pub(crate) fn mesh_files(stem: &str, format: &str, parts: &[SolidMesh]) -> Result<Vec<(String, Vec<u8>)>, String> {
|
||||
let names = mesh_file_names(stem, format)?;
|
||||
let bytes = match format {
|
||||
/// OBJ with its MTL after it and the PNG files of `textures` last (an OBJ's opacity maps each after
|
||||
/// its texture). `textures` holds the picture of each part that has one, in the order of `parts`.
|
||||
pub(crate) fn mesh_files(stem: &str, format: &str, parts: &[SolidMesh], textures: &[Option<Texture>]) -> Result<Vec<(String, Vec<u8>)>, String> {
|
||||
let (images, image) = images(parts.len(), textures);
|
||||
let maps: Vec<bool> = images.iter().map(|(_, map)| map.is_some()).collect();
|
||||
let names = mesh_file_names(stem, format, &maps)?;
|
||||
let pictures: Vec<Arc<Vec<u8>>> = images.iter().map(|(p, _)| p.clone()).collect();
|
||||
let scene = Scene { parts, textures, image: &image, pictures: &pictures, maps: &maps };
|
||||
let pngs = || pictures.iter().map(|p| p.as_ref().clone());
|
||||
let bytes: Vec<Vec<u8>> = match format {
|
||||
"obj" => {
|
||||
let (obj, mtl) = obj(&obj_stem(stem), parts);
|
||||
vec![obj.into_bytes(), mtl.into_bytes()]
|
||||
let stem = obj_stem(stem);
|
||||
let (obj, mtl) = obj(&stem, &scene);
|
||||
let with_maps = images.iter().flat_map(|(p, map)| std::iter::once(p.as_ref().clone()).chain(map.as_ref().map(|m| m.as_ref().clone())));
|
||||
[obj.into_bytes(), mtl.into_bytes()].into_iter().chain(with_maps).collect()
|
||||
}
|
||||
"gltf" => vec![gltf(stem, &scene).into_bytes()],
|
||||
"usda" => std::iter::once(usda(stem, &scene).into_bytes()).chain(pngs()).collect(),
|
||||
_ => {
|
||||
let mut members = vec![(format!("{stem}.usda"), usda(stem, &scene).into_bytes())];
|
||||
members.extend(pngs().enumerate().map(|(k, png)| (texture_name(stem, k), png)));
|
||||
vec![super::zip::store_aligned(&members, 64)?]
|
||||
}
|
||||
"gltf" => vec![gltf(stem, parts).into_bytes()],
|
||||
"usda" => vec![usda(stem, parts).into_bytes()],
|
||||
_ => vec![super::zip::store_aligned(&[(format!("{stem}.usda"), usda(stem, parts).into_bytes())], 64)?],
|
||||
};
|
||||
Ok(names.into_iter().zip(bytes).collect())
|
||||
}
|
||||
|
||||
/// The distinct colors of `parts` in order, and each part's index among them.
|
||||
fn materials(parts: &[SolidMesh]) -> (Vec<[f32; 4]>, Vec<usize>) {
|
||||
let mut colors: Vec<[f32; 4]> = vec![];
|
||||
let index = parts
|
||||
/// The parts of an object with their pictures: `image` is each part's index among `pictures`, and
|
||||
/// `maps` says for each picture whether it has an opacity map.
|
||||
struct Scene<'a> {
|
||||
parts: &'a [SolidMesh],
|
||||
textures: &'a [Option<Texture>],
|
||||
image: &'a [Option<usize>],
|
||||
pictures: &'a [Arc<Vec<u8>>],
|
||||
maps: &'a [bool],
|
||||
}
|
||||
|
||||
impl Scene<'_> {
|
||||
/// Part `k`'s texture coordinates and picture, when it has a picture.
|
||||
fn texture(&self, k: usize) -> Option<(&[[f64; 2]], usize)> {
|
||||
let t = self.textures.get(k)?.as_ref()?;
|
||||
Some((t.uv.as_slice(), (*self.image.get(k)?)?))
|
||||
}
|
||||
}
|
||||
|
||||
/// A material: a color, with a picture that replaces its red, green and blue.
|
||||
#[derive(Clone, Copy, PartialEq)]
|
||||
struct Material {
|
||||
color: [f32; 4],
|
||||
image: Option<usize>,
|
||||
}
|
||||
|
||||
/// The distinct materials of `scene`'s parts in order, and each part's index among them.
|
||||
fn materials(scene: &Scene) -> (Vec<Material>, Vec<usize>) {
|
||||
let mut out: Vec<Material> = vec![];
|
||||
let index = scene
|
||||
.parts
|
||||
.iter()
|
||||
.map(|p| {
|
||||
colors.iter().position(|c| *c == p.color).unwrap_or_else(|| {
|
||||
colors.push(p.color);
|
||||
colors.len() - 1
|
||||
.enumerate()
|
||||
.map(|(k, p)| {
|
||||
let m = Material { color: p.color, image: scene.texture(k).map(|(_, i)| i) };
|
||||
out.iter().position(|c| *c == m).unwrap_or_else(|| {
|
||||
out.push(m);
|
||||
out.len() - 1
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
(colors, index)
|
||||
(out, index)
|
||||
}
|
||||
|
||||
/// An sRGB channel (0..1) as linear light.
|
||||
@@ -96,8 +217,9 @@ fn num(v: f64) -> String {
|
||||
format!("{v}")
|
||||
}
|
||||
|
||||
fn obj(stem: &str, parts: &[SolidMesh]) -> (String, String) {
|
||||
let (colors, material) = materials(parts);
|
||||
fn obj(stem: &str, scene: &Scene) -> (String, String) {
|
||||
let parts = scene.parts;
|
||||
let (materials, material) = materials(scene);
|
||||
let mut o = String::new();
|
||||
let _ = writeln!(o, "mtllib {stem}.mtl");
|
||||
let _ = writeln!(o, "o {stem}");
|
||||
@@ -106,33 +228,64 @@ fn obj(stem: &str, parts: &[SolidMesh]) -> (String, String) {
|
||||
let _ = writeln!(o, "v {} {} {}", num(v[0]), num(v[1]), num(v[2]));
|
||||
}
|
||||
}
|
||||
// OBJ's texture coordinates run up from the picture's bottom.
|
||||
for k in 0..parts.len() {
|
||||
for uv in scene.texture(k).map(|(uv, _)| uv).unwrap_or_default() {
|
||||
let _ = writeln!(o, "vt {} {}", num(uv[0]), num(1.0 - uv[1]));
|
||||
}
|
||||
}
|
||||
for p in parts {
|
||||
for n in &p.mesh.normals {
|
||||
let _ = writeln!(o, "vn {} {} {}", num(n[0]), num(n[1]), num(n[2]));
|
||||
}
|
||||
}
|
||||
let mut base = 1usize;
|
||||
let (mut base, mut uv_base) = (1usize, 1usize);
|
||||
for (k, p) in parts.iter().enumerate() {
|
||||
let _ = writeln!(o, "g Solid_{}", k + 1);
|
||||
let _ = writeln!(o, "usemtl Material_{}", material.get(k).copied().unwrap_or(0) + 1);
|
||||
let textured = scene.texture(k).filter(|(uv, _)| uv.len() == p.mesh.positions.len()).is_some();
|
||||
for t in &p.mesh.triangles {
|
||||
let [a, b, c] = t.map(|i| i as usize + base);
|
||||
let _ = writeln!(o, "f {a}//{a} {b}//{b} {c}//{c}");
|
||||
if textured {
|
||||
let [a, b, c] = t.map(|i| i as usize);
|
||||
let corner = |i: usize| format!("{}/{}/{}", i + base, i + uv_base, i + base);
|
||||
let _ = writeln!(o, "f {} {} {}", corner(a), corner(b), corner(c));
|
||||
} else {
|
||||
let [a, b, c] = t.map(|i| i as usize + base);
|
||||
let _ = writeln!(o, "f {a}//{a} {b}//{b} {c}//{c}");
|
||||
}
|
||||
}
|
||||
base += p.mesh.positions.len();
|
||||
uv_base += scene.texture(k).map_or(0, |(uv, _)| uv.len());
|
||||
}
|
||||
let mut m = String::new();
|
||||
for (k, c) in colors.iter().enumerate() {
|
||||
for (k, mat) in materials.iter().enumerate() {
|
||||
let c = mat.color;
|
||||
let _ = writeln!(m, "newmtl Material_{}", k + 1);
|
||||
let _ = writeln!(m, "Kd {} {} {}", num(f64::from(c[0])), num(f64::from(c[1])), num(f64::from(c[2])));
|
||||
let _ = writeln!(m, "d {}", num(f64::from(c[3])));
|
||||
match mat.image {
|
||||
// The picture holds the color; Kd multiplies it.
|
||||
Some(_) => {
|
||||
let _ = writeln!(m, "Kd 1 1 1");
|
||||
}
|
||||
None => {
|
||||
let _ = writeln!(m, "Kd {} {} {}", num(f64::from(c[0])), num(f64::from(c[1])), num(f64::from(c[2])));
|
||||
}
|
||||
}
|
||||
// A picture's opacity map holds the opacity, as gray levels.
|
||||
let _ = writeln!(m, "d {}", if mat.image.is_some() { "1".to_string() } else { num(f64::from(c[3])) });
|
||||
let _ = writeln!(m, "illum 1");
|
||||
if let Some(i) = mat.image {
|
||||
let _ = writeln!(m, "map_Kd -clamp on {}", texture_name(stem, i));
|
||||
if scene.maps.get(i).copied().unwrap_or(false) {
|
||||
let _ = writeln!(m, "map_d -clamp on {}", opacity_name(stem, i));
|
||||
}
|
||||
}
|
||||
}
|
||||
(o, m)
|
||||
}
|
||||
|
||||
fn gltf(stem: &str, parts: &[SolidMesh]) -> String {
|
||||
let (colors, material) = materials(parts);
|
||||
fn gltf(stem: &str, scene: &Scene) -> String {
|
||||
let parts = scene.parts;
|
||||
let (materials, material) = materials(scene);
|
||||
let mut buffer: Vec<u8> = vec![];
|
||||
let (mut views, mut accessors, mut primitives) = (vec![], vec![], vec![]);
|
||||
let mut view = |buffer: &mut Vec<u8>, bytes: Vec<u8>, target: u32| -> usize {
|
||||
@@ -154,16 +307,25 @@ fn gltf(stem: &str, parts: &[SolidMesh]) -> String {
|
||||
}));
|
||||
accessors.push(json!({ "bufferView": normals, "componentType": 5126, "count": count, "type": "VEC3" }));
|
||||
accessors.push(json!({ "bufferView": indices, "componentType": 5125, "count": p.mesh.triangles.len() * 3, "type": "SCALAR" }));
|
||||
primitives.push(json!({
|
||||
let mut primitive = json!({
|
||||
"attributes": { "POSITION": at, "NORMAL": at + 1 },
|
||||
"indices": at + 2,
|
||||
"material": material.get(k).copied().unwrap_or(0),
|
||||
}));
|
||||
});
|
||||
// glTF's texture coordinates run down from the picture's top, as the picture's own do.
|
||||
if let Some((uv, _)) = scene.texture(k).filter(|(uv, _)| uv.len() == count) {
|
||||
let bytes = uv.iter().flatten().flat_map(|x| (*x as f32).to_le_bytes()).collect();
|
||||
let coords = view(&mut buffer, bytes, 34962);
|
||||
primitive["attributes"]["TEXCOORD_0"] = json!(accessors.len());
|
||||
accessors.push(json!({ "bufferView": coords, "componentType": 5126, "count": count, "type": "VEC2" }));
|
||||
}
|
||||
primitives.push(primitive);
|
||||
}
|
||||
let materials: Vec<Value> = colors
|
||||
let materials: Vec<Value> = materials
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(k, c)| {
|
||||
.map(|(k, mat)| {
|
||||
let c = mat.color;
|
||||
let mut m = json!({
|
||||
"name": format!("Material_{}", k + 1),
|
||||
"pbrMetallicRoughness": {
|
||||
@@ -173,13 +335,18 @@ fn gltf(stem: &str, parts: &[SolidMesh]) -> String {
|
||||
},
|
||||
"doubleSided": true,
|
||||
});
|
||||
if let Some(i) = mat.image {
|
||||
// The picture holds the color and the opacity; the factor multiplies them.
|
||||
m["pbrMetallicRoughness"]["baseColorFactor"] = json!([1.0, 1.0, 1.0, 1.0]);
|
||||
m["pbrMetallicRoughness"]["baseColorTexture"] = json!({ "index": i });
|
||||
}
|
||||
if c[3] < 1.0 {
|
||||
m["alphaMode"] = json!("BLEND");
|
||||
}
|
||||
m
|
||||
})
|
||||
.collect();
|
||||
let doc = json!({
|
||||
let mut doc = json!({
|
||||
"asset": { "version": "2.0", "generator": "VectorCraft" },
|
||||
"scene": 0,
|
||||
"scenes": [{ "nodes": [0] }],
|
||||
@@ -193,6 +360,14 @@ fn gltf(stem: &str, parts: &[SolidMesh]) -> String {
|
||||
"bufferViews": views,
|
||||
"accessors": accessors,
|
||||
});
|
||||
if !scene.pictures.is_empty() {
|
||||
// Linear filtering, mipmaps, and coordinates held at the picture's edge.
|
||||
doc["samplers"] = json!([{ "magFilter": 9729, "minFilter": 9987, "wrapS": 33071, "wrapT": 33071 }]);
|
||||
doc["textures"] = Value::Array((0..scene.pictures.len()).map(|i| json!({ "sampler": 0, "source": i })).collect());
|
||||
doc["images"] = Value::Array(
|
||||
scene.pictures.iter().map(|p| json!({ "uri": format!("data:image/png;base64,{}", vectorcraft_format::base64_encode(p)) })).collect(),
|
||||
);
|
||||
}
|
||||
serde_json::to_string_pretty(&doc).unwrap_or_default()
|
||||
}
|
||||
|
||||
@@ -205,8 +380,9 @@ fn prim_name(name: &str) -> String {
|
||||
out
|
||||
}
|
||||
|
||||
fn usda(stem: &str, parts: &[SolidMesh]) -> String {
|
||||
let (colors, material) = materials(parts);
|
||||
fn usda(stem: &str, scene: &Scene) -> String {
|
||||
let parts = scene.parts;
|
||||
let (materials, material) = materials(scene);
|
||||
let root = prim_name(stem);
|
||||
let triple = |v: [f64; 3]| format!("({}, {}, {})", num(v[0]), num(v[1]), num(v[2]));
|
||||
let list = |items: Vec<String>| items.join(", ");
|
||||
@@ -238,23 +414,178 @@ fn usda(stem: &str, parts: &[SolidMesh]) -> String {
|
||||
linear(c[2])
|
||||
);
|
||||
let _ = writeln!(u, " float[] primvars:displayOpacity = [{}] (\n interpolation = \"constant\"\n )", c[3]);
|
||||
// USD's texture coordinates run up from the picture's bottom.
|
||||
if let Some((uv, _)) = scene.texture(k).filter(|(uv, _)| uv.len() == p.mesh.positions.len()) {
|
||||
let st = list(uv.iter().map(|t| format!("({}, {})", num(t[0]), num(1.0 - t[1]))).collect());
|
||||
let _ = writeln!(u, " texCoord2f[] primvars:st = [{st}] (\n interpolation = \"vertex\"\n )");
|
||||
}
|
||||
let _ = writeln!(u, " uniform token subdivisionScheme = \"none\"\n }}\n");
|
||||
}
|
||||
let _ = writeln!(u, " def Scope \"Materials\"\n {{");
|
||||
for (k, c) in colors.iter().enumerate() {
|
||||
let m = k + 1;
|
||||
for (k, mat) in materials.iter().enumerate() {
|
||||
let (m, c) = (k + 1, mat.color);
|
||||
let at = format!("/{root}/Materials/Material_{m}");
|
||||
let _ = writeln!(u, " def Material \"Material_{m}\"\n {{");
|
||||
let _ = writeln!(u, " token outputs:surface.connect = </{root}/Materials/Material_{m}/Surface.outputs:surface>\n");
|
||||
let _ = writeln!(u, " token outputs:surface.connect = <{at}/Surface.outputs:surface>\n");
|
||||
let _ = writeln!(u, " def Shader \"Surface\"\n {{");
|
||||
let _ = writeln!(u, " uniform token info:id = \"UsdPreviewSurface\"");
|
||||
let _ = writeln!(u, " color3f inputs:diffuseColor = ({}, {}, {})", linear(c[0]), linear(c[1]), linear(c[2]));
|
||||
let _ = writeln!(u, " float inputs:opacity = {}", c[3]);
|
||||
match mat.image {
|
||||
// The picture holds the color, and the opacity when the face is not opaque.
|
||||
Some(_) => {
|
||||
let _ = writeln!(u, " color3f inputs:diffuseColor.connect = <{at}/Texture.outputs:rgb>");
|
||||
if c[3] < 1.0 {
|
||||
let _ = writeln!(u, " float inputs:opacity.connect = <{at}/Texture.outputs:a>");
|
||||
} else {
|
||||
let _ = writeln!(u, " float inputs:opacity = 1");
|
||||
}
|
||||
}
|
||||
None => {
|
||||
let _ = writeln!(u, " color3f inputs:diffuseColor = ({}, {}, {})", linear(c[0]), linear(c[1]), linear(c[2]));
|
||||
let _ = writeln!(u, " float inputs:opacity = {}", c[3]);
|
||||
}
|
||||
}
|
||||
let _ = writeln!(u, " float inputs:roughness = 1");
|
||||
let _ = writeln!(u, " token outputs:surface\n }}\n }}");
|
||||
let _ = writeln!(u, " token outputs:surface\n }}");
|
||||
if let Some(i) = mat.image {
|
||||
let _ = writeln!(u, "\n def Shader \"Texture\"\n {{");
|
||||
let _ = writeln!(u, " uniform token info:id = \"UsdUVTexture\"");
|
||||
let _ = writeln!(u, " asset inputs:file = @{}@", texture_name(stem, i));
|
||||
let _ = writeln!(u, " float2 inputs:st.connect = <{at}/Coordinates.outputs:result>");
|
||||
let _ = writeln!(u, " token inputs:sourceColorSpace = \"sRGB\"");
|
||||
let _ = writeln!(u, " token inputs:wrapS = \"clamp\"");
|
||||
let _ = writeln!(u, " token inputs:wrapT = \"clamp\"");
|
||||
let _ = writeln!(u, " float3 outputs:rgb");
|
||||
if c[3] < 1.0 {
|
||||
let _ = writeln!(u, " float outputs:a");
|
||||
}
|
||||
let _ = writeln!(u, " }}");
|
||||
let _ = writeln!(u, "\n def Shader \"Coordinates\"\n {{");
|
||||
let _ = writeln!(u, " uniform token info:id = \"UsdPrimvarReader_float2\"");
|
||||
let _ = writeln!(u, " string inputs:varname = \"st\"");
|
||||
let _ = writeln!(u, " float2 outputs:result\n }}");
|
||||
}
|
||||
let _ = writeln!(u, " }}");
|
||||
}
|
||||
let _ = writeln!(u, " }}\n}}");
|
||||
u
|
||||
}
|
||||
|
||||
/// The pictures of the graphics on `parts` ([`SolidMesh::graphics`]), one for each part in order
|
||||
/// (`None` for a part without graphics, or whose graphics draw nothing): the part's color with its
|
||||
/// graphics drawn over it, flat and unshaded ([`vectorcraft_render::effects::mesh_graphics_art`]),
|
||||
/// over the bounds of the art points of its corners, `size` pixels along the longer side. Parts with
|
||||
/// the same color, face, graphics and bounds share one picture. `pixels` counts the pixels drawn so
|
||||
/// far, and every call of one export shares it: an error when it passes [`MAX_TEXTURE_PIXELS`].
|
||||
pub(crate) fn textures(doc: &Document, parts: &[SolidMesh], size: u32, pixels: &mut u64) -> Result<Vec<Option<Texture>>, String> {
|
||||
let mut renderer: Option<vectorcraft_render::Renderer> = None;
|
||||
// Each picture drawn: the part it was drawn for, its bounds, and the PNG with its opacity map
|
||||
// (`None`: nothing drawn).
|
||||
let mut drawn: Vec<Drawn> = vec![];
|
||||
let mut out = vec![];
|
||||
for part in parts {
|
||||
let Some(g) = &part.graphics else {
|
||||
out.push(None);
|
||||
continue;
|
||||
};
|
||||
let Some(frame) = texture_frame(g) else {
|
||||
out.push(None);
|
||||
continue;
|
||||
};
|
||||
let scale = f64::from(size) / frame.width().max(frame.height());
|
||||
let fit = |side: f64| ((side * scale).ceil() as u32).clamp(1, size);
|
||||
let (w, h) = (fit(frame.width()), fit(frame.height()));
|
||||
let same = |(p, r, _): &&Drawn| p.color == part.color && *r == frame && p.graphics.as_ref().is_some_and(|o| same_graphics(o, g));
|
||||
let png = match drawn.iter().find(same) {
|
||||
Some((_, _, png)) => png.clone(),
|
||||
None => {
|
||||
let png = match vectorcraft_render::effects::mesh_graphics_art(doc, NodeId(0), g)? {
|
||||
None => None,
|
||||
Some(art) => {
|
||||
*pixels = pixels.saturating_add(u64::from(w) * u64::from(h));
|
||||
if *pixels > MAX_TEXTURE_PIXELS {
|
||||
return Err(format!(
|
||||
"the graphics need more than {MAX_TEXTURE_PIXELS} pixels of textures: lower textureSize (now {size})"
|
||||
));
|
||||
}
|
||||
let renderer = renderer.get_or_insert_with(vectorcraft_render::Renderer::new);
|
||||
Some(picture(doc, renderer, (part.color, g.opacity, g.object), art, (frame, scale), (w, h))?)
|
||||
}
|
||||
};
|
||||
drawn.push((part, frame, png.clone()));
|
||||
png
|
||||
}
|
||||
};
|
||||
out.push(png.map(|(png, opacity)| {
|
||||
let uv = g.art.iter().map(|p| [(p.x - frame.x0) * scale / f64::from(w), (p.y - frame.y0) * scale / f64::from(h)]).collect();
|
||||
Texture { png, opacity, uv }
|
||||
}));
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Does [`textures`] draw a picture for one of `parts`: a part with graphics whose corners span an
|
||||
/// area and whose graphics draw something? Nothing is rendered.
|
||||
pub fn draws_textures(doc: &Document, parts: &[SolidMesh]) -> bool {
|
||||
parts.iter().any(|p| {
|
||||
p.graphics
|
||||
.as_ref()
|
||||
.is_some_and(|g| texture_frame(g).is_some() && matches!(vectorcraft_render::effects::mesh_graphics_art(doc, NodeId(0), g), Ok(Some(_))))
|
||||
})
|
||||
}
|
||||
|
||||
/// The part of the art's plane a picture of `g` covers: the bounds of its corners' art points, when
|
||||
/// they span an area.
|
||||
fn texture_frame(g: &MeshGraphics) -> Option<Rect> {
|
||||
g.art_bounds().filter(|r| r.width() > 1e-9 && r.height() > 1e-9 && r.width().is_finite() && r.height().is_finite())
|
||||
}
|
||||
|
||||
/// A picture [`textures`] drew: the part, the bounds and the PNG with its opacity map.
|
||||
type Drawn<'a> = (&'a SolidMesh, Rect, Option<Picture>);
|
||||
|
||||
/// Do `a` and `b` draw the same graphics on their face?
|
||||
fn same_graphics(a: &MeshGraphics, b: &MeshGraphics) -> bool {
|
||||
a.face == b.face && a.center == b.center && a.graphics == b.graphics && a.opacity == b.opacity && a.object == b.object
|
||||
}
|
||||
|
||||
/// `art` drawn over `color` as a PNG of `w` × `h` pixels whose top left is `frame`'s top left, at
|
||||
/// `scale` pixels a point, with a grayscale PNG of its alpha when some of it is not opaque. As on
|
||||
/// the canvas, the art is drawn at `face` (the opacity of the face's fill or stroke), the color at
|
||||
/// its own opacity without `object`'s, and `object` (the object's opacity) applies to the whole
|
||||
/// picture.
|
||||
fn picture(
|
||||
doc: &Document,
|
||||
renderer: &mut vectorcraft_render::Renderer,
|
||||
(color, face, object): ([f32; 4], f32, f32),
|
||||
mut art: Node,
|
||||
(frame, scale): (Rect, f64),
|
||||
(w, h): (u32, u32),
|
||||
) -> Result<Picture, String> {
|
||||
// The color reaches two pixels past the frame, so the picture's edge pixels are covered.
|
||||
let reach = 2.0 / scale;
|
||||
let back = Rect::new(frame.x0 - reach, frame.y0 - reach, frame.x0 + f64::from(w) / scale + reach, frame.y0 + f64::from(h) / scale + reach);
|
||||
let fill = Paint::solid(Color::rgb(color[0], color[1], color[2]));
|
||||
let mut ground = Node::path(NodeId(0), vectorcraft_geom::shapes::rectangle(back), Appearance::basic(fill, Paint::None, 0.0));
|
||||
let unit = |v: f32| if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 };
|
||||
let object = unit(object);
|
||||
ground.opacity = if object > 0.0 { unit(color[3] / object) } else { 0.0 };
|
||||
art.opacity *= unit(face);
|
||||
let mut group = Node::group(NodeId(0), vec![Arc::new(ground), Arc::new(art)]);
|
||||
group.opacity = object;
|
||||
let group = Arc::new(group);
|
||||
let (pw, ph) = (u16::try_from(w).map_err(|_| "texture too large")?, u16::try_from(h).map_err(|_| "texture too large")?);
|
||||
let view = Affine::scale(scale) * Affine::translate((-frame.x0, -frame.y0));
|
||||
let drawn = renderer.render_node(doc, &group, pw, ph, view).ok_or_else(|| "the graphics could not be drawn".to_string())?;
|
||||
let alpha: Vec<u8> = drawn.pixels.iter().skip(3).step_by(4).copied().collect();
|
||||
let opacity = if alpha.iter().all(|a| *a == 255) {
|
||||
None
|
||||
} else {
|
||||
let gray = image::GrayImage::from_raw(w, h, alpha).ok_or("the texture's opacity could not be drawn")?;
|
||||
let mut png = vec![];
|
||||
gray.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).map_err(|e| format!("PNG encoding failed: {e}"))?;
|
||||
Some(Arc::new(png))
|
||||
};
|
||||
Ok((Arc::new(drawn.to_png()?), opacity))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -7,7 +7,7 @@ use super::*;
|
||||
fn square(color: [f32; 4]) -> SolidMesh {
|
||||
let [a, b, c, d] = [[-5.0, -5.0, 0.0], [5.0, -5.0, 0.0], [5.0, 5.0, 0.0], [-5.0, 5.0, 0.0]];
|
||||
let mesh = Mesh { positions: vec![a, b, c, a, c, d], normals: vec![[0.0, 0.0, 1.0]; 6], triangles: vec![[0, 1, 2], [3, 4, 5]] };
|
||||
SolidMesh { mesh, color }
|
||||
SolidMesh::plain(mesh, color)
|
||||
}
|
||||
|
||||
const RED: [f32; 4] = [1.0, 0.0, 0.0, 1.0];
|
||||
@@ -18,9 +18,14 @@ fn text(files: &[(String, Vec<u8>)], name: &str) -> String {
|
||||
String::from_utf8(bytes.clone()).unwrap()
|
||||
}
|
||||
|
||||
/// [`mesh_files`] without textures.
|
||||
fn plain_files(stem: &str, format: &str, parts: &[SolidMesh]) -> Result<Vec<(String, Vec<u8>)>, String> {
|
||||
mesh_files(stem, format, parts, &[])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn obj_numbers_corners_across_solids_and_names_its_materials() {
|
||||
let files = mesh_files("Box", "obj", &[square(RED), square(BLUE), square(RED)]).unwrap();
|
||||
let files = plain_files("Box", "obj", &[square(RED), square(BLUE), square(RED)]).unwrap();
|
||||
assert_eq!(files.iter().map(|(n, _)| n.as_str()).collect::<Vec<_>>(), ["Box.obj", "Box.mtl"]);
|
||||
let obj = text(&files, "Box.obj");
|
||||
assert!(obj.starts_with("mtllib Box.mtl\no Box\n"));
|
||||
@@ -36,7 +41,7 @@ fn obj_numbers_corners_across_solids_and_names_its_materials() {
|
||||
|
||||
#[test]
|
||||
fn gltf_holds_its_buffer_and_every_accessor_fits_it() {
|
||||
let files = mesh_files("Box", "gltf", &[square(RED), square(BLUE)]).unwrap();
|
||||
let files = plain_files("Box", "gltf", &[square(RED), square(BLUE)]).unwrap();
|
||||
let g: Value = serde_json::from_str(&text(&files, "Box.gltf")).unwrap();
|
||||
assert_eq!(g["asset"]["version"], "2.0");
|
||||
let uri = g["buffers"][0]["uri"].as_str().unwrap();
|
||||
@@ -59,11 +64,13 @@ fn gltf_holds_its_buffer_and_every_accessor_fits_it() {
|
||||
assert_eq!(g["materials"][1]["alphaMode"], "BLEND");
|
||||
assert!(g["materials"][0].get("alphaMode").is_none());
|
||||
assert_eq!(g["materials"][0]["doubleSided"], true);
|
||||
// Without graphics there are no textures.
|
||||
assert!(g.get("images").is_none() && g.get("textures").is_none() && prims[0]["attributes"].get("TEXCOORD_0").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn usda_is_y_up_in_points_with_a_material_for_each_color() {
|
||||
let files = mesh_files("My Box", "usda", &[square(RED), square([0.5, 0.5, 0.5, 1.0])]).unwrap();
|
||||
let files = plain_files("My Box", "usda", &[square(RED), square([0.5, 0.5, 0.5, 1.0])]).unwrap();
|
||||
let u = text(&files, "My Box.usda");
|
||||
assert!(u.starts_with("#usda 1.0\n"));
|
||||
assert!(u.contains("defaultPrim = \"My_Box\"") && u.contains("upAxis = \"Y\"") && u.contains("def Xform \"My_Box\""), "{u}");
|
||||
@@ -75,11 +82,12 @@ fn usda_is_y_up_in_points_with_a_material_for_each_color() {
|
||||
// sRGB 0.5 is about 0.214 linear.
|
||||
assert!(u.contains("color3f inputs:diffuseColor = (0.21404"), "{u}");
|
||||
assert_eq!(u.matches('{').count(), u.matches('}').count());
|
||||
assert!(!u.contains("primvars:st") && !u.contains("UsdUVTexture"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn usdz_stores_the_layer_uncompressed_on_a_64_byte_boundary() {
|
||||
let files = mesh_files("Box", "usdz", &[square(RED)]).unwrap();
|
||||
let files = plain_files("Box", "usdz", &[square(RED)]).unwrap();
|
||||
let (name, zip) = &files[0];
|
||||
assert_eq!(name, "Box.usdz");
|
||||
// The local header: 30 bytes, the name, then the extra field.
|
||||
@@ -88,7 +96,7 @@ fn usdz_stores_the_layer_uncompressed_on_a_64_byte_boundary() {
|
||||
assert_eq!(u16_at(8), 0, "stored, not deflated");
|
||||
let start = 30 + u16_at(26) + u16_at(28);
|
||||
assert_eq!(start % 64, 0);
|
||||
let layer = mesh_files("Box", "usda", &[square(RED)]).unwrap().remove(0).1;
|
||||
let layer = plain_files("Box", "usda", &[square(RED)]).unwrap().remove(0).1;
|
||||
assert_eq!(&zip[start..start + layer.len()], layer.as_slice());
|
||||
let archive = super::super::zip::Archive::open(zip, 8).unwrap();
|
||||
assert_eq!(archive.read("Box.usda", usize::MAX).unwrap(), Some(layer));
|
||||
@@ -96,11 +104,11 @@ fn usdz_stores_the_layer_uncompressed_on_a_64_byte_boundary() {
|
||||
|
||||
#[test]
|
||||
fn an_obj_names_its_mtl_file_without_spaces_or_comment_marks() {
|
||||
let files = mesh_files("Box #1", "obj", &[square(RED)]).unwrap();
|
||||
let files = plain_files("Box #1", "obj", &[square(RED)]).unwrap();
|
||||
assert_eq!(files.iter().map(|(n, _)| n.as_str()).collect::<Vec<_>>(), ["Box__1.obj", "Box__1.mtl"]);
|
||||
assert!(text(&files, "Box__1.obj").starts_with("mtllib Box__1.mtl\n"));
|
||||
assert_eq!(mesh_file_names("Box #1", "obj").unwrap(), ["Box__1.obj", "Box__1.mtl"]);
|
||||
assert_eq!(mesh_file_names("Box #1", "usda").unwrap(), ["Box #1.usda"]);
|
||||
assert_eq!(mesh_file_names("Box #1", "obj", &[]).unwrap(), ["Box__1.obj", "Box__1.mtl"]);
|
||||
assert_eq!(mesh_file_names("Box #1", "usda", &[]).unwrap(), ["Box #1.usda"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -108,17 +116,17 @@ fn obj_and_usda_keep_coordinates_a_32_bit_float_would_merge() {
|
||||
let mut part = square(RED);
|
||||
part.mesh.positions[0] = [20_000_000.0, 0.0, 0.0];
|
||||
part.mesh.positions[1] = [20_000_001.0, 0.0, 0.0];
|
||||
let obj = text(&mesh_files("Box", "obj", std::slice::from_ref(&part)).unwrap(), "Box.obj");
|
||||
let obj = text(&plain_files("Box", "obj", std::slice::from_ref(&part)).unwrap(), "Box.obj");
|
||||
assert!(obj.contains("v 20000000 0 0\nv 20000001 0 0\n"), "{obj}");
|
||||
let usda = text(&mesh_files("Box", "usda", &[part]).unwrap(), "Box.usda");
|
||||
let usda = text(&plain_files("Box", "usda", &[part]).unwrap(), "Box.usda");
|
||||
assert!(usda.contains("(20000001, 0, 0)"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unknown_format_is_refused() {
|
||||
assert!(mesh_files("Box", "fbx", &[square(RED)]).is_err());
|
||||
assert!(mesh_file_names("Box", "").is_err());
|
||||
assert_eq!(mesh_file_names("Box", "obj").unwrap(), ["Box.obj", "Box.mtl"]);
|
||||
assert!(plain_files("Box", "fbx", &[square(RED)]).is_err());
|
||||
assert!(mesh_file_names("Box", "", &[]).is_err());
|
||||
assert_eq!(mesh_file_names("Box", "obj", &[]).unwrap(), ["Box.obj", "Box.mtl"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -128,3 +136,114 @@ fn prim_names_are_usd_identifiers() {
|
||||
assert_eq!(prim_name(""), "_");
|
||||
assert_eq!(prim_name("é/x"), "__x");
|
||||
}
|
||||
|
||||
/// A red square, then a blue one whose corners show picture `png` (u to the right, v down).
|
||||
fn textured(png: &[u8]) -> (Vec<SolidMesh>, Vec<Option<Texture>>) {
|
||||
let uv = vec![[0.0, 1.0], [1.0, 1.0], [1.0, 0.0], [0.0, 1.0], [1.0, 0.0], [0.0, 0.0]];
|
||||
let texture = Texture { png: Arc::new(png.to_vec()), opacity: None, uv };
|
||||
(vec![square(RED), square(BLUE)], vec![None, Some(texture)])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_format_carries_a_textured_part_with_its_coordinates_and_picture() {
|
||||
let png = b"\x89PNG picture".to_vec();
|
||||
let (parts, pictures) = textured(&png);
|
||||
// OBJ: vt runs up from the picture's bottom, the textured faces name it, and map_Kd the PNG
|
||||
// written beside it, with its name in one word.
|
||||
let files = mesh_files("My Box", "obj", &parts, &pictures).unwrap();
|
||||
assert_eq!(files.iter().map(|(n, _)| n.as_str()).collect::<Vec<_>>(), ["My_Box.obj", "My_Box.mtl", "My_Box-texture-1.png"]);
|
||||
assert_eq!(files[2].1, png);
|
||||
let obj = text(&files, "My_Box.obj");
|
||||
assert_eq!(obj.lines().filter(|l| l.starts_with("vt ")).collect::<Vec<_>>(), ["vt 0 0", "vt 1 0", "vt 1 1", "vt 0 0", "vt 1 1", "vt 0 1"]);
|
||||
assert_eq!(obj.lines().rfind(|l| l.starts_with("f ")), Some("f 10/4/10 11/5/11 12/6/12"));
|
||||
assert!(obj.contains("f 1//1 2//2 3//3"), "the plain part keeps no texture coordinates");
|
||||
let mtl = text(&files, "My_Box.mtl");
|
||||
assert!(mtl.contains("newmtl Material_2\nKd 1 1 1\nd 1\nillum 1\nmap_Kd -clamp on My_Box-texture-1.png\n"), "{mtl}");
|
||||
assert_eq!(mtl.matches("map_Kd").count(), 1);
|
||||
// glTF: TEXCOORD_0 down from the top, and the picture embedded as a data URI.
|
||||
let g: Value = serde_json::from_str(&text(&mesh_files("Box", "gltf", &parts, &pictures).unwrap(), "Box.gltf")).unwrap();
|
||||
let prims = g["meshes"][0]["primitives"].as_array().unwrap();
|
||||
assert!(prims[0]["attributes"].get("TEXCOORD_0").is_none());
|
||||
let uv = &g["accessors"][prims[1]["attributes"]["TEXCOORD_0"].as_u64().unwrap() as usize];
|
||||
assert_eq!((uv["type"].as_str(), uv["count"].as_u64(), uv["componentType"].as_u64()), (Some("VEC2"), Some(6), Some(5126)));
|
||||
let view = &g["bufferViews"][uv["bufferView"].as_u64().unwrap() as usize];
|
||||
let data = vectorcraft_format::base64_decode(g["buffers"][0]["uri"].as_str().unwrap().split(',').nth(1).unwrap()).unwrap();
|
||||
let at = view["byteOffset"].as_u64().unwrap() as usize;
|
||||
let first: Vec<f32> = (0..2).map(|k| f32::from_le_bytes(data[at + 4 * k..at + 4 * k + 4].try_into().unwrap())).collect();
|
||||
assert_eq!(first, [0.0, 1.0]);
|
||||
let material = &g["materials"][prims[1]["material"].as_u64().unwrap() as usize];
|
||||
assert_eq!(material["pbrMetallicRoughness"]["baseColorTexture"]["index"], 0);
|
||||
assert_eq!(material["pbrMetallicRoughness"]["baseColorFactor"], serde_json::json!([1.0, 1.0, 1.0, 1.0]));
|
||||
assert_eq!(g["textures"][0]["source"], 0);
|
||||
assert_eq!(g["samplers"][0]["wrapS"], 33071);
|
||||
let image = g["images"][0]["uri"].as_str().unwrap().strip_prefix("data:image/png;base64,").unwrap();
|
||||
assert_eq!(vectorcraft_format::base64_decode(image).unwrap(), png);
|
||||
// USDA: st up from the bottom, read by a primvar reader into a UV texture of the PNG beside it.
|
||||
let files = mesh_files("Box", "usda", &parts, &pictures).unwrap();
|
||||
assert_eq!(files.iter().map(|(n, _)| n.as_str()).collect::<Vec<_>>(), ["Box.usda", "Box-texture-1.png"]);
|
||||
let u = text(&files, "Box.usda");
|
||||
assert_eq!(u.matches("primvars:st").count(), 1);
|
||||
assert!(u.contains("texCoord2f[] primvars:st = [(0, 0), (1, 0), (1, 1), (0, 0), (1, 1), (0, 1)]"), "{u}");
|
||||
assert!(u.contains("color3f inputs:diffuseColor.connect = </Box/Materials/Material_2/Texture.outputs:rgb>"), "{u}");
|
||||
assert!(u.contains("asset inputs:file = @Box-texture-1.png@") && u.contains("uniform token info:id = \"UsdUVTexture\""));
|
||||
assert!(u.contains("float2 inputs:st.connect = </Box/Materials/Material_2/Coordinates.outputs:result>"));
|
||||
assert!(u.contains("string inputs:varname = \"st\""));
|
||||
assert_eq!(u.matches('{').count(), u.matches('}').count());
|
||||
// USDZ: the layer first, then the picture, each on a 64-byte boundary.
|
||||
let zip = mesh_files("Box", "usdz", &parts, &pictures).unwrap().remove(0).1;
|
||||
let archive = super::super::zip::Archive::open(&zip, 8).unwrap();
|
||||
assert_eq!(archive.read("Box.usda", usize::MAX).unwrap().map(String::from_utf8), Some(Ok(u)));
|
||||
assert_eq!(archive.read("Box-texture-1.png", usize::MAX).unwrap(), Some(png.clone()));
|
||||
let u16_at = |at: usize| u16::from_le_bytes([zip[at], zip[at + 1]]) as usize;
|
||||
let u32_at = |at: usize| u32::from_le_bytes([zip[at], zip[at + 1], zip[at + 2], zip[at + 3]]) as usize;
|
||||
let first = 30 + u16_at(26) + u16_at(28);
|
||||
let second = first + u32_at(18);
|
||||
assert_eq!(&zip[second..second + 4], &[0x50, 0x4b, 0x03, 0x04], "the picture comes second");
|
||||
let data = second + 30 + u16_at(second + 26) + u16_at(second + 28);
|
||||
assert_eq!((first % 64, data % 64), (0, 0));
|
||||
assert_eq!(&zip[data..data + png.len()], png.as_slice());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_textured_face_that_is_not_opaque_takes_its_opacity_from_the_picture() {
|
||||
let (parts, mut pictures) = textured(b"picture");
|
||||
if let Some(t) = pictures[1].as_mut() {
|
||||
t.opacity = Some(Arc::new(b"gray".to_vec()));
|
||||
}
|
||||
// OBJ: the opacity map, written after its texture, is the MTL's map_d.
|
||||
let files = mesh_files("My Box", "obj", &parts, &pictures).unwrap();
|
||||
let names: Vec<&str> = files.iter().map(|(n, _)| n.as_str()).collect();
|
||||
assert_eq!(names, ["My_Box.obj", "My_Box.mtl", "My_Box-texture-1.png", "My_Box-texture-1-opacity.png"]);
|
||||
assert_eq!(files[3].1, b"gray");
|
||||
assert_eq!(mesh_file_names("My Box", "obj", &image_maps(&pictures)).unwrap(), names);
|
||||
let mtl = text(&files, "My_Box.mtl");
|
||||
assert!(mtl.contains("d 1\nillum 1\nmap_Kd -clamp on My_Box-texture-1.png\nmap_d -clamp on My_Box-texture-1-opacity.png\n"), "{mtl}");
|
||||
let g: Value = serde_json::from_str(&text(&mesh_files("Box", "gltf", &parts, &pictures).unwrap(), "Box.gltf")).unwrap();
|
||||
let material = &g["materials"][1];
|
||||
assert_eq!((material["pbrMetallicRoughness"]["baseColorFactor"][3].as_f64(), material["alphaMode"].as_str()), (Some(1.0), Some("BLEND")));
|
||||
let usda = mesh_files("Box", "usda", &parts, &pictures).unwrap();
|
||||
assert_eq!(usda.len(), 2, "USD reads the opacity from the texture's alpha");
|
||||
let u = text(&usda, "Box.usda");
|
||||
assert!(u.contains("float inputs:opacity.connect = </Box/Materials/Material_2/Texture.outputs:a>") && u.contains("float outputs:a"), "{u}");
|
||||
// An opaque textured face reads no opacity from its picture.
|
||||
let (_, plain) = textured(b"picture");
|
||||
let opaque = vec![square(RED), square([0.0, 0.0, 1.0, 1.0])];
|
||||
let u = text(&mesh_files("Box", "usda", &opaque, &plain).unwrap(), "Box.usda");
|
||||
assert!(!u.contains("outputs:a") && u.contains("float inputs:opacity = 1"), "{u}");
|
||||
let mtl = text(&mesh_files("Box", "obj", &opaque, &plain).unwrap(), "Box.mtl");
|
||||
assert!(!mtl.contains("map_d") && mtl.contains("Kd 1 1 1\nd 1\n"), "{mtl}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parts_sharing_a_picture_write_it_once() {
|
||||
let (mut parts, mut pictures) = textured(b"one");
|
||||
parts.push(square(BLUE));
|
||||
pictures.push(pictures[1].clone());
|
||||
assert_eq!(image_maps(&pictures), [false]);
|
||||
let files = mesh_files("Box", "obj", &parts, &pictures).unwrap();
|
||||
assert_eq!(files.len(), 3);
|
||||
assert_eq!(text(&files, "Box.mtl").matches("newmtl").count(), 2, "the blue parts share the textured material");
|
||||
assert_eq!(mesh_file_names("Box", "usda", &[false, true]).unwrap(), ["Box.usda", "Box-texture-1.png", "Box-texture-2.png"]);
|
||||
assert_eq!(mesh_file_names("A @b", "gltf", &[false, false]).unwrap(), ["A @b.gltf"]);
|
||||
assert_eq!(texture_name("A @b#c", 0), "A__b_c-texture-1.png");
|
||||
}
|
||||
@@ -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()))
|
||||
}
|
||||
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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.
|
||||
|
||||
Loaded 100 of 624 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user