Merge main into feat/palette-compact-rows

This commit is contained in:
dotCooCoo
2026-11-16 10:05:26 -08:00
539 changed files with 38189 additions and 3973 deletions
Generated
+236 -110
View File
@@ -146,13 +146,28 @@ version = "2.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cc7bb162ec39d46ab1ca8c77bf72e890535becd1751bb45f64c597edb4c8c6b3"
[[package]]
name = "alloc-no-stdlib"
version = "3.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2fb6cfd47bf496ff64095c20eaba0c201404ee38714d4142fcfa1dc334fcc7a"
[[package]]
name = "alloc-stdlib"
version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0e76a019e91224d279006ff972f1e984179a6e9feb050adba6ce8274aef23195"
dependencies = [
"alloc-no-stdlib",
"alloc-no-stdlib 2.0.4",
]
[[package]]
name = "alloc-stdlib"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b5c1865780388bfa186411ab5f247819487fc4864c6e9c3106611fa347586e1"
dependencies = [
"alloc-no-stdlib 3.0.0",
]
[[package]]
@@ -217,7 +232,7 @@ dependencies = [
"objc2-foundation 0.3.2",
"parking_lot",
"percent-encoding",
"windows-sys 0.52.0",
"windows-sys 0.61.2",
"wl-clipboard-rs",
"x11rb",
]
@@ -596,9 +611,9 @@ version = "8.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5cc91aac060a7a1e25823bdccbfb6af1875b88f17c6daac97894eed8207166b3"
dependencies = [
"alloc-no-stdlib",
"alloc-stdlib",
"brotli-decompressor",
"alloc-no-stdlib 2.0.4",
"alloc-stdlib 0.2.4",
"brotli-decompressor 5.0.3",
]
[[package]]
@@ -607,8 +622,18 @@ version = "5.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3a32acac15fe1967bc3986b2a6347dffc965602354ea6f450ad07e8bfd253583"
dependencies = [
"alloc-no-stdlib",
"alloc-stdlib",
"alloc-no-stdlib 2.0.4",
"alloc-stdlib 0.2.4",
]
[[package]]
name = "brotli-decompressor"
version = "6.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cc031cd87c6529082b0b65c604e86af0ed7744841b17ccfe60b1e31fa606179e"
dependencies = [
"alloc-no-stdlib 3.0.0",
"alloc-stdlib 0.3.0",
]
[[package]]
@@ -976,7 +1001,7 @@ dependencies = [
[[package]]
name = "craft-affinity"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=228f6d0c50f1fdee4c5124603602993fc79d4c9d#228f6d0c50f1fdee4c5124603602993fc79d4c9d"
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
dependencies = [
"crc32fast",
"flate2",
@@ -987,17 +1012,17 @@ dependencies = [
[[package]]
name = "craft-codepage"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=8bd1412eaa7c0b58f3f9c401495d35fe12d6d85e#8bd1412eaa7c0b58f3f9c401495d35fe12d6d85e"
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
[[package]]
name = "craft-docpath"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb#9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb"
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
[[package]]
name = "craft-dxf"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=8bd1412eaa7c0b58f3f9c401495d35fe12d6d85e#8bd1412eaa7c0b58f3f9c401495d35fe12d6d85e"
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
dependencies = [
"craft-codepage",
"encoding_rs",
@@ -1009,17 +1034,25 @@ dependencies = [
[[package]]
name = "craft-eps"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6d620e971e820b517b11a99cad040ebac670e1e2#6d620e971e820b517b11a99cad040ebac670e1e2"
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
[[package]]
name = "craft-fonts-build"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=c4b8405d5fd8f29cf77de528206bd2b38bb0ecb6#c4b8405d5fd8f29cf77de528206bd2b38bb0ecb6"
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
[[package]]
name = "craft-gif"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
dependencies = [
"gif",
]
[[package]]
name = "craft-gzip"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=b0d84cd15db39f2af9869cfb47b8b72cbeca3f20#b0d84cd15db39f2af9869cfb47b8b72cbeca3f20"
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
dependencies = [
"flate2",
]
@@ -1027,7 +1060,7 @@ dependencies = [
[[package]]
name = "craft-i18n"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=c4b8405d5fd8f29cf77de528206bd2b38bb0ecb6#c4b8405d5fd8f29cf77de528206bd2b38bb0ecb6"
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
dependencies = [
"fixed_decimal",
"icu_decimal",
@@ -1050,12 +1083,16 @@ dependencies = [
[[package]]
name = "craft-image-codecs"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e2dc681a3#e2dc681a3ad8a47038da2f11ddd2c5e1c0454991"
source = "git+https://github.com/storytold/craft-libs?rev=431f704478962677ec47e512754464d372901830#431f704478962677ec47e512754464d372901830"
dependencies = [
"craft-jpeg",
"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",
@@ -1064,33 +1101,101 @@ dependencies = [
"serde_json",
"thiserror 2.0.21",
"tiff",
"zune-core 0.5.3",
"zune-jpeg 0.5.15",
"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)",
"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-jpeg"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e2dc681a3#e2dc681a3ad8a47038da2f11ddd2c5e1c0454991"
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"
dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "craft-jxl"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
dependencies = [
"jixel",
"jxl-oxide",
"thiserror 2.0.21",
]
[[package]]
name = "craft-keymap"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb#9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb"
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
dependencies = [
"egui",
"serde",
"serde_json",
]
[[package]]
name = "craft-metadata"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=431f704478962677ec47e512754464d372901830#431f704478962677ec47e512754464d372901830"
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)",
"quick-xml 0.41.0",
"serde",
]
[[package]]
name = "craft-metafile"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6d620e971e820b517b11a99cad040ebac670e1e2#6d620e971e820b517b11a99cad040ebac670e1e2"
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
dependencies = [
"encoding_rs",
"image",
@@ -1101,7 +1206,7 @@ dependencies = [
[[package]]
name = "craft-pdf"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb#9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb"
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
dependencies = [
"hayro-interpret",
"hayro-syntax",
@@ -1112,7 +1217,7 @@ dependencies = [
[[package]]
name = "craft-print"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb#9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb"
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
dependencies = [
"craft-winprint-gdi",
"log",
@@ -1126,7 +1231,7 @@ dependencies = [
[[package]]
name = "craft-proof"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb#9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb"
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
dependencies = [
"log",
"miniz_oxide 0.9.1",
@@ -1137,7 +1242,7 @@ dependencies = [
[[package]]
name = "craft-psd"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e2dc681a3#e2dc681a3ad8a47038da2f11ddd2c5e1c0454991"
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
dependencies = [
"encoding_rs",
"flate2",
@@ -1145,14 +1250,29 @@ dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "craft-stream-codecs"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
dependencies = [
"fax",
"hayro-ccitt",
"hayro-jbig2",
"thiserror 2.0.21",
]
[[package]]
name = "craft-svg"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6d620e971e820b517b11a99cad040ebac670e1e2#6d620e971e820b517b11a99cad040ebac670e1e2"
source = "git+https://github.com/storytold/craft-libs?rev=431f704478962677ec47e512754464d372901830#431f704478962677ec47e512754464d372901830"
dependencies = [
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=6d620e971e820b517b11a99cad040ebac670e1e2)",
"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)",
"data-url",
"flate2",
"kurbo 0.13.1",
"quick-xml 0.41.0",
"resvg 0.48.1",
"roxmltree 0.21.2",
"thiserror 2.0.21",
"usvg 0.48.1",
@@ -1163,7 +1283,16 @@ dependencies = [
[[package]]
name = "craft-tiff"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e2dc681a3#e2dc681a3ad8a47038da2f11ddd2c5e1c0454991"
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"
dependencies = [
"serde",
"thiserror 2.0.21",
@@ -1172,7 +1301,7 @@ dependencies = [
[[package]]
name = "craft-ui"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=c4b8405d5fd8f29cf77de528206bd2b38bb0ecb6#c4b8405d5fd8f29cf77de528206bd2b38bb0ecb6"
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
dependencies = [
"craft-fonts-build",
"craft-i18n",
@@ -1193,7 +1322,7 @@ dependencies = [
[[package]]
name = "craft-update"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280#e98299546f5c5c3c22388d16507f8b5e61a5f280"
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
dependencies = [
"chrono",
"dunce",
@@ -1220,7 +1349,7 @@ dependencies = [
[[package]]
name = "craft-vectorcraft-format"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=b0d84cd15db39f2af9869cfb47b8b72cbeca3f20#b0d84cd15db39f2af9869cfb47b8b72cbeca3f20"
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
dependencies = [
"flate2",
"serde",
@@ -1242,7 +1371,7 @@ dependencies = [
[[package]]
name = "craft-window"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb#9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb"
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
dependencies = [
"egui",
"objc2 0.6.5",
@@ -1253,7 +1382,7 @@ dependencies = [
[[package]]
name = "craft-winprint-gdi"
version = "0.1.0"
source = "git+https://github.com/storytold/winprint.rs?rev=417ac3c4d14d3da5485a99c7d5ce8f05664ec312#417ac3c4d14d3da5485a99c7d5ce8f05664ec312"
source = "git+https://github.com/storytold/winprint.rs?rev=64e7afd4d1483512385012c340ecaaaf0f3beb7f#64e7afd4d1483512385012c340ecaaaf0f3beb7f"
dependencies = [
"windows-sys 0.61.2",
]
@@ -1261,18 +1390,20 @@ dependencies = [
[[package]]
name = "craft-xml"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6d620e971e820b517b11a99cad040ebac670e1e2#6d620e971e820b517b11a99cad040ebac670e1e2"
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=e2dc681a3#e2dc681a3ad8a47038da2f11ddd2c5e1c0454991"
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
dependencies = [
"quick-xml 0.41.0",
"serde",
"thiserror 2.0.21",
]
@@ -1750,7 +1881,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
dependencies = [
"libc",
"windows-sys 0.52.0",
"windows-sys 0.61.2",
]
[[package]]
@@ -2143,16 +2274,6 @@ dependencies = [
"wasm-bindgen",
]
[[package]]
name = "gif"
version = "0.13.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4ae047235e33e2829703574b54fdec96bfbad892062d97fed2f76022287de61b"
dependencies = [
"color_quant",
"weezl 0.1.12",
]
[[package]]
name = "gif"
version = "0.14.2"
@@ -2386,7 +2507,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a"
[[package]]
name = "hayro-cmap"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb#9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb"
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
dependencies = [
"brotli",
"hayro-postscript",
@@ -2395,7 +2516,7 @@ dependencies = [
[[package]]
name = "hayro-interpret"
version = "0.7.0"
source = "git+https://github.com/storytold/craft-libs?rev=9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb#9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb"
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
dependencies = [
"bitflags 2.13.2",
"hayro-cmap",
@@ -2413,7 +2534,7 @@ dependencies = [
[[package]]
name = "hayro-jbig2"
version = "0.3.0"
source = "git+https://github.com/storytold/craft-libs?rev=9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb#9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb"
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
dependencies = [
"fearless_simd",
"hayro-ccitt",
@@ -2431,12 +2552,12 @@ dependencies = [
[[package]]
name = "hayro-postscript"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb#9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb"
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
[[package]]
name = "hayro-syntax"
version = "0.7.2"
source = "git+https://github.com/storytold/craft-libs?rev=9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb#9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb"
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
dependencies = [
"flate2",
"hayro-ccitt",
@@ -2446,7 +2567,7 @@ dependencies = [
"rustc-hash 2.1.3",
"smallvec",
"stringprep",
"zune-jpeg 0.5.15",
"zune-jpeg",
]
[[package]]
@@ -2831,15 +2952,15 @@ dependencies = [
"bytemuck",
"byteorder-lite",
"color_quant",
"gif 0.14.2",
"gif",
"image-webp",
"moxcms",
"num-traits",
"png 0.18.1",
"qoi",
"tiff",
"zune-core 0.5.3",
"zune-jpeg 0.5.15",
"zune-core",
"zune-jpeg",
]
[[package]]
@@ -2929,6 +3050,12 @@ version = "1.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
[[package]]
name = "jixel"
version = "0.3.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "278a75e12caacec34be774d62ad05e45fc0b6a52d1f4e9f7fbc0209ecdf794f3"
[[package]]
name = "jni"
version = "0.22.4"
@@ -3092,7 +3219,7 @@ version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e35d032bcec660647828527ff42c6f5776d2fd44b8357f9f6d9ac6dc07218e46"
dependencies = [
"brotli-decompressor",
"brotli-decompressor 5.0.3",
"jxl-bitstream",
"jxl-frame",
"jxl-grid",
@@ -3124,7 +3251,7 @@ version = "0.12.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d36c662923f47586880211f3bc7c0d83fb3a9b410d278c7bde93450748abeef3"
dependencies = [
"brotli-decompressor",
"brotli-decompressor 5.0.3",
"jxl-bitstream",
"jxl-color",
"jxl-frame",
@@ -3230,13 +3357,13 @@ dependencies = [
[[package]]
name = "krilla"
version = "0.8.2"
source = "git+https://github.com/storytold/craft-libs?rev=9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb#9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb"
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
dependencies = [
"base64 0.22.1",
"bumpalo",
"flate2",
"float-cmp",
"gif 0.14.2",
"gif",
"image-webp",
"imagesize 0.14.0",
"indexmap",
@@ -3251,7 +3378,7 @@ dependencies = [
"tiny-skia-path 0.12.0",
"xmp-writer",
"yoke",
"zune-jpeg 0.5.15",
"zune-jpeg",
]
[[package]]
@@ -3339,7 +3466,7 @@ checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4"
[[package]]
name = "linesweeper"
version = "0.5.0"
source = "git+https://github.com/storytold/craft-libs?rev=481f66d287b2a06845f3667a19daf35f0fe958ed#481f66d287b2a06845f3667a19daf35f0fe958ed"
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
dependencies = [
"arrayvec",
"kurbo 0.13.1",
@@ -4044,7 +4171,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967"
dependencies = [
"libc",
"windows-sys 0.52.0",
"windows-sys 0.61.2",
]
[[package]]
@@ -4566,7 +4693,7 @@ dependencies = [
"once_cell",
"socket2",
"tracing",
"windows-sys 0.52.0",
"windows-sys 0.61.2",
]
[[package]]
@@ -4806,15 +4933,12 @@ version = "0.45.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a8928798c0a55e03c9ca6c4c6846f76377427d2c1e1f7e6de3c06ae57942df43"
dependencies = [
"gif 0.13.3",
"image-webp",
"log",
"pico-args",
"rgb",
"svgtypes 0.15.3",
"tiny-skia 0.11.4",
"usvg 0.45.1",
"zune-jpeg 0.4.21",
]
[[package]]
@@ -4824,7 +4948,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67e3803f97b999e80cbf7c6ecdd07a8102204d92e1633cf48783720c521196bd"
dependencies = [
"bytemuck",
"gif 0.14.2",
"gif",
"image-webp",
"log",
"pico-args",
@@ -4832,7 +4956,7 @@ dependencies = [
"svgtypes 0.16.1",
"tiny-skia 0.12.0",
"usvg 0.48.1",
"zune-jpeg 0.5.15",
"zune-jpeg",
]
[[package]]
@@ -4944,7 +5068,7 @@ dependencies = [
"errno",
"libc",
"linux-raw-sys 0.12.1",
"windows-sys 0.52.0",
"windows-sys 0.61.2",
]
[[package]]
@@ -5003,7 +5127,7 @@ dependencies = [
"security-framework",
"security-framework-sys",
"webpki-root-certs",
"windows-sys 0.52.0",
"windows-sys 0.61.2",
]
[[package]]
@@ -5868,7 +5992,7 @@ dependencies = [
"getrandom 0.4.3",
"once_cell",
"rustix 1.1.6",
"windows-sys 0.52.0",
"windows-sys 0.61.2",
]
[[package]]
@@ -5940,7 +6064,7 @@ dependencies = [
"half",
"quick-error 2.0.1",
"weezl 0.1.12",
"zune-jpeg 0.5.15",
"zune-jpeg",
]
[[package]]
@@ -6547,8 +6671,8 @@ 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)",
"crc32fast",
"image",
"proptest",
]
@@ -6576,6 +6700,7 @@ name = "vectorcraft-cad"
version = "0.24.1"
dependencies = [
"craft-dxf",
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)",
"image",
"kurbo 0.13.1",
"serde_json",
@@ -6628,7 +6753,9 @@ name = "vectorcraft-doc"
version = "0.24.1"
dependencies = [
"chrono",
"hayro-ccitt",
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)",
"craft-stream-codecs",
"flate2",
"image",
"jpeg-encoder",
"kurbo 0.13.1",
@@ -6639,16 +6766,17 @@ dependencies = [
"tiff",
"vectorcraft-color",
"vectorcraft-geom 0.24.1",
"zune-jpeg 0.5.15",
"zune-jpeg",
]
[[package]]
name = "vectorcraft-effects"
version = "0.24.1"
dependencies = [
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)",
"craft-svg",
"image",
"kurbo 0.13.1",
"resvg 0.48.1",
"serde_json",
"svgtypes 0.16.1",
"vectorcraft-color",
@@ -6669,11 +6797,14 @@ dependencies = [
"cfb",
"chrono",
"craft-docpath",
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)",
"craft-jxl",
"craft-proof",
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e2dc681a3)",
"craft-stream-codecs",
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)",
"crc32fast",
"flate2",
"hayro-jpeg2000",
"hayro-ccitt",
"heic-rs",
"image",
"jxl-color",
@@ -6690,6 +6821,7 @@ dependencies = [
"serde_json",
"skrifa 0.47.0",
"thiserror 2.0.21",
"tiff",
"vectorcraft-affinity",
"vectorcraft-apischema",
"vectorcraft-brush",
@@ -6709,10 +6841,11 @@ dependencies = [
"vectorcraft-svg",
"vectorcraft-testkit",
"vectorcraft-text",
"vectorcraft-three-d",
"vectorcraft-tools",
"vectorcraft-trace",
"wat",
"zune-core 0.5.3",
"zune-core",
"zune-jpegxl",
]
@@ -6721,11 +6854,12 @@ 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-pdf",
"craft-stream-codecs",
"encoding_rs",
"fax",
"flate2",
"hayro-ccitt",
"image",
"kurbo 0.13.1",
"memchr",
@@ -6799,6 +6933,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)",
"image",
"log",
"proptest",
@@ -6818,6 +6953,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-metafile",
"image",
"kurbo 0.13.1",
@@ -6858,8 +6994,10 @@ version = "0.24.1"
dependencies = [
"aes",
"chrono",
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)",
"craft-pdf",
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e2dc681a3)",
"craft-stream-codecs",
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)",
"flate2",
"getrandom 0.4.3",
"image",
@@ -6884,15 +7022,14 @@ dependencies = [
"vectorcraft-geom 0.24.1",
"vectorcraft-testkit",
"vectorcraft-text",
"weezl 0.2.1",
]
[[package]]
name = "vectorcraft-plugins"
version = "0.24.1"
dependencies = [
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)",
"craft-vectorcraft-format",
"image",
"log",
"serde",
"serde_json",
@@ -6910,11 +7047,12 @@ dependencies = [
name = "vectorcraft-render"
version = "0.24.1"
dependencies = [
"craft-image-codecs",
"craft-gif",
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)",
"craft-psd",
"craft-tiff",
"craft-stream-codecs",
"craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)",
"flate2",
"gif 0.14.2",
"image",
"jpeg-encoder",
"log",
@@ -6949,13 +7087,13 @@ 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-svg",
"data-url",
"flate2",
"image",
"kurbo 0.13.1",
"proptest",
"resvg 0.45.1",
"serde",
"serde_json",
"simplecss",
@@ -6978,8 +7116,8 @@ dependencies = [
name = "vectorcraft-testkit"
version = "0.24.1"
dependencies = [
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)",
"fax",
"image",
"kurbo 0.13.1",
"proptest",
"serde_json",
@@ -7017,6 +7155,7 @@ dependencies = [
name = "vectorcraft-three-d"
version = "0.24.1"
dependencies = [
"proptest",
"vectorcraft-geom 0.24.1",
"vectorcraft-pathops 0.24.1",
]
@@ -7025,7 +7164,7 @@ dependencies = [
name = "vectorcraft-tools"
version = "0.24.1"
dependencies = [
"image",
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)",
"kurbo 0.13.1",
"serde",
"serde_json",
@@ -7042,7 +7181,7 @@ dependencies = [
name = "vectorcraft-trace"
version = "0.24.1"
dependencies = [
"craft-image-codecs",
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)",
"image",
"kurbo 0.13.1",
"serde",
@@ -7057,6 +7196,7 @@ version = "0.24.1"
dependencies = [
"bytemuck",
"chrono",
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)",
"craft-keymap",
"craft-ui",
"craft-update",
@@ -7733,7 +7873,7 @@ version = "0.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
dependencies = [
"windows-sys 0.52.0",
"windows-sys 0.61.2",
]
[[package]]
@@ -8011,7 +8151,7 @@ dependencies = [
[[package]]
name = "winprint"
version = "0.2.1"
source = "git+https://github.com/storytold/winprint.rs?rev=5f80b9baf6b58937c401656634e42d33f00ddf49#5f80b9baf6b58937c401656634e42d33f00ddf49"
source = "git+https://github.com/storytold/winprint.rs?rev=8ae097ef941b432b0e7671b1ec3a506800e65e57#8ae097ef941b432b0e7671b1ec3a506800e65e57"
dependencies = [
"flate2",
"fmt-derive",
@@ -8026,6 +8166,7 @@ dependencies = [
"windows",
"windows-core",
"windows-implement",
"windows-numerics",
"xml",
]
@@ -8485,12 +8626,6 @@ version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
[[package]]
name = "zune-core"
version = "0.4.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f423a2c17029964870cfaabb1f13dfab7d092a62a29a89264f4d36990ca414a"
[[package]]
name = "zune-core"
version = "0.5.3"
@@ -8506,22 +8641,13 @@ dependencies = [
"simd-adler32",
]
[[package]]
name = "zune-jpeg"
version = "0.4.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29ce2c8a9384ad323cf564b67da86e21d3cfdff87908bc1223ed5c99bc792713"
dependencies = [
"zune-core 0.4.12",
]
[[package]]
name = "zune-jpeg"
version = "0.5.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296"
dependencies = [
"zune-core 0.5.3",
"zune-core",
]
[[package]]
@@ -8530,7 +8656,7 @@ version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cba11ecd07cc23351500e840ae03841b7e4997923ec8e4832ee3ae199ea0b6b4"
dependencies = [
"zune-core 0.5.3",
"zune-core",
]
[[package]]
+43 -41
View File
@@ -11,35 +11,37 @@ rust-version = "1.95"
repository = "https://github.com/storytold/vectorcraft"
[workspace.dependencies]
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb", default-features = false, features = ["interpret", "write"] }
craft-print = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" }
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" }
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "c4b8405d5fd8f29cf77de528206bd2b38bb0ecb6", features = ["serde"] }
craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" }
craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" }
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" }
# 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 = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb", features = ["egui"] }
craft-window = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd", 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 = "b0d84cd15db39f2af9869cfb47b8b72cbeca3f20" }
craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "b0d84cd15db39f2af9869cfb47b8b72cbeca3f20" }
craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
# 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 = "228f6d0c50f1fdee4c5124603602993fc79d4c9d" }
craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
# SVG parsing, limits, SVGZ and writer (craft-libs#778).
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "6d620e971e820b517b11a99cad040ebac670e1e2", features = ["tree"] }
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "431f704478962677ec47e512754464d372901830", features = ["tree"] }
# EPS container, previews, ASCII85 and DSC comments (craft-libs#778).
craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "6d620e971e820b517b11a99cad040ebac670e1e2" }
craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
# DXF tags, reader and writer (craft-libs#778, #926, #927).
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "8bd1412eaa7c0b58f3f9c401495d35fe12d6d85e" }
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
# WMF, EMF and EMF+ reader (craft-libs#778).
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "6d620e971e820b517b11a99cad040ebac670e1e2" }
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "e2dc681a3" }
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "e2dc681a3" }
craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "e2dc681a3" }
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "e2dc681a3" }
craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "e2dc681a3" }
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", features = ["egui"] }
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"] }
# internal
vectorcraft-geom = { path = "crates/geom" }
vectorcraft-color = { path = "crates/color" }
@@ -97,10 +99,12 @@ wat = "1.228"
# Without `text` (glyph runs, through glifo and a second skrifa): the renderer draws the outlines
# vectorcraft-text gives it. The other default features stay.
vello_cpu = { version = "0.2", default-features = false, features = ["std", "png", "u8_pipeline", "f32_pipeline"] }
# The image crate still decodes and encodes for the readers not yet moved to craft-image-codecs
# (File › Open's raster path, PDF and SVG images, the renderer's image paint, DIBs). Its format
# features stay until the last of those moves, so no file that opens today stops opening.
image = { version = "0.25", default-features = false, features = ["png", "jpeg", "webp", "gif", "tiff", "bmp", "tga"] }
# Without `text` and the system fonts (fontdb, harfrust and skrifa, at other versions than ours):
# SVG import reads `<text>` from the XML itself and never gives usvg a font. A test of the SVG
# crate turns `text` on.
# SVG import reads `<text>` from the XML itself and never gives usvg a font.
usvg = { version = "0.48", default-features = false, features = ["svgz"] }
# Without `simple-text` (its text shaping, the only user of rustybuzz and ttf-parser, which are
# unmaintained, #1730): the PDF writer places glyphs itself. A test of the PDF crate turns it on.
@@ -112,18 +116,9 @@ flate2 = { version = "1", default-features = false, features = ["rust_backend"]
rustix = { version = "1.1", default-features = false }
# Zstandard decoder (pure Rust, builds for wasm32 too): the editing copy an EPS carries of its art.
ruzstd = { version = "0.9.1", default-features = false, features = ["std"] }
# CCITT Group 3 and Group 4 decoder (ITU-T T.4 and T.6): EPS images read through
# `CCITTFaxDecode`. The PDF reader's hayro-syntax uses the same version.
hayro-ccitt = "0.3"
# Substring search for the EPS reader's PostScript `search`.
memchr = "2"
# The WHATWG Encoding Standard's legacy encodings: names in legacy .ai files read in the code page
# the user picks (Mac OS Roman, Korean, Japanese, Chinese).
encoding_rs = "0.8.42"
jpeg-encoder = { version = "0.6", default-features = false, features = ["std"] }
gif = { version = "0.14", default-features = false, features = ["std", "raii_no_panic"] }
# CMYK image samples (vectorcraft-doc's cmyk module): the image crate's own TIFF and JPEG
# decoders, read directly (the image crate converts CMYK to RGB).
# vectorcraft-doc's CMYK TIFF reader and writer (src/cmyk.rs) still use `tiff`. `zune-jpeg` and
# `hayro-ccitt` are only the references tests compare craft-image-codecs' CMYK JPEG inks and
# craft-stream-codecs' Group 3 rows with (vectorcraft-doc's and vectorcraft-engine's dev-dependencies).
tiff = "0.11"
zune-jpeg = "0.5"
# JPEG XL decoder (pure Rust, MIT OR Apache-2.0): File › Open and Place read `.jxl` images. It is
@@ -136,6 +131,13 @@ jxl-grid = "0.6.2"
# Tests: a lossless JPEG XL encoder (pure Rust, MIT OR Apache-2.0 OR Zlib) for the `.jxl` test files.
zune-jpegxl = { version = "0.5.2", default-features = false, features = ["std"] }
zune-core = "0.5"
hayro-ccitt = "0.3"
jpeg-encoder = { version = "0.6", default-features = false, features = ["std"] }
# Substring search for the EPS reader's PostScript `search`.
memchr = "2"
# The WHATWG Encoding Standard's legacy encodings: names in legacy .ai files read in the code page
# the user picks (Mac OS Roman, Korean, Japanese, Chinese).
encoding_rs = "0.8.42"
# ui
egui = "0.37"
@@ -179,13 +181,13 @@ lto = "thin"
codegen-units = 1
[patch.crates-io]
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" }
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" }
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" }
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" }
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" }
krilla = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" }
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "481f66d287b2a06845f3667a19daf35f0fe958ed" }
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" }
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" }
+122
View File
@@ -146,3 +146,125 @@ Indic hyphenation patterns (crates/text/patterns/):
Copyright (C) 2016 Santhosh Thottingal, used under the MIT license option.
Original copyright and full license notices are preserved in each hyph-*.tex file.
Source: hyphenation/tex-hyphen, commit 5684c0f51c0b81133db2efbe60a408b4155a3ff5.
JPEG encoder dependency notices
jpeg-encoder 0.6.1, https://crates.io/crates/jpeg-encoder/0.6.1
Licensed under (MIT OR Apache-2.0) AND IJG. The MIT option and the IJG and SIMD
notices are reproduced below. Original license texts and provenance hashes are
retained in licenses/jpeg-encoder-0.6.1/.
--- jpeg-encoder 0.6.1: LICENSE-MIT ---
Copyright (c) 2021 Volker Ströbel <volkerstroebel@mysurdity.de>
Permission is hereby granted, free of charge, to any
person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the
Software without restriction, including without
limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice
shall be included in all copies or substantial portions
of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
--- jpeg-encoder 0.6.1: IJG-NOTICE.txt ---
/*
* Ported from mozjpeg to rust
*
* This file was part of the Independent JPEG Group's software:
* Copyright (C) 1991-1996, Thomas G. Lane.
* libjpeg-turbo Modifications:
* Copyright (C) 2015, 2020, D. R. Commander.
*
* Conditions of distribution and use:
* In plain English:
*
* 1. We don't promise that this software works. (But if you find any bugs,
* please let us know!)
* 2. You can use this software for whatever you want. You don't have to pay us.
* 3. You may not pretend that you wrote this software. If you use it in a
* program, you must acknowledge somewhere in your documentation that
* you've used the IJG code.
*
* In legalese:
*
* The authors make NO WARRANTY or representation, either express or implied,
* with respect to this software, its quality, accuracy, merchantability, or
* fitness for a particular purpose. This software is provided "AS IS", and you,
* its user, assume the entire risk as to its quality and accuracy.
*
* This software is copyright (C) 1991-2020, Thomas G. Lane, Guido Vollbeding.
* All Rights Reserved except as specified below.
*
* Permission is hereby granted to use, copy, modify, and distribute this
* software (or portions thereof) for any purpose, without fee, subject to these
* conditions:
* (1) If any part of the source code for this software is distributed, then this
* README file must be included, with this copyright and no-warranty notice
* unaltered; and any additions, deletions, or changes to the original files
* must be clearly indicated in accompanying documentation.
* (2) If only executable code is distributed, then the accompanying
* documentation must state that "this software is based in part on the work of
* the Independent JPEG Group".
* (3) Permission for use of this software is granted only if the user accepts
* full responsibility for any undesirable consequences; the authors accept
* NO LIABILITY for damages of any kind.
*
* These conditions apply to any software derived from or based on the IJG code,
* not just to the unmodified library. If you use our work, you ought to
* acknowledge us.
*
* Permission is NOT granted for the use of any IJG author's name or company name
* in advertising or publicity relating to this software or products derived from
* it. This software may be referred to only as "the Independent JPEG Group's
* software".
*
* We specifically permit and encourage the use of this software as the basis of
* commercial products, provided that all warranty or liability claims are
* assumed by the product vendor.
*
* This file contains a slower but more accurate integer implementation of the
* forward DCT (Discrete Cosine Transform).
*
* A 2-D DCT can be done by 1-D DCT on each row followed by 1-D DCT
* on each column. Direct algorithms are also available, but they are
* much more complex and seem not to be any faster when reduced to code.
*
* This implementation is based on an algorithm described in
* C. Loeffler, A. Ligtenberg and G. Moschytz, "Practical Fast 1-D DCT
* Algorithms with 11 Multiplications", Proc. Int'l. Conf. on Acoustics,
* Speech, and Signal Processing 1989 (ICASSP '89), pp. 988-991.
* The primary algorithm described there uses 11 multiplies and 29 adds.
* We use their alternate method with 12 multiplies and 32 adds.
* The advantage of this method is that no data path contains more than one
* multiplication; this allows a very simple and accurate implementation in
* scaled fixed-point arithmetic, with a minimal number of shifts.
*/
--- jpeg-encoder 0.6.1: SIMD-NOTICE.txt ---
/*
* Ported from mozjpeg / jfdctint-avx2.asm to rust
* Copyright 2009 Pierre Ossman <ossman@cendio.se> for Cendio AB
* Copyright (C) 2009, 2016, 2018, 2020, D. R. Commander.
*
* Based on the x86 SIMD extension for IJG JPEG library
* Copyright (C) 1999-2006, MIYASAKA Masaru.
*/
+4
View File
@@ -131,9 +131,11 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
- 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-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-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.
@@ -146,6 +148,8 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
- 2026-11-01: New Symbols from Layers joins the Document Tools add-on (Object › Plug-ins › Document Tools): one symbol of each top-level layer's art (the layers highlighted in the Layers panel when two or more are, else every layer), named after the layer, made as New Symbol makes one; Convert Layers to Symbols also puts an instance of each in place of its layer's art. Empty layers are skipped and reported; one undo step. A VectorCraft addition: headline numbers unchanged.
- 2026-11-01: Document Tools, a built-in add-on (Object › Plug-ins › Document Tools), starts with Save a Timestamped Copy: a copy of the document named `<name>_YYYY-MM-DD_HH-MM` (UTC; `-2`, `-3`… when that name is taken) goes next to it, or into a folder picked for a document never saved, written as File › Save a Copy writes it, so the document keeps its path, title and modified state. Off on the web, which has no clock. A VectorCraft addition: headline numbers unchanged.
- 2026-11-01: Divide into Dashes joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the selected paths, or only their direct-selected segments, are cut into separate open paths of a dash length measured along the curve, with an optional gap (left empty, or kept as pieces), each keeping the path's appearance; Fit to Corners and Ends stretches or squeezes the lengths so every run starts and ends on a dash. A dialog with Preview, one undo step, at most 100000 pieces. A VectorCraft addition: headline numbers unchanged.
- 2026-11-15: Common Tangents in the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the straight lines that touch two selected convex closed paths (ellipses at any rotation and scale, or convex Bézier paths) without crossing either are added as open paths with the current stroke: external, internal or all, and the line joining the centers if asked; a path inside the other has none unless the two touch, and a message says why; a dialog with Preview, one undo step (`addon.pathtools.commonTangents`, #7845). A VectorCraft addition: headline numbers unchanged.
- 2026-11-15: With Smart Guides and Snap to Tangent on, a Line Segment drag pressed on one convex curved path and dragged near another lands on a common tangent of the two: both ends move to where the line touches the paths, each labeled "tangent" (#7845). A VectorCraft addition: headline numbers unchanged.
- 2026-11-03: Text Tweaker, the first tool of the Type Tools add-on (Object › Plug-ins › Type Tools): one character attribute (size, baseline shift, rotation, horizontal or vertical scale, tracking, leading or stroke weight) goes letter by letter from a start value to an end value along a straight ramp, an ease, a bow, a spike or at random with a seed, set as the Character panel sets it, while the text stays live; a dialog with Preview, one undo step (`addon.type.textTweaker`, #4924). A VectorCraft addition: headline numbers unchanged.
- 2026-11-01: Group Overlapping Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects whose visual bounds overlap or touch, chains included, go into one group each, within their own layer or group, at the stacking place of their frontmost member; objects that overlap nothing stay as they are. One undo step, a sweep along x so thousands of loose pieces group quickly (at most 20000 objects). A VectorCraft addition: headline numbers unchanged.
- 2026-10-31: Export for Screens works as the reference app's dialog: Artboards and Assets tabs with a grid or list of thumbnails, Clear Selection and Prefix, Create Sub-folders by Scale or Format (on by default), Export PDFs As Single File (the chosen artboards as one PDF's pages, `pdfs: "single"`) or Multiple Files, iOS and Android rows, format presets in a ☰ menu, and a count of the files the export writes (#4895). About 55 community PRs and fixes landed the same day: Find Font, Replace Font, Outline Stroke and Expand leave hidden and locked art alone (with a warning); DXF export writes LINE and ELLIPSE entities and outlines only the strokes a CAD line can't draw; Blob Brush Angle and Roundness; Shift-constrained Perspective Selection; Grid Repeat Options Preview; a gradient mesh from a file budgeted at about a million quads; width-profile strokes keep their shape zoomed out; `.ai`/EPS import fidelity (area type, envelopes, transparency in dictionaries, character styles); PDF import finds hyphenated and CMap-suffixed font names; Windows renders follow the process's core affinity; Enter or Escape in a floating panel's field no longer reaches the canvas (#4803); Properties shows Blend Options for any selected blend (#4817); Artwork Cleanup finds doubled type (#4835) and joins stacked lines into one object (Join Point Text, #4826). Headline numbers unchanged.
+1 -1
View File
@@ -20,4 +20,4 @@ craft-affinity = { workspace = true }
proptest = { workspace = true }
# The tests build containers and decode previews.
crc32fast = { workspace = true }
image = { workspace = true }
craft-image-codecs = { workspace = true }
+2 -2
View File
@@ -50,8 +50,8 @@ fn source_backed_tiles_retain_the_embedded_jpeg_pixels() {
assert_eq!((image.width, image.height), (400, 300));
assert_eq!(image.transform, Affine::IDENTITY);
let Pixels::Rgba8(pixels) = &image.pixels else { panic!("expected retained level-zero pixels") };
let expected = image::load_from_memory(&source(&bytes)).unwrap().into_rgba8();
assert_eq!(pixels.as_slice(), expected.as_raw());
let expected = craft_image_codecs::decode(&source(&bytes)).unwrap().to_rgba8();
assert_eq!(pixels.as_slice(), expected.as_slice());
assert!(pixels.as_chunks::<4>().0.iter().all(|p| p[3] == 255));
assert!(pixels.as_chunks::<4>().0.iter().any(|p| p[0] != p[1]));
}
+1
View File
@@ -19,6 +19,7 @@ vectorcraft-pathops = { workspace = true }
vectorcraft-text = { workspace = true }
kurbo = { workspace = true }
image = { workspace = true }
craft-image-codecs = { workspace = true }
[dev-dependencies]
serde_json = { workspace = true }
+20 -19
View File
@@ -5,7 +5,6 @@
//! filled outlines where the look needs them.
use std::collections::HashMap;
use std::io::Cursor;
use kurbo::PathEl;
use vectorcraft_color::Paint;
@@ -1403,35 +1402,37 @@ impl<'a> Scene<'a> {
/// Image `im` as a file in the chosen format, and its size in pixels.
fn encode_image(&self, im: &ImageObject) -> Result<(DxfImage, (u32, u32)), String> {
use craft_image_codecs::{ChannelLayout, EncodeOptions, Format, Image as CodecImage, SampleType};
let blob = self.doc.image_blob(im).filter(|b| !b.bytes.is_empty()).ok_or_else(|| "an image has no pixels and was left out".to_string())?;
// The pixels it converts to (RGBA, 4 bytes each) are read from its header before decoding.
let (w, h) = image::ImageReader::new(Cursor::new(blob.bytes.as_slice()))
.with_guessed_format()
.ok()
.and_then(|r| r.into_dimensions().ok())
.ok_or_else(|| UNDECODED.to_string())?;
let (w, h) = vectorcraft_doc::header_size(&blob.bytes).ok_or_else(|| UNDECODED.to_string())?;
if u64::from(w) * u64::from(h) > MAX_IMAGE_PIXELS {
return Err("an image is too large for DXF and was left out".to_string());
}
let img = image::load_from_memory(&blob.bytes).map_err(|_| UNDECODED.to_string())?;
let size = (img.width(), img.height());
let mut bytes = vec![];
let written = match self.o.raster {
RasterFormat::Png => img.to_rgba8().write_to(&mut Cursor::new(&mut bytes), image::ImageFormat::Png),
let decoded = craft_image_codecs::decode(&blob.bytes).map_err(|_| UNDECODED.to_string())?;
let size = decoded.dimensions();
let mut rgba = decoded.to_rgba8();
let bytes = match self.o.raster {
RasterFormat::Png => {
let img = CodecImage::from_raw(size.0, size.1, ChannelLayout::Rgba, SampleType::U8, rgba)
.map_err(|e| format!("an image could not be written: {e}"))?;
craft_image_codecs::encode(&img, Format::Png, &EncodeOptions::default())
}
RasterFormat::Jpeg => {
// No alpha in JPEG: transparent pixels over white.
let mut rgba = img.to_rgba8();
for p in rgba.pixels_mut() {
let mut rgb = Vec::with_capacity(rgba.len() / 4 * 3);
for p in rgba.as_chunks_mut::<4>().0 {
let a = u32::from(p[3]);
for c in 0..3 {
p[c] = ((u32::from(p[c]) * a + 255 * (255 - a)) / 255) as u8;
for c in &p[..3] {
rgb.push(((u32::from(*c) * a + 255 * (255 - a)) / 255) as u8);
}
}
let rgb = image::DynamicImage::ImageRgba8(rgba).to_rgb8();
rgb.write_with_encoder(image::codecs::jpeg::JpegEncoder::new_with_quality(&mut bytes, 90))
let img = CodecImage::from_raw(size.0, size.1, ChannelLayout::Rgb, SampleType::U8, rgb)
.map_err(|e| format!("an image could not be written: {e}"))?;
craft_image_codecs::encode(&img, Format::Jpeg, &EncodeOptions { jpeg_quality: 90, ..EncodeOptions::default() })
}
};
written.map_err(|e| format!("an image could not be written: {e}"))?;
}
.map_err(|e| format!("an image could not be written: {e}"))?;
Ok((DxfImage { name: format!("{}.{}", blob.content_key(), self.o.raster.extension()), bytes }, size))
}
}
+26 -4
View File
@@ -852,8 +852,19 @@ fn the_cnc_preset_writes_version_2000_in_millimeters_with_type_as_paths_and_stro
/// A 4 × 2 px PNG placed at (10, 20) under key `raster-1`, and before it in paint order
/// `fill`'s rectangle.
fn image_and_fill_doc(fill: Paint) -> Document {
let mut png = vec![];
image::RgbaImage::from_pixel(4, 2, image::Rgba([0, 0, 255, 255])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
let png = craft_image_codecs::encode(
&craft_image_codecs::Image::from_raw(
4,
2,
craft_image_codecs::ChannelLayout::Rgba,
craft_image_codecs::SampleType::U8,
[0u8, 0, 255, 255].repeat(8),
)
.unwrap(),
craft_image_codecs::Format::Png,
&craft_image_codecs::EncodeOptions::default(),
)
.unwrap();
let mut d = doc_with(|d| {
let im = ImageObject {
key: "raster-1".into(),
@@ -1312,8 +1323,19 @@ fn a_font_height_reference_is_written_as_the_size_drawn() {
#[test]
fn images_link_png_or_jpeg_files() {
let mut png = vec![];
image::RgbaImage::from_pixel(4, 2, image::Rgba([255, 0, 0, 128])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
let png = craft_image_codecs::encode(
&craft_image_codecs::Image::from_raw(
4,
2,
craft_image_codecs::ChannelLayout::Rgba,
craft_image_codecs::SampleType::U8,
[255u8, 0, 0, 128].repeat(8),
)
.unwrap(),
craft_image_codecs::Format::Png,
&craft_image_codecs::EncodeOptions::default(),
)
.unwrap();
let mut d = doc_with(|d| {
let im = ImageObject {
key: "raster-1".into(),
+6 -2
View File
@@ -17,15 +17,19 @@ vectorcraft-geom = { workspace = true }
vectorcraft-color = { workspace = true }
kurbo = { workspace = true }
image = { workspace = true }
# Image headers (PNG and JPEG sizes, `pixels::header_size`) and CMYK JPEG inks (`cmyk`).
craft-image-codecs = { workspace = true }
tiff = { workspace = true }
# 1-bit TIFFs compressed with CCITT Group 3 (Compression 2 and 3).
hayro-ccitt = { workspace = true }
zune-jpeg = { workspace = true }
craft-stream-codecs = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
thiserror = { workspace = true }
chrono = { workspace = true }
[dev-dependencies]
flate2 = { workspace = true }
# The CMYK JPEG reader `cmyk` had before craft-image-codecs, kept as the reference its inks match.
zune-jpeg = { workspace = true }
jpeg-encoder = { workspace = true }
proptest = { workspace = true }
+148 -108
View File
@@ -9,10 +9,6 @@
use std::io::Cursor;
use std::sync::Arc;
use zune_jpeg::zune_core::bytestream::ZCursor;
use zune_jpeg::zune_core::colorspace::ColorSpace;
use zune_jpeg::zune_core::options::DecoderOptions;
use crate::ImageBlob;
/// Most pixels a CMYK image is decoded with (256 MB of samples): larger ones decode as RGB.
@@ -44,12 +40,7 @@ fn pixels(width: u32, height: u32) -> Option<u64> {
/// The number of colour components of JPEG `bytes` (its frame header); `None` when they aren't a
/// JPEG.
pub fn jpeg_components(bytes: &[u8]) -> Option<usize> {
if !bytes.starts_with(&[0xFF, 0xD8]) {
return None;
}
let mut d = zune_jpeg::JpegDecoder::new_with_options(ZCursor::new(bytes), DecoderOptions::default());
d.decode_headers().ok()?;
Some(d.info()?.components as usize)
craft_image_codecs::jpeg_inks::jpeg_components(bytes)
}
fn is_tiff(bytes: &[u8]) -> bool {
@@ -645,9 +636,7 @@ pub fn tiff_icc_profile(bytes: &[u8]) -> Option<Vec<u8>> {
/// The ICC profile of a JPEG, put together from all its numbered `ICC_PROFILE` APP2 segments;
/// `None` without one.
fn jpeg_icc(bytes: &[u8]) -> Option<Vec<u8>> {
let mut d = zune_jpeg::JpegDecoder::new_with_options(ZCursor::new(bytes), DecoderOptions::default());
d.decode_headers().ok()?;
d.icc_profile().filter(|icc| !icc.is_empty())
craft_image_codecs::jpeg_inks::jpeg_icc_profile(bytes)
}
/// The bytes after an `ICC_PROFILE` APP2 segment's length: its name, then the segment's number and
@@ -851,10 +840,7 @@ impl ImageBlob {
pub fn header_size(&self) -> Option<(u32, u32)> {
let bytes = self.bytes.as_slice();
if bytes.starts_with(&[0xFF, 0xD8]) {
let mut d = zune_jpeg::JpegDecoder::new_with_options(ZCursor::new(bytes), DecoderOptions::default());
d.decode_headers().ok()?;
let (w, h) = d.dimensions()?;
return Some((u32::try_from(w).ok()?, u32::try_from(h).ok()?));
return craft_image_codecs::jpeg_inks::jpeg_dimensions(bytes);
}
tiff(bytes).and_then(|(_, mut d)| d.dimensions().ok())
}
@@ -932,30 +918,10 @@ fn sample_inks(inks: &Inks, x: f64, y: f64, size: u32) -> Option<[u8; 4]> {
/// The ink amounts of a four-component JPEG (its samples inverted back; YCCK converted to CMYK
/// first, as JPEG readers do).
fn jpeg_inks(bytes: &[u8]) -> Option<Inks> {
let mut d = zune_jpeg::JpegDecoder::new_with_options(ZCursor::new(bytes), DecoderOptions::default());
d.decode_headers().ok()?;
let space = d.input_colorspace()?;
if d.info()?.components != 4 || !matches!(space, ColorSpace::CMYK | ColorSpace::YCCK) {
return None;
}
let (w, h) = d.dimensions()?;
let (w, h) = (u32::try_from(w).ok()?, u32::try_from(h).ok()?);
pixels(w, h)?;
d.set_options(DecoderOptions::default().jpeg_set_out_colorspace(space));
let mut data = d.decode().ok()?;
for p in data.as_chunks_mut::<4>().0 {
if space == ColorSpace::YCCK {
let [y, cb, cr] = [p[0], p[1], p[2]].map(f32::from);
// libjpeg's YCCK → CMYK: the complement of the YCbCr colour's RGB.
p[0] = (434.456 - y - 1.402 * cr).clamp(0.0, 255.0) as u8;
p[1] = (119.541 - y + 0.344 * cb + 0.714 * cr).clamp(0.0, 255.0) as u8;
p[2] = (481.816 - y - 1.772 * cb).clamp(0.0, 255.0) as u8;
}
for v in p.iter_mut() {
*v = 255 - *v;
}
}
Inks::new(w, h, data)
let limits = craft_image_codecs::Limits { max_pixels: MAX_CMYK_PIXELS, ..craft_image_codecs::Limits::default() };
let image = craft_image_codecs::jpeg_inks::decode_jpeg_inks(bytes, &limits).ok()?;
let (w, h) = image.dimensions();
Inks::new(w, h, image.into_data())
}
/// The ink amounts of a CMYK TIFF (16-bit samples to 8 bits), its inks stored together or one plane
@@ -1107,9 +1073,20 @@ pub enum Group3Error {
TooLarge { w: u32, h: u32 },
/// A strip or tile ends before its last row or can't be decoded (it holds a code the decoder
/// doesn't read, such as T.4's uncompressed mode, or a row of the wrong width), or a tile is
/// larger than [`crate::MAX_RASTER_ALLOC`] allows as RGBA.
#[error("could not decode image: {0}")]
Damaged(hayro_ccitt::DecodeError),
/// larger than [`crate::MAX_RASTER_ALLOC`] allows as RGBA, or is wider than
/// [`craft_stream_codecs::MAX_CCITT_COLUMNS`].
#[error("could not decode image: {}", damage(*.0))]
Damaged(craft_stream_codecs::CcittErrorKind),
}
/// What went wrong in a Group 3 strip or tile, as [`Group3Error::Damaged`] says it.
fn damage(kind: craft_stream_codecs::CcittErrorKind) -> &'static str {
use craft_stream_codecs::CcittErrorKind as K;
match kind {
K::UnexpectedEof => "unexpected end of input",
K::Overflow => "arithmetic overflow in position calculation",
K::InvalidData => "invalid CCITT code sequence",
}
}
/// The pixels of a 1-bit TIFF compressed with CCITT Group 3, which the image decoder doesn't read,
@@ -1124,7 +1101,7 @@ pub enum Group3Error {
/// an error when the pixels would take more than [`crate::MAX_RASTER_ALLOC`] as RGBA, a tile is
/// larger than that allowance, or a strip or tile can't be decoded or ends before its last row.
pub fn group3_tiff_rgba(bytes: &[u8]) -> Option<Result<image::RgbaImage, Group3Error>> {
use hayro_ccitt::{DecodeError, DecodeSettings, DecoderContext, EncodingMode};
use craft_stream_codecs::{CcittErrorKind as DecodeError, CcittParams, decode_ccitt_raw};
use tiff::tags::Tag;
let (kind, mut d) = tiff(bytes)?;
let compression = d.find_tag_unsigned::<u16>(Tag::Compression).ok().flatten()?;
@@ -1143,12 +1120,8 @@ pub fn group3_tiff_rgba(bytes: &[u8]) -> Option<Result<image::RgbaImage, Group3E
}
let t4_options = d.find_tag_unsigned::<u32>(Tag::Unknown(292)).ok().flatten().unwrap_or(0);
let lsb_first = d.find_tag_unsigned::<u16>(Tag::FillOrder).ok().flatten() == Some(2);
let encoding = if compression == 3 && t4_options & 1 != 0 {
// Each row's tag bit says how it is coded.
EncodingMode::Group3_2D { k: 2 }
} else {
EncodingMode::Group3_1D
};
// Each row's tag bit says how it is coded (K above 0), or every row is one-dimensional (K 0).
let k = if compression == 3 && t4_options & 1 != 0 { 2 } else { 0 };
// The width and height of each strip or tile, and the tags of their offsets and byte counts.
let tiled = d.get_chunk_type() == tiff::decoder::ChunkType::Tile;
let (cw, ch, offsets, counts) = if tiled {
@@ -1182,76 +1155,54 @@ pub fn group3_tiff_rgba(bytes: &[u8]) -> Option<Result<image::RgbaImage, Group3E
budget -= len;
let data = bytes.get(start..start + len)?;
let data: std::borrow::Cow<[u8]> = if lsb_first { data.iter().map(|b| b.reverse_bits()).collect() } else { data.into() };
let settings = DecodeSettings {
columns: cw,
// A tile is coded whole; the last strip only has the image's remaining rows.
rows: if tiled { ch } else { ch.min(h - y0) },
end_of_block: compression == 3,
// A tile is coded whole; the last strip only has the image's remaining rows.
let rows = if tiled { ch } else { ch.min(h - y0) };
let params = CcittParams {
k,
columns: i64::from(cw),
rows: i64::from(rows),
end_of_line: compression == 3,
rows_are_byte_aligned: compression == 2,
encoding,
invert_black: false,
encoded_byte_align: compression == 2,
end_of_block: compression == 3,
// 1 bits are black runs, 0 bits white ones.
black_is_1: true,
};
let mut rows = Rows { out: &mut gray, width: w, height: h, x0, y0, x: 0, y: 0, zero };
if let Err(e) = hayro_ccitt::decode(&data, &mut rows, &mut DecoderContext::new(settings)) {
let Ok(out) = decode_ccitt_raw(&data, &params, rows) else {
// Wider than the decoder reads.
return damaged(DecodeError::Overflow);
};
if let Some(e) = out.error {
return damaged(e);
}
// The data ended, or six EOL codes came, before the strip's or tile's last row.
if rows.y < settings.rows {
if out.rows_decoded < rows {
return damaged(DecodeError::UnexpectedEof);
}
put_rows(&mut gray, (w, h), (x0, y0), cw, &out.data, zero);
}
let gray = image::GrayImage::from_raw(w, h, gray)?;
Some(Ok(image::DynamicImage::ImageLuma8(gray).to_rgba8()))
}
/// Where a strip or tile of a Group 3 TIFF ([`group3_tiff_rgba`]) puts its decoded pixels: `out`
/// holds the image's levels row by row, `width` × `height`, and the strip or tile starts at (`x0`,
/// `y0`). Pixels past the image's right or bottom edge (a tile's padding) are dropped.
struct Rows<'a> {
out: &'a mut [u8],
width: u32,
height: u32,
x0: u32,
y0: u32,
/// The next pixel in the strip or tile.
x: u64,
y: u32,
/// The level of a white run.
zero: u8,
}
impl Rows<'_> {
/// The next `n` pixels of the row, a white run's or a black run's.
fn run(&mut self, white: bool, n: u64) {
let level = if white { self.zero } else { u8::MAX - self.zero };
let row = u64::from(self.y0) + u64::from(self.y);
let left = u64::from(self.x0) + self.x;
let right = left.saturating_add(n).min(u64::from(self.width));
if row < u64::from(self.height) && left < right {
let at = row * u64::from(self.width);
if let (Ok(a), Ok(b)) = (usize::try_from(at + left), usize::try_from(at + right))
&& let Some(px) = self.out.get_mut(a..b)
{
px.fill(level);
}
/// The decoded rows `packed` of a strip or tile of a Group 3 TIFF ([`group3_tiff_rgba`]), `columns`
/// wide, one bit a pixel (1 a black run's), put into `out`, the image's levels row by row, `size`
/// (width, height), from (`x0`, `y0`): a 0 bit as `zero` (the level of a white run), a 1 bit as the
/// other level. Pixels past the image's right or bottom edge (a tile's padding) are dropped.
fn put_rows(out: &mut [u8], size: (u32, u32), (x0, y0): (u32, u32), columns: u32, packed: &[u8], zero: u8) {
let (width, height) = (size.0 as usize, size.1 as usize);
let (x0, y0, columns) = (x0 as usize, y0 as usize, columns as usize);
let stride = columns.div_ceil(8);
if stride == 0 {
return;
}
let across = columns.min(width.saturating_sub(x0));
for (y, row) in packed.chunks(stride).enumerate() {
let Some(at) = (y0 + y < height).then(|| (y0 + y) * width + x0) else { break };
let Some(px) = out.get_mut(at..at + across) else { break };
for (x, p) in px.iter_mut().enumerate() {
let black = row.get(x / 8).is_some_and(|b| b & (0x80 >> (x % 8)) != 0);
*p = if black { u8::MAX - zero } else { zero };
}
self.x = self.x.saturating_add(n);
}
}
impl hayro_ccitt::Decoder for Rows<'_> {
fn push_pixel(&mut self, white: bool) {
self.run(white, 1);
}
fn push_pixel_chunk(&mut self, white: bool, chunk_count: u32) {
self.run(white, u64::from(chunk_count) * 8);
}
fn next_line(&mut self) {
self.y = self.y.saturating_add(1);
self.x = 0;
}
}
@@ -2209,4 +2160,93 @@ mod tests {
assert_eq!(Inks::new(0, 2, vec![]), None, "empty");
assert_eq!(Inks::new(1 << 14, 1 << 13, vec![]), None, "too large");
}
/// The CMYK JPEG reader before craft-image-codecs read the inks (zune-jpeg, every sample
/// inverted, libjpeg's truncating YCCK conversion), the reference [`jpeg_inks`] matches.
fn zune_inks(bytes: &[u8]) -> Option<Inks> {
use zune_jpeg::zune_core::{bytestream::ZCursor, colorspace::ColorSpace, options::DecoderOptions};
let mut d = zune_jpeg::JpegDecoder::new_with_options(ZCursor::new(bytes), DecoderOptions::default());
d.decode_headers().ok()?;
let space = d.input_colorspace()?;
if d.info()?.components != 4 || !matches!(space, ColorSpace::CMYK | ColorSpace::YCCK) {
return None;
}
let (w, h) = d.dimensions()?;
let (w, h) = (u32::try_from(w).ok()?, u32::try_from(h).ok()?);
pixels(w, h)?;
d.set_options(DecoderOptions::default().jpeg_set_out_colorspace(space));
let mut data = d.decode().ok()?;
for p in data.as_chunks_mut::<4>().0 {
if space == ColorSpace::YCCK {
let [y, cb, cr] = [p[0], p[1], p[2]].map(f32::from);
p[0] = (434.456 - y - 1.402 * cr).clamp(0.0, 255.0) as u8;
p[1] = (119.541 - y + 0.344 * cb + 0.714 * cr).clamp(0.0, 255.0) as u8;
p[2] = (481.816 - y - 1.772 * cb).clamp(0.0, 255.0) as u8;
}
for v in p.iter_mut() {
*v = 255 - *v;
}
}
Inks::new(w, h, data)
}
/// CMYK and YCCK JPEGs of many sizes, samplings and qualities, baseline and progressive, with
/// and without Adobe's marker and an ICC profile, read the inks, size, component count and
/// profile the zune-jpeg reader read; so do gray and RGB JPEGs (no inks) and cut-off files.
/// The frames it panicked on (progressive 4:2:0 CMYK, whose C, M and Y `jpeg-encoder` writes at
/// 1×1 and K at 2×2) read as no inks.
#[test]
fn cmyk_jpegs_read_as_the_zune_reader_read_them() {
use jpeg_encoder::{ColorType, Encoder, SamplingFactor};
let reference_size = |bytes: &[u8]| {
use zune_jpeg::zune_core::{bytestream::ZCursor, options::DecoderOptions};
let mut d = zune_jpeg::JpegDecoder::new_with_options(ZCursor::new(bytes), DecoderOptions::default());
d.decode_headers().ok()?;
let (w, h) = d.dimensions()?;
Some((u32::try_from(w).ok()?, u32::try_from(h).ok()?, usize::from(d.info()?.components), d.icc_profile().filter(|i| !i.is_empty())))
};
let (mut files, mut read, mut panicked) = (0, 0, 0);
for (i, (w, h)) in [(1u16, 1u16), (7, 3), (16, 16), (33, 31), (100, 77)].into_iter().enumerate() {
let n = usize::from(w) * usize::from(h);
let px: Vec<u8> = (0..n * 4).map(|k| ((k * 2_654_435_761 + i * 97) >> 7) as u8).collect();
for ty in [ColorType::Cmyk, ColorType::CmykAsYcck, ColorType::Rgba, ColorType::Luma] {
for (q, sampling, progressive, icc) in [
(100, SamplingFactor::R_4_4_4, false, false),
(70, SamplingFactor::R_4_2_0, true, true),
(40, SamplingFactor::R_4_2_2, false, false),
] {
let mut out = Vec::new();
let mut e = Encoder::new(&mut out, q);
e.set_sampling_factor(sampling);
e.set_progressive(progressive);
if icc {
let mut icc = vec![4; 70_000];
icc[16..20].copy_from_slice(b"CMYK");
e.add_icc_profile(&icc).unwrap();
}
let samples = if ty == ColorType::Luma { &px[..n] } else { &px[..] };
e.encode(samples, w, h, ty).unwrap();
let cut = out[..out.len() * 2 / 3].to_vec();
for file in [out, cut] {
let b = ImageBlob::new("image/jpeg", file.clone());
// The zune-jpeg reader panicked on some subsampled CMYK frames; those
// read as no inks now.
let inks = std::panic::catch_unwind(|| zune_inks(&file)).unwrap_or_else(|_| {
panicked += 1;
None
});
read += usize::from(inks.is_some());
assert_eq!(b.cmyk(), inks, "{w}x{h} {ty:?} q{q}");
let r = reference_size(&file);
assert_eq!(b.header_size(), r.as_ref().map(|r| (r.0, r.1)));
assert_eq!(jpeg_components(&file), r.as_ref().map(|r| r.2));
assert_eq!(jpeg_icc(&file), r.and_then(|r| r.3));
files += 1;
}
}
}
}
assert_eq!(files, 5 * 4 * 3 * 2);
assert!(read > 20 && panicked > 0, "{read} read as inks, {panicked} panicked");
}
}
+96
View File
@@ -0,0 +1,96 @@
//! Images decoded through craft-image-codecs as the image crate gave them (#778): the renderer,
//! File › Open and Place, SVG import, and embedded and linked images read their pixels with
//! [`decode_image`] and [`decode_within`], and size them from their header with [`decoded_layout`].
/// Decoded pixels, as stored and as the image crate gave them, and the ICC profile the file embeds.
pub type DecodedImage = (image::DynamicImage, Option<Vec<u8>>);
/// `bytes` decoded as `format` within `allowance` bytes, the pixels as stored (not turned
/// upright) and as the image crate gave them ([`dynamic`]), with the ICC profile the file embeds.
/// The renderer, File › Open and Place, SVG import, and embedded and linked images read images
/// with it.
pub fn decode_image(format: craft_image_codecs::Format, bytes: &[u8], allowance: u64) -> Result<DecodedImage, craft_image_codecs::CodecError> {
let opts = craft_image_codecs::DecodeOptions {
limits: craft_image_codecs::Limits { max_width: u32::MAX, max_height: u32::MAX, max_pixels: u64::MAX, max_alloc: allowance },
keep_orientation: true,
};
let mut img = craft_image_codecs::decode_as_with(format, bytes, &opts)?;
let icc = img.icc.take();
let img = dynamic(img).ok_or_else(|| craft_image_codecs::CodecError::InvalidImage("the decoded samples don't fit the image".into()))?;
Ok((img, icc))
}
/// `bytes` decoded within `max` bytes, counted as the file's samples and as RGBA (#1717), the
/// pixels as stored and as the image crate gave them, with the ICC profile the file embeds.
/// Image blobs read their pixels with it. `Ok(None)` when they would take more than `max` as
/// samples or as RGBA (the header alone decides; the pixels are not read). `Err` when the bytes
/// aren't an image the decoder reads, including a file whose header fits the allowance but whose
/// pixels can't be decoded (a cut-short file, or one the decoder refuses as a decompression bomb).
pub fn decode_within(bytes: &[u8], max: u64) -> Result<Option<DecodedImage>, craft_image_codecs::CodecError> {
let format = craft_image_codecs::detect(bytes).ok_or(craft_image_codecs::CodecError::UnknownFormat)?;
let (w, h, per_pixel) =
decoded_layout(bytes, format).ok_or_else(|| craft_image_codecs::CodecError::InvalidImage("the image's size can't be read".into()))?;
let pixels = u64::from(w) * u64::from(h);
if pixels.saturating_mul(per_pixel) > max || pixels.saturating_mul(4) > max {
return Ok(None);
}
decode_image(format, bytes, max).map(Some)
}
/// A decoded image as the image crate's: 8- and 16-bit gray, gray and alpha, RGB and RGBA as they
/// are, 32-bit float RGB and RGBA as they are, anything else as 8-bit RGBA.
fn dynamic(img: craft_image_codecs::Image) -> Option<image::DynamicImage> {
use craft_image_codecs::{ChannelLayout as L, SampleType as S};
use image::{DynamicImage as D, ImageBuffer as B};
let (w, h) = img.dimensions();
Some(match (img.layout(), img.sample_type()) {
(L::Gray, S::U8) => D::ImageLuma8(B::from_raw(w, h, img.into_data())?),
(L::GrayA, S::U8) => D::ImageLumaA8(B::from_raw(w, h, img.into_data())?),
(L::Rgb, S::U8) => D::ImageRgb8(B::from_raw(w, h, img.into_data())?),
(L::Rgba, S::U8) => D::ImageRgba8(B::from_raw(w, h, img.into_data())?),
(layout @ (L::Gray | L::GrayA | L::Rgb | L::Rgba), S::U16) => {
let v = img.to_u16_samples()?;
match layout {
L::Gray => D::ImageLuma16(B::from_raw(w, h, v)?),
L::GrayA => D::ImageLumaA16(B::from_raw(w, h, v)?),
L::Rgb => D::ImageRgb16(B::from_raw(w, h, v)?),
_ => D::ImageRgba16(B::from_raw(w, h, v)?),
}
}
_ => D::ImageRgba8(B::from_raw(w, h, img.to_rgba8())?),
})
}
/// The image's size and the bytes a pixel of it takes decoded ([`decode_as`]), read from its
/// header: palettes as RGB (RGBA with a transparent entry; GIF frames always RGBA), bitmaps as 8-bit
/// gray, 16-bit samples as two bytes. A PNG whose header alone is there is read from its `IHDR`;
/// a format whose header says only its size (TGA, ICO and the like) counts RGBA.
pub fn decoded_layout(bytes: &[u8], format: craft_image_codecs::Format) -> Option<(u32, u32, u64)> {
use craft_image_codecs::{Format as F, RasterColorType as T};
if let Some(i) = craft_image_codecs::inspect_raster(bytes).ok().flatten() {
let deep = i.bits_per_sample > 8 && i.color_type != T::Indexed;
let channels = match i.color_type {
_ if format == F::Gif => 4,
T::Indexed => 3 + u64::from(i.transparent_index.is_some()),
T::Bitmap => 1,
_ => u64::from(i.channels.max(1)),
};
return Some((i.width, i.height, channels * if deep { 2 } else { 1 }));
}
if format != F::Png {
return crate::header_size(bytes).map(|(w, h)| (w, h, 4));
}
if bytes.get(12..16)? != b"IHDR" {
return None;
}
let be = |at: usize| Some(u32::from_be_bytes(bytes.get(at..at + 4)?.try_into().ok()?));
let (depth, color) = (*bytes.get(24)?, *bytes.get(25)?);
let channels: u64 = match color {
0 => 1,
2 | 3 => 3,
4 => 2,
6 => 4,
_ => return None,
};
Some((be(16)?, be(20)?, channels * if depth == 16 { 2 } else { 1 }))
}
+23
View File
@@ -491,6 +491,10 @@ pub struct GraphSpec {
pub first_column_in_front: bool,
#[serde(skip_serializing_if = "std::ops::Not::not")]
pub filled_lines: bool,
/// Graph Type › Line Width: how wide Draw Filled Lines draws a line, in points. `None` draws
/// [`DEFAULT_FILLED_LINE_WIDTH`]; see [`Self::filled_line_width`].
#[serde(skip_serializing_if = "Option::is_none")]
pub line_width: Option<f64>,
/// Graph Type › Add Drop Shadow (behind columns, bars, lines and pie wedges) and Add Legend Across Top (the
/// legend in rows above the plot instead of a column on its right).
#[serde(skip_serializing_if = "std::ops::Not::not")]
@@ -565,6 +569,24 @@ fn is_zero(n: &usize) -> bool {
*n == 0
}
/// Graph Type › Line Width: the width Draw Filled Lines draws a line at when the graph sets none, and the least and
/// greatest widths a graph takes, in points.
pub const DEFAULT_FILLED_LINE_WIDTH: f64 = 3.0;
pub const MIN_FILLED_LINE_WIDTH: f64 = 0.01;
pub const MAX_FILLED_LINE_WIDTH: f64 = 1000.0;
/// The weight of the black outline Draw Filled Lines draws around each band, in points.
pub const FILLED_LINE_OUTLINE_WIDTH: f64 = 0.25;
impl GraphSpec {
/// How wide Draw Filled Lines draws a line, in points: [`Self::line_width`], else [`DEFAULT_FILLED_LINE_WIDTH`]. A
/// width a file gives outside [`MIN_FILLED_LINE_WIDTH`] to [`MAX_FILLED_LINE_WIDTH`], or not finite, draws the
/// default.
pub fn filled_line_width(&self) -> f64 {
self.line_width.filter(|w| (MIN_FILLED_LINE_WIDTH..=MAX_FILLED_LINE_WIDTH).contains(w)).unwrap_or(DEFAULT_FILLED_LINE_WIDTH)
}
}
/// Edge-to-Edge Lines for a graph saved before the option existed: on, as it was drawn then.
fn edge_to_edge_before_the_option() -> bool {
true
@@ -704,6 +726,7 @@ impl Default for GraphSpec {
first_row_in_front: false,
first_column_in_front: false,
filled_lines: false,
line_width: None,
drop_shadow: false,
legend_across_top: false,
pie_legend_in_wedges: false,
+5 -3
View File
@@ -14,6 +14,7 @@ pub mod cmyk;
pub mod color_mask;
pub mod compound_shape;
pub mod corners;
pub mod decode;
pub mod depth;
pub mod dimension;
pub mod graph;
@@ -54,7 +55,7 @@ pub mod overprint;
pub mod pattern;
pub mod perspective;
mod pixels;
pub use pixels::{GraySource, MAX_RASTER_ALLOC, PixelPick};
pub use pixels::{GraySource, MAX_RASTER_ALLOC, PixelPick, header_size};
pub mod placed_document;
pub mod plugin_data;
pub mod ppi;
@@ -96,8 +97,9 @@ pub use compound_shape::ShapeMode;
pub use corners::LiveCorners;
pub use depth::{MAX_DEPTH, MAX_SYMBOL_NODES};
pub use graph::{
ColumnDesign, ColumnType, Fractions, GraphDesign, GraphKind, GraphSpec, LabelRows, LabelStyles, MAX_GRAPH_CATEGORIES, MAX_GRAPH_SERIES,
PiePosition, PieSort, SeriesPaint, TickLength, ValueAxisSide,
ColumnDesign, ColumnType, DEFAULT_FILLED_LINE_WIDTH, FILLED_LINE_OUTLINE_WIDTH, Fractions, GraphDesign, GraphKind, GraphSpec, LabelRows,
LabelStyles, MAX_FILLED_LINE_WIDTH, MAX_GRAPH_CATEGORIES, MAX_GRAPH_SERIES, MIN_FILLED_LINE_WIDTH, PiePosition, PieSort, SeriesPaint, TickLength,
ValueAxisSide,
};
pub use hit::{Hit, HitKind};
pub use links::{LinkInfo, PlacementOptions};
+47 -29
View File
@@ -145,9 +145,9 @@ impl ImageBlob {
/// This blob after its pixels are decoded once, within [`crate::MAX_RASTER_ALLOC`], to check
/// that they can be read; with `proxy`, it also gets the preview [`Self::with_proxy`] makes,
/// made from that decode. `None` when the pixels can't be read, as with a file cut short that
/// has a header but not all its pixels. An image whose pixels would take more than the
/// allowance as RGBA is not decoded, and one whose decode needs more than the allowance stops
/// decoding; either is returned as it is.
/// has a header but not all its pixels, or one the decoder refuses as a decompression bomb.
/// An image whose pixels would take more than the allowance as RGBA is not decoded and is
/// returned as it is.
pub fn checked_with_proxy(self, proxy: bool) -> Option<Self> {
self.checked_with_pixels(proxy).map(|(blob, _)| blob)
}
@@ -155,22 +155,12 @@ impl ImageBlob {
/// [`Self::checked_with_proxy`], with the pixels it decoded: `None` beside the blob when it
/// decoded none (an image past the allowance).
pub fn checked_with_pixels(mut self, proxy: bool) -> Option<(Self, Option<image::DynamicImage>)> {
let max = crate::MAX_RASTER_ALLOC;
let reader = || image::ImageReader::new(Cursor::new(self.bytes.as_slice())).with_guessed_format().ok();
let (w, h) = reader()?.into_dimensions().ok()?;
if u64::from(w) * u64::from(h) > max / 4 {
return Some((self, None));
}
let mut r = reader()?;
let mut limits = image::Limits::default();
limits.max_alloc = Some(max);
r.limits(limits);
let img = match r.decode() {
Ok(img) => img,
Err(image::ImageError::Limits(_)) => return Some((self, None)),
let img = match crate::decode::decode_within(&self.bytes, crate::MAX_RASTER_ALLOC) {
Ok(Some((img, _))) => img,
Ok(None) => return Some((self, None)),
Err(_) => return None,
};
if proxy && self.proxy.is_none() && w.max(h) > PROXY_SIZE {
if proxy && self.proxy.is_none() && img.width().max(img.height()) > PROXY_SIZE {
self.proxy = proxy_of(&img).map(Arc::new);
}
Some((self, Some(img)))
@@ -210,21 +200,16 @@ pub fn missing_placeholder() -> Option<Vec<u8>> {
/// `bytes` decoded and shrunk to fit [`PROXY_SIZE`] as a PNG; `None` when small enough already or
/// undecodable.
fn proxy_png(bytes: &[u8]) -> Option<Vec<u8>> {
let (w, h) = image::ImageReader::new(Cursor::new(bytes)).with_guessed_format().ok()?.into_dimensions().ok()?;
let format = craft_image_codecs::detect(bytes)?;
let (w, h, _) = crate::decode::decoded_layout(bytes, format)?;
if w.max(h) <= PROXY_SIZE {
return None;
}
// The proxy decodes within the project's raster cap, counted as RGBA like every other
// decode path (#3597): the header alone decides whether the pixels could ever fit, and the
// decoder gets the same budget instead of image's own default.
if u64::from(w) * u64::from(h) > crate::MAX_RASTER_ALLOC / 4 {
return None;
}
let mut reader = image::ImageReader::new(Cursor::new(bytes)).with_guessed_format().ok()?;
let mut limits = image::Limits::default();
limits.max_alloc = Some(crate::MAX_RASTER_ALLOC);
reader.limits(limits);
proxy_of(&reader.decode().ok()?)
// The proxy decodes within the project's raster cap, counted as the file's samples and as
// RGBA like every other decode path (#3597, #1717): the header alone decides whether the
// pixels could ever fit, and the decoder gets the same budget.
let (img, _) = crate::decode::decode_within(bytes, crate::MAX_RASTER_ALLOC).ok()??;
proxy_of(&img)
}
/// Decoded image `img` shrunk to fit [`PROXY_SIZE`] as a PNG.
@@ -748,4 +733,37 @@ mod tests {
assert!(p.pixels().all(|q| q.0 == [200, 30, 30, 128]), "{:?}", p.get_pixel(0, 0));
}
}
/// A PNG that says it is `w` × `h` 1-bit grey pixels (header and a stub IDAT, no rows).
fn png_header_1bit(w: u32, h: u32) -> Vec<u8> {
let mut out = vec![0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A];
let push = |out: &mut Vec<u8>, chunk: &[u8]| {
out.extend((chunk.len() as u32 - 4).to_be_bytes());
out.extend(chunk);
out.extend(crc32(chunk).to_be_bytes());
};
let mut ihdr = b"IHDR".to_vec();
ihdr.extend(w.to_be_bytes());
ihdr.extend(h.to_be_bytes());
ihdr.extend([1, 0, 0, 0, 0]);
push(&mut out, &ihdr);
push(&mut out, b"IDAT\x78\x9c");
push(&mut out, b"IEND");
out
}
/// A header-only 23,170 × 23,170 1-bit gray PNG is within the 2 GiB RGBA allowance, so Place
/// decodes it and must refuse it (no pixel rows). 23,171 × 23,170 is past the allowance and is
/// kept unread, not refused. craft-image-codecs reports the cut-short file as LimitExceeded
/// (its decompression-bomb guard); that is still "pixels can't be read", not "past the allowance".
#[test]
fn a_gray_header_within_the_allowance_is_unreadable() {
let within = png_header_1bit(23_170, 23_170);
let over = png_header_1bit(23_171, 23_170);
assert!(crate::decode::decode_within(&within, crate::MAX_RASTER_ALLOC).is_err(), "header-only within the allowance");
assert!(matches!(crate::decode::decode_within(&over, crate::MAX_RASTER_ALLOC), Ok(None)), "past the allowance is not decoded");
assert!(ImageBlob::new("image/png", within).checked_with_pixels(false).is_none(), "Place refuses the file");
let (_, pixels) = ImageBlob::new("image/png", over).checked_with_pixels(false).expect("past the allowance is kept unread");
assert!(pixels.is_none());
}
}
+126 -23
View File
@@ -20,15 +20,41 @@ pub type PixelPick<'a> = (Option<[f64; 4]>, usize, &'a dyn Fn(f64, f64) -> bool)
/// the header first: the decoder's limit is on the file's samples, and a gray image is a quarter
/// of what it becomes here (#1717).
fn rgba_within(bytes: &[u8], max: u64) -> Option<image::RgbaImage> {
let (w, h) = image::ImageReader::new(Cursor::new(bytes)).with_guessed_format().ok()?.into_dimensions().ok()?;
if u64::from(w) * u64::from(h) > max / 4 {
Some(crate::decode::decode_within(bytes, max).ok()??.0.into_rgba8())
}
/// An image file's stored size in pixels, read from its header by craft-image-codecs without
/// decoding any pixels: PNG's IHDR, a JPEG's frame, a TIFF's first full-resolution page, a
/// still or animated WebP's canvas, BMP's header ([`craft_image_codecs::probe_allocation_size`],
/// with no size limit), and a GIF's logical screen and the other formats' headers
/// ([`craft_image_codecs::probe_size`]). Not turned by an EXIF orientation. `None` when no header
/// gives a size.
pub fn header_size(bytes: &[u8]) -> Option<(u32, u32)> {
if craft_image_codecs::detect(bytes) == Some(craft_image_codecs::Format::Gif) {
// A GIF frame may be larger than the logical screen the image crate gave as its size.
return craft_image_codecs::probe_size(bytes).ok();
}
craft_image_codecs::probe_allocation_size(bytes)
.ok()
.or_else(|| craft_image_codecs::probe_size(bytes).ok())
// A BMP whose pixel data does not match its header (a truncated file, or a header that
// declares more pixels than the file holds) is refused by the image crate decoder the
// probes use. The BITMAPINFOHEADER still names the size, which Place, Paste and Open
// need so they can say the image is too large to draw instead of that its size can't
// be read.
.or_else(|| bmp_header_size(bytes))
}
/// Width and height from a BMP file's BITMAPINFOHEADER, without opening it as a decoder would.
/// Height may be negative (top-down storage); the stored magnitude is the size.
fn bmp_header_size(bytes: &[u8]) -> Option<(u32, u32)> {
if bytes.get(..2) != Some(b"BM") {
return None;
}
let mut reader = image::ImageReader::new(Cursor::new(bytes)).with_guessed_format().ok()?;
let mut limits = image::Limits::default();
limits.max_alloc = Some(max);
reader.limits(limits);
Some(reader.decode().ok()?.into_rgba8())
let dim = |at: usize| -> Option<i32> { Some(i32::from_le_bytes(bytes.get(at..at + 4)?.try_into().ok()?)) };
let width = u32::try_from(dim(18)?).ok().filter(|&n| n > 0)?;
let height = dim(22)?.unsigned_abs();
(height > 0).then_some((width, height))
}
impl ImageBlob {
@@ -385,30 +411,43 @@ mod tests {
assert!(ImageBlob::png(b"not a png".to_vec()).sample_pixels(&[(None, 100, &any)]).is_none());
}
/// A GIF whose `w` × `h` screen holds one opaque red pixel at the top left. The file holds no
/// other pixels, and the decoder makes them transparent.
fn gif_with_one_red_pixel(w: u16, h: u16) -> Vec<u8> {
let mut gif = b"GIF89a".to_vec();
gif.extend_from_slice(&w.to_le_bytes());
gif.extend_from_slice(&h.to_le_bytes());
// Flags for a global color table of two colors, the background and aspect bytes, then the
// table: red and black.
gif.extend_from_slice(&[0x80, 0, 0, 255, 0, 0, 0, 0, 0]);
// A 1 × 1 image at (0, 0), its LZW data (clear, color 0, end), and the end of the file.
gif.extend_from_slice(&[0x2C, 0, 0, 0, 0, 1, 0, 1, 0, 0, 2, 2, 0x44, 0x01, 0, 0x3B]);
gif
/// An RGBA PNG of `w` × `h` pixels with one opaque red pixel at the top left, the rest
/// transparent. Written row by row so the 11,586² allowance image is not held decoded
/// while it is encoded.
fn png_with_one_red_pixel(w: u32, h: u32) -> Vec<u8> {
use std::io::Write;
let mut z = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::fast());
let mut row = vec![0u8; 1 + w as usize * 4];
row[1..5].copy_from_slice(&[255, 0, 0, 255]);
z.write_all(&row).unwrap();
row[1..5].fill(0);
for _ in 1..h {
z.write_all(&row).unwrap();
}
let idat = [&b"IDAT"[..], &z.finish().unwrap()].concat();
let ihdr = [&b"IHDR"[..], &w.to_be_bytes(), &h.to_be_bytes(), &[8, 6, 0, 0, 0]].concat();
let mut out = b"\x89PNG\r\n\x1a\n".to_vec();
for chunk in [&ihdr[..], &idat[..], b"IEND"] {
out.extend((chunk.len() as u32 - 4).to_be_bytes());
out.extend(chunk);
let mut crc = flate2::Crc::new();
crc.update(chunk);
out.extend(crc.sum().to_be_bytes());
}
out
}
/// The pixels are decoded within the allowance, not within the decoder's own 512 MB: an RGBA
/// image of 11,586 × 11,586 pixels (536,941,584 bytes) is recolored and sampled.
/// image of 11,586 × 11,586 pixels (536,941,584 bytes) is recolored and sampled. A PNG, not a
/// sparse GIF: craft-image-codecs refuses a GIF whose unbacked logical screen is past 256 MiB.
#[test]
fn pixels_past_the_decoders_own_limit_are_decoded_within_the_allowance() {
let (w, h) = (11_586, 11_586);
let rgba = u64::from(w) * u64::from(h) * 4;
assert!(rgba > 512 << 20);
let gif = gif_with_one_red_pixel(w, h);
assert!(rgba_within(&gif, rgba - 1).is_none(), "past the allowance");
let b = ImageBlob::new("image/gif", gif);
let png = png_with_one_red_pixel(w, h);
assert!(rgba_within(&png, rgba - 1).is_none(), "past the allowance");
let b = ImageBlob::png(png);
assert!(b.map_rgb(|[r, g, bl]| [bl, g, r]).is_some(), "red becomes blue");
assert_eq!(b.sample(0.5, 0.5, 1), Some([255, 0, 0, 255]));
assert_eq!(b.sample(f64::from(w) - 0.5, f64::from(h) - 0.5, 1), None, "transparent");
@@ -556,4 +595,68 @@ mod tests {
assert_eq!(la8.coverage(), Some((4, 1, vec![255, 0, 204, 128])));
assert_eq!(ImageBlob::png(vec![1, 2, 3]).coverage(), None);
}
/// Embedded-image pixels through craft-image-codecs (#778) are those the image crate decoded:
/// the same layout and samples for PNG, GIF, WebP, TIFF and BMP at each depth the image
/// crate writes, and JPEG samples within two steps.
#[test]
fn decoded_pixels_are_those_the_image_crate_read() {
use image::{DynamicImage as D, ImageFormat as F};
let rgba =
image::RgbaImage::from_fn(9, 5, |x, y| image::Rgba([(x * 29) as u8, (y * 47) as u8, ((x + 2 * y) * 9) as u8, 255 - (x * y * 6) as u8]));
let deep = image::ImageBuffer::<image::Rgba<u16>, _>::from_fn(9, 5, |x, y| {
image::Rgba([(x * 7_001) as u16, (y * 12_007) as u16, 5, 65_535 - (x * y) as u16])
});
let images = [
D::ImageRgba8(rgba.clone()),
D::ImageRgb8(D::ImageRgba8(rgba.clone()).to_rgb8()),
D::ImageLuma8(D::ImageRgba8(rgba.clone()).to_luma8()),
D::ImageLumaA8(D::ImageRgba8(rgba).to_luma_alpha8()),
D::ImageRgba16(deep.clone()),
D::ImageLuma16(D::ImageRgba16(deep).to_luma16()),
];
let mut checked = 0;
for img in &images {
for f in [F::Png, F::Gif, F::WebP, F::Tiff, F::Bmp, F::Jpeg] {
let mut bytes = Vec::new();
if img.write_to(&mut Cursor::new(&mut bytes), f).is_err() {
continue;
}
let what = format!("{f:?} {:?}", img.color());
let want = image::load_from_memory_with_format(&bytes, f).unwrap();
let (got, _) = crate::decode::decode_within(&bytes, MAX_RASTER_ALLOC)
.unwrap_or_else(|e| panic!("{what}: {e}"))
.unwrap_or_else(|| panic!("{what}: past the allowance"));
let tolerance = if f == F::Jpeg { 2 * 257 } else { 0 };
if f != F::Jpeg {
assert_eq!(got.color(), want.color(), "{what}");
}
let worst = got.to_rgba16().as_raw().iter().zip(want.to_rgba16().as_raw()).map(|(a, b)| a.abs_diff(*b)).max();
assert!(worst.is_some_and(|w| w <= tolerance), "{what}: {worst:?}");
// Link previews and the checked-image path read the same pixels.
let handed = ImageBlob::new(format!("image/{f:?}").to_ascii_lowercase(), bytes.clone())
.checked_with_pixels(false)
.unwrap_or_else(|| panic!("{what}: checked"))
.1
.unwrap_or_else(|| panic!("{what}: checked past the allowance"));
assert_eq!(handed.color(), got.color(), "{what} checked");
assert_eq!(handed.as_bytes(), got.as_bytes(), "{what} checked");
checked += 1;
}
}
assert!(checked >= 20, "{checked}");
}
/// A BMP header that declares 30,000 × 30,000 pixels, with only one pixel of data, still
/// reports that size: Paste and Place can then say the image is too large to draw.
#[test]
fn a_truncated_bmp_header_still_gives_its_declared_size() {
let mut bmp = vec![];
image::RgbImage::from_pixel(1, 1, image::Rgb([200, 40, 40])).write_to(&mut Cursor::new(&mut bmp), image::ImageFormat::Bmp).unwrap();
bmp[18..22].copy_from_slice(&30_000i32.to_le_bytes());
bmp[22..26].copy_from_slice(&30_000i32.to_le_bytes());
assert_eq!(header_size(&bmp), Some((30_000, 30_000)));
let (w, h, _) = crate::decode::decoded_layout(&bmp, craft_image_codecs::Format::Bmp).expect("layout from the header");
assert_eq!((w, h), (30_000, 30_000));
}
}
+7 -7
View File
@@ -1,5 +1,5 @@
//! Placed documents: another VectorCraft file, or a page of a PDF or `.ai` file, placed linked
//! ([`PlacedDocument`]).
//! Placed documents: another VectorCraft file, a page of a PDF or `.ai` file, or an EPS file,
//! placed linked ([`PlacedDocument`]).
//!
//! The object keeps the link to the file and the file's bytes, stored like image data in
//! [`Document::images`] (with a small preview a save writes instead, as for linked images), so the
@@ -7,9 +7,9 @@
//! joins the object tree, so editing can't reach it: it is locked by design. Drawing and exporting
//! expand it like a live object ([`crate::live::expanded`]).
//!
//! The file is read by the engine's loader (native documents, PDF and `.ai` pages), which lives
//! above this crate and registers itself ([`set_loader`]); the art read is kept in a small cache
//! by content. Before exporting,
//! The file is read by the engine's loader (native documents, PDF and `.ai` pages, EPS files),
//! which lives above this crate and registers itself ([`set_loader`]); the art read is kept in a
//! small cache by content. Before exporting,
//! every exporter calls [`Document::with_placed_art`], which adds the resources the art uses
//! (images, symbols, patterns) under names of their own ([`RESOURCE_PREFIX`]) to a temporary copy
//! of the document, so they never meet the user's or show in panels. Placed documents inside a
@@ -27,8 +27,8 @@ use vectorcraft_color::Paint;
use crate::{AppearanceItem, Document, ImageBlob, ImageObject, LinkInfo, Node, NodeKind, PatternDef, PlacementOptions, Symbol};
/// A placed document: an artboard of another VectorCraft file, or a page of a PDF or `.ai` file,
/// shown as one locked object.
/// A placed document: an artboard of another VectorCraft file, a page of a PDF or `.ai` file, or
/// an EPS file's art, shown as one locked object.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct PlacedDocument {
/// The file (its `page` is the artboard or page shown, 1-based).
+5 -5
View File
@@ -50,10 +50,10 @@ pub struct Selection {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub key_guide: Option<NodeId>,
/// The key anchor for Align: one of two or more anchor points selected with Direct Selection,
/// the last one a Shift-click added (path, anchor in [`Self::anchors`]). Align and Distribute
/// move the other selected points relative to it, and it stays in place. Never set with `key`
/// or `key_guide`; [`Self::prune`] clears it when the point is no longer a selected anchor, or
/// fewer than two points are selected.
/// designated by clicking an already-selected anchor point without modifiers (path, anchor in
/// [`Self::anchors`]). Align and Distribute move the other selected points relative to it, and
/// it stays in place. Never set with `key` or `key_guide`; [`Self::prune`] clears it when the
/// point is no longer a selected anchor, or fewer than two points are selected.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub key_anchor: Option<(NodeId, AnchorRef)>,
/// The new art on a locked artboard that this selection keeps editable
@@ -311,7 +311,7 @@ impl Selection {
let anchor_kept = self.key_anchor.is_some_and(|(id, (si, ai))| {
self.objects.contains(&id)
&& !self.segments.contains_key(&id)
&& self.anchors.get(&id).is_some_and(|set| set.contains(&(si, ai)))
&& (self.anchors.get(&id).is_some_and(|set| set.contains(&(si, ai))) || !self.anchors.contains_key(&id))
&& found
.get(&id)
.and_then(|p| doc.node_at(p))
+17
View File
@@ -206,6 +206,13 @@ pub const LANGUAGES: &[(&str, &str, Quotes)] = &[
("Assamese", "as", Quotes::ENGLISH),
("Sanskrit", "sa", Quotes::ENGLISH),
("Urdu", "ur", Quotes::ENGLISH),
// “…” outside, ‘…’ inside: CLDR gives these no delimiters of their own (`↑↑↑`, inherited), so
// they take root's (https://github.com/unicode-org/cldr/blob/main/common/main/root.xml,
// `delimiters`): sa.xml, ne.xml, as.xml, kok.xml and sd.xml (Arabic script; sd_Deva.xml for
// Devanagari inherits too) in https://github.com/unicode-org/cldr/blob/main/common/main/.
("Nepali", "ne", Quotes::ENGLISH),
("Konkani", "kok", Quotes::ENGLISH),
("Sindhi", "sd", Quotes::ENGLISH),
];
/// The quotes of a [`LANGUAGES`] entry (case-insensitive).
@@ -420,6 +427,11 @@ mod tests {
assert_eq!(char_language("BG"), Ok(Some("bg")));
assert_eq!(char_language_name(Some("bg")), Some("Bulgarian"));
assert_eq!(char_language_name(Some("sr-Cyrl")), Some("Serbian: Cyrillic"));
// Sanskrit, Nepali, Assamese, Konkani (a three-letter tag) and Sindhi, by name or tag.
for (name, tag) in [("Sanskrit", "sa"), ("Nepali", "ne"), ("Assamese", "as"), ("Konkani", "kok"), ("Sindhi", "sd")] {
assert_eq!((char_language(name), char_language(&tag.to_uppercase())), (Ok(Some(tag)), Ok(Some(tag))), "{name}");
assert_eq!(char_language_name(Some(tag)), Some(name));
}
// Every entry has a tag of its own, and a name of its own.
for (i, (n, t, _)) in LANGUAGES.iter().enumerate() {
assert!(LANGUAGES.iter().skip(i + 1).all(|(n2, t2, _)| n2 != n && t2 != t), "{n} {t}");
@@ -443,6 +455,11 @@ mod tests {
}
let mut prev = None;
assert_eq!(language_quotes("croatian").unwrap().apply("\"a 'b' c\"", &mut prev), "„a ‚b‘ c“");
// Sanskrit, Nepali, Assamese, Konkani and Sindhi take CLDR root's quotes.
for name in ["Sanskrit", "Nepali", "Assamese", "Konkani", "Sindhi"] {
let mut prev = None;
assert_eq!(language_quotes(name).unwrap().apply("\"a 'b' c\"", &mut prev), "“a ‘b’ c”", "{name}");
}
// Only a typed `”` stands for a straight quote; the other curly quotes stay as typed.
assert_eq!(Quotes::typed_as_straight('”'), Some('"'));
assert!(['“', '„', '‘', '’', '‚', '"', '\'', '«', '»', '「', 'a'].iter().all(|&c| Quotes::typed_as_straight(c).is_none()));
+3 -3
View File
@@ -17,10 +17,10 @@ vectorcraft-text = { workspace = true }
vectorcraft-plugins = { workspace = true }
vectorcraft-trace = { workspace = true }
image = { workspace = true }
craft-image-codecs = { workspace = true }
kurbo = { workspace = true }
# Effect › SVG Filters draws its filters with resvg (MIT OR Apache-2.0), at the usvg version the
# workspace reads SVG with; raster-images decodes the object's pixels it hands the filter as a PNG.
resvg = { version = "0.48", default-features = false, features = ["raster-images"] }
# Effect › SVG Filters draws its filters with craft-svg's resvg (`tree-render`).
craft-svg = { workspace = true, features = ["tree-render"] }
# The number lists of filter attributes, read as usvg reads them (MIT OR Apache-2.0; already used by usvg).
svgtypes = "0.16"
serde_json = { workspace = true }
+5 -5
View File
@@ -182,28 +182,28 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
REVOLVE,
"Revolve…",
&["Effect", "3D and Materials"],
"{angle: degrees (0..360, 360), offset: pt (0..100000, 0), edge: left|right, rotationX: degrees (0), rotationY: degrees (0), rotationZ: degrees (0), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), segments: integer (8..128, 64), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a hard-edged shadow, black at 50% times the art's opacity), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), cap: bool (true, close circular ends of open profiles; partial-sweep cut sides stay open), expandVisibleOnly: bool (true, trim covered opaque solid surfaces only on Expand Appearance; surfaces with graphics keep every face), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the swept side, see threeD.mapGraphic: symbol: name of a document symbol, face: front (the side), x: pt (0; the offset of the graphic's center from the middle of the side, around the axis: the angle times the profile's distance from the axis at that point), y: pt (0; along the profile, toward its lower end), scale: % (1..10000, 100), rotation: degrees (-360..360, 0; counterclockwise); wrapped around the side at its own size, so it reaches farther around where the profile comes nearer the axis, shaded with it and drawn only where the side's outside faces the viewer; a full turn cuts it at the back; nothing on the caps), render: object ({mode: shaded}; mode: shaded|wireframe, wireframe draws the edges of the faces the effect draws, each once, stroked 0.5 pt black with round joins, with no fill, shadow or graphics, whatever the opacity of the fills, strokes and group members, while the effect stays live; the stroke is VectorCraft's own)}. Shaded surfaces use smooth vector gradients automatically; intersecting profiles use approximate painter visibility.",
"{angle: degrees (0..360, 360), offset: pt (0..100000, 0), edge: left|right, rotationX: degrees (0), rotationY: degrees (0), rotationZ: degrees (0), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), segments: integer (8..128, 64), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), cap: bool (true: solid, closing circular ends of open profiles and a partial sweep's cut sides; false: hollow), expandVisibleOnly: bool (true, trim covered opaque solid surfaces only on Expand Appearance; surfaces with graphics keep every face), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the swept side, see threeD.mapGraphic: symbol: name of a document symbol, face: front (the side), x: pt (0; the offset of the graphic's center from the middle of the side, around the axis: the angle times the profile's distance from the axis at that point), y: pt (0; along the profile, toward its lower end), scale: % (1..10000, 100), rotation: degrees (-360..360, 0; counterclockwise); wrapped around the side at its own size, so it reaches farther around where the profile comes nearer the axis, shaded with it and drawn only where the side's outside faces the viewer; a full turn cuts it at the back; nothing on the caps), render: object ({mode: shaded}; mode: shaded|wireframe, wireframe draws the edges of the faces the effect draws, each once, stroked 0.5 pt black with round joins, with no fill, shadow or graphics, whatever the opacity of the fills, strokes and group members, while the effect stays live; the stroke is VectorCraft's own)}. Shaded surfaces use smooth vector gradients automatically; intersecting profiles use approximate painter visibility.",
json!({"angle":360.0,"offset":0.0,"edge":"left","rotationX":0.0,"rotationY":0.0,"rotationZ":0.0,"perspectiveAngle":0.0,"segments":64,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"cap":true,"expandVisibleOnly":true,"graphics":[],"render":{"mode":"shaded"}}),
),
g(
EXTRUDE,
"Extrude & Bevel…",
&["Effect", "3D and Materials"],
"{depth: pt (0..2000, 50), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none), bevelWidth: pt (0..1000, 4), bevelHeight: pt (0..1000, 4), bevelRepeat: integer (1..32, 1), bevelSpace: % (0..90, 0; flat between repeats), bevelInside: bool (false: added around the shape; true: carved into it), bevelBothSides: bool (false), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a hard-edged shadow, black at 50% times the art's opacity), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the caps, see threeD.mapGraphic: symbol: name of a document symbol, face: front|back (front; the back reads left to right as seen from behind), x: pt (0; the offset of the graphic's center from the center of the object's bounds, in the face's own plane), y: pt (0), scale: % (1..10000, 100; of the symbol's own size), rotation: degrees (-360..360, 0; counterclockwise); drawn turned, foreshortened and shaded with the cap and clipped to it, on a solid cap only), render: object ({mode: shaded}; mode: shaded|wireframe, as Revolve's)}. The front face is the art, extruded backwards about the centre of its bounds; painted with the top fill (else the top stroke).",
"{depth: pt (0..2000, 50), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none), bevelWidth: pt (0..1000, 4), bevelHeight: pt (0..1000, 4), bevelRepeat: integer (1..32, 1), bevelSpace: % (0..90, 0; flat between repeats), bevelInside: bool (false: added around the shape; true: carved into it), bevelBothSides: bool (false), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the caps, see threeD.mapGraphic: symbol: name of a document symbol, face: front|back (front; the back reads left to right as seen from behind), x: pt (0; the offset of the graphic's center from the center of the object's bounds, in the face's own plane), y: pt (0), scale: % (1..10000, 100; of the symbol's own size), rotation: degrees (-360..360, 0; counterclockwise); drawn turned, foreshortened and shaded with the cap and clipped to it, on a solid cap only), render: object ({mode: shaded}; mode: shaded|wireframe, as Revolve's)}. The front face is the art, extruded backwards about the centre of its bounds; painted with the top fill (else the top stroke).",
json!({"depth":50.0,"twist":0.0,"taper":100.0,"cap":true,"bevel":"none","bevelWidth":4.0,"bevelHeight":4.0,"bevelRepeat":1,"bevelSpace":0.0,"bevelInside":false,"bevelBothSides":false,"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"graphics":[],"render":{"mode":"shaded"}}),
),
g(
INFLATE,
"Inflate…",
&["Effect", "3D and Materials"],
"{depth: pt (0..2000, 0; flat depth between front and back), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: no back, a shell open behind), volume: % (0..100, 50; 50 rounds the edge like a half sphere), bothSides: bool (false: flat back), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a hard-edged shadow, black at 50% times the art's opacity), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), render: object ({mode: shaded}; mode: shaded|wireframe, as Revolve's)}. Painted with the top fill (else the top stroke).",
"{depth: pt (0..2000, 0; flat depth between front and back), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: no back, a shell open behind), volume: % (0..100, 50; 50 rounds the edge like a half sphere), bothSides: bool (false: flat back), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), render: object ({mode: shaded}; mode: shaded|wireframe, as Revolve's)}. Painted with the top fill (else the top stroke).",
json!({"depth":0.0,"twist":0.0,"taper":100.0,"cap":true,"volume":50.0,"bothSides":false,"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"render":{"mode":"shaded"}}),
),
g(
ROTATE,
"Rotate…",
&["Effect", "3D and Materials"],
"{rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a hard-edged shadow, black at 50% times the art's opacity), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the plane, as Extrude & Bevel's, with face front only), render: object ({mode: shaded}; mode: shaded|wireframe, as Revolve's)}. Turns the flat art in 3D about the centre of its bounds; every fill and stroke keeps its paint, shaded as one plane.",
"{rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the plane, as Extrude & Bevel's, with face front only), render: object ({mode: shaded}; mode: shaded|wireframe, as Revolve's)}. Turns the flat art in 3D about the centre of its bounds; every fill and stroke keeps its paint, shaded as one plane.",
json!({"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"graphics":[],"render":{"mode":"shaded"}}),
),
g(
@@ -217,7 +217,7 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
CLASSIC_REVOLVE,
"Revolve (Classic)…",
&["Effect", "3D and Materials", "3D (Classic)"],
"{angle: degrees (0..360, 360; how far the profile sweeps round the axis), cap: bool (true: solid, the open ends closed; false: hollow), offset: pt (0..1000, 0; the axis's distance from the profile, a ring past 0), edge: left|right (left; the axis is at the left or the right edge of the profile's bounds), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: wireframe|none|diffuse|plastic (plastic; wireframe draws the edges of every face and fills none; none keeps the paint unlit; diffuse lights the faces softly; plastic adds a glossy highlight), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, every face whichever way it faces), highlightIntensity: % (0..100, 60; plastic only), highlightSize: % (0..100, 90; 100 broad, 0 a small spot; plastic only), blendSteps: integer (1..256, 25; how many levels the shading and the highlight are rounded to), shadingColor: black|custom|none|blackOverprint (black; the color the faces darken toward; none keeps the paint and adds only the highlight; blackOverprint keeps the paint and draws the shading over it as overprinting black, on the black plate, with no highlight), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), preserveSpotColors: bool (false; a color linked to a spot or global swatch stays a tint of that swatch, lighter where the highlight is, with black multiplied and overprinting where the faces darken, so a spot color keeps its plate; it does nothing while shadingColor is custom, and with blackOverprint every face keeps its paint and swatch link whether it is on or off)}. The profile sweeps round a vertical axis, as Revolve's does, painted with the top fill (else the top stroke); every face is drawn, back to front. The defaults are VectorCraft's own.",
"{angle: degrees (0..360, 360; how far the profile sweeps round the axis), cap: bool (true: solid, the open ends and a partial sweep's cut sides closed; false: hollow), offset: pt (0..1000, 0; the axis's distance from the profile, a ring past 0), edge: left|right (left; the axis is at the left or the right edge of the profile's bounds), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: wireframe|none|diffuse|plastic (plastic; wireframe draws the edges of every face and fills none; none keeps the paint unlit; diffuse lights the faces softly; plastic adds a glossy highlight), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, every face whichever way it faces), highlightIntensity: % (0..100, 60; plastic only), highlightSize: % (0..100, 90; 100 broad, 0 a small spot; plastic only), blendSteps: integer (1..256, 25; how many levels the shading and the highlight are rounded to), shadingColor: black|custom|none|blackOverprint (black; the color the faces darken toward; none keeps the paint and adds only the highlight; blackOverprint keeps the paint and draws the shading over it as overprinting black, on the black plate, with no highlight), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), preserveSpotColors: bool (false; a color linked to a spot or global swatch stays a tint of that swatch, lighter where the highlight is, with black multiplied and overprinting where the faces darken, so a spot color keeps its plate; it does nothing while shadingColor is custom, and with blackOverprint every face keeps its paint and swatch link whether it is on or off)}. The profile sweeps round a vertical axis, as Revolve's does, painted with the top fill (else the top stroke); every face is drawn, back to front. The defaults are VectorCraft's own.",
json!({"angle":360.0,"cap":true,"offset":0.0,"edge":"left","rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"surface":"plastic","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":100.0,"ambient":50.0,"highlightIntensity":60.0,"highlightSize":90.0,"blendSteps":25,"shadingColor":"black","shadingCustom":"#000000","preserveSpotColors":false}),
),
g(
+3 -3
View File
@@ -86,9 +86,9 @@ pub use raster::{
without_geometry,
};
pub use reshape::{
SYMBOL_ART_MAX_NODES, expand_outlined, follows_image_pixels, gives_image_shape, has_gradient_copies, has_instance_row_raster, has_item_geometry,
has_painted_effects, has_transform_art, has_transform_copies, has_transform_options, image_paint, needs_outline, outer_effects, outline_art,
outline_text, paint_type_piece, reshape,
SYMBOL_ART_MAX_NODES, expand_outlined, follows_image_pixels, gives_image_shape, has_copied_row_raster, has_gradient_copies,
has_instance_row_raster, has_item_geometry, has_painted_effects, has_transform_art, has_transform_copies, has_transform_options, image_paint,
instance_as_art, needs_outline, outer_effects, outline_art, outline_text, paint_type_piece, reshape,
};
pub use revolve::{
CLASSIC_REVOLVE, REVOLVE, has_revolve, is_revolve, revolve_art, revolve_art_in, revolve_options, validate_revolve, validate_revolve_in,
+36 -14
View File
@@ -6,7 +6,6 @@
//! lies one pixel per point at 100 %, centered on the object's center and repeated in both
//! directions.
use std::io::Cursor;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex, PoisonError};
@@ -85,9 +84,15 @@ impl LoadedTexture {
/// Its [`TEXTURE_IMAGE`] value: the gray levels as a grayscale PNG, base64; `None` when the
/// PNG can't be written.
pub fn to_stored(&self) -> Option<String> {
let img = image::GrayImage::from_raw(self.width, self.height, self.gray.clone())?;
let mut png = Vec::new();
img.write_to(&mut Cursor::new(&mut png), image::ImageFormat::Png).ok()?;
let img = craft_image_codecs::Image::from_raw(
self.width,
self.height,
craft_image_codecs::ChannelLayout::Gray,
craft_image_codecs::SampleType::U8,
self.gray.clone(),
)
.ok()?;
let png = craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok()?;
Some(base64_encode(&png))
}
@@ -95,21 +100,38 @@ impl LoadedTexture {
/// `None` when `png` isn't a PNG or holds no pixels.
/// `None` too when its gray levels would take the live textures past [`MAX_LIVE`].
fn from_png(png: &[u8]) -> Option<Self> {
let reader = || {
let mut reader = image::ImageReader::with_format(Cursor::new(png), image::ImageFormat::Png);
let mut limits = image::Limits::default();
limits.max_alloc = Some(vectorcraft_doc::MAX_RASTER_ALLOC);
reader.limits(limits);
reader
};
let (w, h) = reader().into_dimensions().ok()?;
let (w, h) = Self::png_ihdr_size(png)?;
let gray = (w as usize).checked_mul(h as usize)?;
if LIVE.load(Ordering::Relaxed).saturating_add(gray) > MAX_LIVE {
return None;
}
let img = reader().decode().ok()?.to_luma8();
let mut opts = craft_image_codecs::DecodeOptions::default();
opts.limits.max_alloc = vectorcraft_doc::MAX_RASTER_ALLOC;
// The codec default caps each side at 2^18; a stored texture can be longer than that and
// still fit the live and allocation budgets.
opts.limits.max_width = u32::MAX;
opts.limits.max_height = u32::MAX;
let img = craft_image_codecs::decode_as_with(craft_image_codecs::Format::Png, png, &opts).ok()?;
let (width, height) = img.dimensions();
(width > 0 && height > 0).then(|| Self::new(width, height, img.into_raw()))
if width == 0 || height == 0 {
return None;
}
use craft_image_codecs::{ChannelLayout as L, SampleType as S};
let luma = match (img.layout(), img.sample_type()) {
(L::Gray, S::U8) => img.into_data(),
_ => image::RgbaImage::from_raw(width, height, img.to_rgba8()).map(image::DynamicImage::ImageRgba8)?.into_luma8().into_raw(),
};
Some(Self::new(width, height, luma))
}
/// Read `(width, height)` from a PNG's IHDR chunk without decoding pixels.
fn png_ihdr_size(png: &[u8]) -> Option<(u32, u32)> {
if png.len() < 24 || &png[..8] != b"\x89PNG\r\n\x1a\n" || &png[12..16] != b"IHDR" {
return None;
}
let w = u32::from_be_bytes(png[16..20].try_into().ok()?);
let h = u32::from_be_bytes(png[20..24].try_into().ok()?);
Some((w, h))
}
/// The surface's height (points) at `p` (points at 100 %, from the object's center): the gray
+8
View File
@@ -1704,6 +1704,14 @@ fn a_loaded_texture_is_its_gray_over_middle_gray() {
assert!(texture("not base64!").is_none() && texture("aGVsbG8=").is_none(), "base64 of a PNG only");
}
/// A stored texture longer than the codec's default 2^18-pixel side still reads back.
#[test]
fn a_stored_texture_longer_than_the_codec_default_side_reads_back() {
let t = LoadedTexture::from_rgba(262_145, 1, &vec![128; 262_145 * 4]).and_then(|t| t.to_stored()).unwrap();
let loaded = texture(&t).unwrap();
assert_eq!(loaded.size(), (262_145, 1));
}
#[test]
fn glass_bends_the_image_by_a_loaded_texture() {
let (w, h) = (48, 40);
+237 -31
View File
@@ -107,15 +107,66 @@ fn reaches_appearance(e: &Effect) -> bool {
}
/// Is `n` a path or compound path that its Transform effects make into art of separate objects
/// ([`has_gradient_copies`], [`has_layered_copies`], [`has_transform_options`], [`copied_raster_at`]),
/// or whose live-effect plug-ins paint what they return ([`has_painted_effects`])? It is drawn,
/// baked and expanded through that art ([`reshape`]).
/// ([`has_gradient_copies`], [`has_layered_copies`], [`has_transform_options`], [`copied_raster_at`],
/// [`has_copied_row_raster`]), or whose live-effect plug-ins paint what they return
/// ([`has_painted_effects`])? It is drawn, baked and expanded through that art ([`reshape`]).
pub fn has_transform_art(n: &Node) -> bool {
has_gradient_copies(n)
|| has_layered_copies(n)
|| has_transform_options(n)
|| has_painted_effects(n)
|| (matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) && copied_raster_at(n).is_some())
|| has_copied_row_raster(n)
}
/// Is `n` a path or compound path with a fill or stroke that paints and whose raster effects are
/// carried by copies: one whose own effects list a Transform effect that makes copies after a
/// raster effect that follows it ([`copied_row_raster_at`]), or one with a raster effect that
/// follows a Transform effect ([`crate::raster::follows`]) on a path whose own Transform effect makes
/// copies ([`has_transform_copies`])? Each copy is then an object of its own carrying that fill's or
/// stroke's raster effects, moved, turned, reflected and scaled with it ([`transform_item_leaf`],
/// [`follow_copies`]).
pub fn has_copied_row_raster(n: &Node) -> bool {
if !matches!(n.kind, NodeKind::Path { guide: false, clipping: false, .. } | NodeKind::Compound { .. }) {
return false;
}
// Checked first: this runs for every object drawn.
if !n.appearance.items.iter().any(follows_row_raster) {
return false;
}
n.appearance.items.iter().any(|i| crate::paints(i) && copied_row_raster_at(i.effects()).is_some()) || has_transform_copies(n)
}
/// Does `item` paint and carry a visible raster effect that follows a Transform effect
/// ([`crate::raster::follows`])?
fn follows_row_raster(item: &AppearanceItem) -> bool {
crate::paints(item) && item.effects().iter().any(|e| e.visible && crate::raster::follows(&e.id))
}
/// Where a fill's or stroke's own effects `fx` split so that each copy of a Transform effect carries
/// the raster effects listed before it: the index of the first visible Transform effect that makes
/// copies (an earlier one that makes copies included) for which a visible raster effect that
/// follows a Transform effect ([`crate::raster::follows`]) is listed before it, every other visible
/// effect before it is a geometry effect or such a raster effect, and no Transform effect before it
/// that makes copies or moves at random holds those raster effects back
/// ([`crate::raster::held_back`]). `None` otherwise, and when a raster effect is listed after it
/// and before a later Transform effect that makes copies or moves at random, which would apply to
/// the art that raster effect paints.
fn copied_row_raster_at(fx: &[Effect]) -> Option<usize> {
let copying =
|e: &Effect| e.visible && e.id == "distort.transform" && crate::distort::transform_map(Rect::ZERO, &merged_params(&e.id, &e.params), 0).1 > 0;
// Is a visible raster effect in `rest` listed before its last Transform effect that holds back?
let raster_held = |rest: &[Effect]| {
rest.iter().rposition(crate::raster::holds_back).is_some_and(|k| rest[..k].iter().any(|e| e.visible && crate::is_raster(&e.id)))
};
(0..fx.len()).find(|&t| {
let before = &fx[..t];
copying(&fx[t])
&& !raster_held(&fx[t + 1..])
&& crate::raster::held_back(before) == 0
&& 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))
})
}
/// Where the own effects of `n`, a path, compound path, type, image or symbol instance, split so
@@ -900,6 +951,16 @@ pub fn expand_outlined(doc: Option<&Document>, n: &Node, symbol_art: Option<&Nod
as_art(doc, n, symbol_art)
}
/// Symbol instance `n` as plain art for Expand Appearance, with or without geometry effects: the
/// art it places, reshaped by those effects when it has some, in the form [`expand_outlined`]
/// gives. `None` for other kinds of objects and for an instance without `symbol_art`.
pub fn instance_as_art(doc: Option<&Document>, n: &Node, symbol_art: Option<&Node>) -> Option<Node> {
if !matches!(n.kind, NodeKind::SymbolInstance { .. }) {
return None;
}
as_art(doc, n, symbol_art)
}
/// [`reshape`] without its checks (no geometry effects: just the art).
pub(crate) fn as_art(doc: Option<&Document>, n: &Node, symbol_art: Option<&Node>) -> Option<Node> {
as_art_with(doc, doc, n, symbol_art, &outline_text, &SymbolNodes::default())
@@ -989,7 +1050,7 @@ fn as_art_opts(
}
_ => outline_art_with(symbols, paint_doc, n, symbol_art, outline, nodes, apart)?,
};
reshape_leaves_apart(&mut art, &fx, &n.appearance.effects, Budget::EFFECTS, apart, paint_doc);
reshape_leaves_apart(&mut art, &fx, &n.appearance.effects, Budget::EFFECTS, (apart, has_copied_row_raster(n)), paint_doc);
if apart {
hoist_copies(&mut art);
}
@@ -1058,7 +1119,8 @@ fn copied_raster_art(doc: Option<&Document>, n: &Node, t: usize, apart: bool, ou
}
None => {
let mut art = one_piece(&source);
let carry = reshape_leaves_apart(&mut art, &geometry_effects(&source), &source.appearance.effects, Budget::EFFECTS, apart, doc);
let rows = has_copied_row_raster(&source);
let carry = reshape_leaves_apart(&mut art, &geometry_effects(&source), &source.appearance.effects, Budget::EFFECTS, (apart, rows), doc);
if apart {
hoist_copies(&mut art);
}
@@ -1099,7 +1161,7 @@ fn copied_raster_art(doc: Option<&Document>, n: &Node, t: usize, apart: bool, ou
}
}
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, apart, doc);
let carry = reshape_leaves_apart(&mut art, &later, &n.appearance.effects, Budget::EFFECTS, (apart, has_copied_row_raster(n)), doc);
let mut ran = n.appearance.effects.clone();
if carry.skipped() {
carry.hide_skipped(&mut ran);
@@ -1230,19 +1292,19 @@ pub(crate) fn geometry_effects(n: &Node) -> Vec<&Effect> {
/// that live-effect plug-ins painting their pieces name are looked up in `doc`, and a deferred one
/// is listed by its index in `owner`, the effect list `fx` was taken from ([`reshape_leaves_apart`]).
pub(crate) fn reshape_leaves(art: &mut Node, fx: &[&Effect], owner: &[Effect], doc: Option<&Document>) {
reshape_leaves_apart(art, fx, owner, Budget::EFFECTS, false, doc);
reshape_leaves_apart(art, fx, owner, Budget::EFFECTS, (false, false), doc);
}
/// [`reshape_leaves`], and how gradients that paint the art as a whole (a group's own fills and
/// strokes) follow the effects ([`crate::Carry`]).
pub(crate) fn reshape_leaves_carrying(art: &mut Node, fx: &[&Effect], owner: &[Effect], doc: Option<&Document>) -> crate::Carry {
reshape_leaves_apart(art, fx, owner, Budget::EFFECTS, false, doc)
reshape_leaves_apart(art, fx, owner, Budget::EFFECTS, (false, false), doc)
}
/// [`reshape_leaves_carrying`] whose paths keep to `budget` together, or to what they cost.
#[cfg(test)]
pub(crate) fn reshape_leaves_within(art: &mut Node, fx: &[&Effect], budget: Budget, doc: Option<&Document>) -> crate::Carry {
reshape_leaves_apart(art, fx, &[], budget, false, doc)
reshape_leaves_apart(art, fx, &[], budget, (false, false), doc)
}
/// `art`, the group of the one piece a path's copies are made from ([`outline_art_with`]), holding
@@ -1263,7 +1325,10 @@ fn hoist_copies(art: &mut Node) {
/// [`reshape_leaves_carrying`] whose paths keep to `budget` together, or to what they cost; with
/// `apart`, a Transform effect's copies of each path are objects
/// of their own ([`copy_leaf`]) whatever paints them, as Expand Appearance makes them. A live-effect
/// of their own ([`copy_leaf`]) whatever paints them, as Expand Appearance makes them. With `rows`,
/// so are the copies of a path with a fill or stroke whose raster effects follow a Transform effect
/// ([`crate::raster::follows`]), and each copy's fills and strokes carry those raster effects moved,
/// turned, reflected and scaled with it ([`follow_copies`]). A live-effect
/// plug-in that paints what it returns makes each path a group of its pieces ([`paint_leaf`]),
/// whose swatches and patterns must be in `doc` (without one, pieces that name one are refused).
/// Returns how gradients that paint the art as a whole follow the effects, and the Transform
@@ -1274,7 +1339,14 @@ fn hoist_copies(art: &mut Node) {
/// type and live objects in it outlined and evaluated first ([`outlined_members`]). When a mask
/// stays as it was, or a Transform effect makes fewer copies than it asks for, art with linked
/// masks keeps its shape under that effect.
fn reshape_leaves_apart(art: &mut Node, fx: &[&Effect], owner: &[Effect], budget: Budget, apart: bool, doc: Option<&Document>) -> crate::Carry {
fn reshape_leaves_apart(
art: &mut Node,
fx: &[&Effect],
owner: &[Effect],
budget: Budget,
(apart, rows): (bool, bool),
doc: Option<&Document>,
) -> crate::Carry {
let mut whole = crate::Carry::default();
if fx.is_empty() {
return whole;
@@ -1311,7 +1383,7 @@ fn reshape_leaves_apart(art: &mut Node, fx: &[&Effect], owner: &[Effect], budget
let params = merged_params(&e.id, &e.params);
// Where a live-effect plug-in sits, which it is listed by when it is deferred.
let effect = owner.iter().position(|x| std::ptr::eq(x, *e)).or_else(|| listed.iter().position(|x| std::ptr::eq(*x, *e)));
let step = Step { e, params: &params, bounds, seed, effect, apart, doc, wholes: &wholes, held };
let step = Step { e, params: &params, bounds, seed, effect, apart, rows, doc, wholes: &wholes, held };
// Art with linked masks keeps its shape under an effect that a mask in it could not take
// as the art it masks did, so no mask is left apart from its art.
let before = masked.then(|| (art.clone(), used));
@@ -1355,6 +1427,7 @@ struct Step<'a> {
seed: u64,
effect: Option<usize>,
apart: bool,
rows: bool,
doc: Option<&'a Document>,
wholes: &'a HashMap<NodeId, bool>,
held: bool,
@@ -1519,8 +1592,12 @@ impl Step<'_> {
// make together; and Expand Appearance (`apart`) makes each copy an object.
// Fills and strokes that stack paint each copy below the one before (#5920, #6316).
// Each copy of a path with a linked mask carries the mask, moved with it.
// With `rows`, each copy carries the raster effects of its fills and strokes,
// following that copy's map.
let rows = self.rows && copies > 0 && leaf.appearance.items.iter().any(follows_row_raster);
let separate = copies > 0
&& (self.apart
|| rows
|| leaf.appearance.has_unplaced_gradient()
|| leaf.appearance.has_placed_gradient()
|| paints_copies_apart(&leaf.appearance, rule)
@@ -1528,9 +1605,12 @@ impl Step<'_> {
// The copies of a path replace it by a group of them, the path included.
let copied = |leaf: &Node| leaf.children().map_or(0, Vec::len);
if options.reach_appearance() {
let (made, moved) = transform_leaf(leaf, &path, map, copies, options, room, raster_map.is_some(), None);
let (made, moved) = transform_leaf(leaf, &path, map, copies, options, room, raster_map.is_some() || rows, None);
*used = used.minus(before).plus(made);
took |= moved;
if moved && rows {
follow_copies(leaf, map, None);
}
if moved {
// With Transform Objects off the path stays, and its mask takes the
// effect's stroke and pattern changes as its own art.
@@ -1546,6 +1626,9 @@ impl Step<'_> {
if separate {
let scaling = vectorcraft_doc::Scaling { keep_fit_when_flat: true, ..Default::default() };
let made = copy_leaf(leaf, &path, m, copies, scaling, room, None);
if rows {
follow_copies(leaf, m, None);
}
*used = used.minus(before).plus(made);
took = true;
moved_ids.insert(leaf.id);
@@ -1937,7 +2020,7 @@ fn transform_leaf(
kept: Kept,
) -> (Budget, bool) {
let mut scaling = copy_scaling(options);
if follows && copies == 0 {
if follows {
scaling.effects = options.strokes.then_some(scale_unfollowed as fn(&mut Effect, f64));
}
if !options.objects {
@@ -2253,7 +2336,8 @@ fn paint_piece(
/// Every path and compound path under `art` (other than clipping paths) with a fill or stroke whose
/// own Transform effect has Transform Patterns or Scale Strokes & Effects on
/// ([`item_transform_options`]), or whose own live-effect plug-in paints what it returns
/// ([`item_transform_options`]) or makes copies that carry the raster effects before it
/// ([`copied_row_raster_at`]), or whose own live-effect plug-in paints what it returns
/// ([`painted_plugin`]), made into a group of objects of its own ([`transform_item_leaf`]). The
/// new paths keep to one [`Budget::EFFECTS`] together (or to what `art` costs, when that is more).
/// The swatches and patterns painted pieces name must be in `doc`; without one they may name none.
@@ -2270,9 +2354,20 @@ fn makes_piece(e: &Effect) -> bool {
reaches_appearance(e) || painted_plugin(e).is_some()
}
/// Does `item` paint and carry an effect that [`makes_piece`]?
/// Where the fill's or stroke's own effects `fx` make its piece of a path an object of its own: the
/// index of the first effect that [`makes_piece`], or of the Transform effect whose copies carry the
/// raster effects before it ([`copied_row_raster_at`]), whichever is listed first.
fn piece_at(fx: &[Effect]) -> Option<usize> {
let copied = copied_row_raster_at(fx);
match fx.iter().position(makes_piece) {
Some(at) => Some(copied.map_or(at, |t| t.min(at))),
None => copied,
}
}
/// Does `item` paint and carry an effect that makes its piece an object of its own ([`piece_at`])?
fn item_makes_piece(item: &AppearanceItem) -> bool {
crate::paints(item) && item.effects().iter().any(makes_piece)
crate::paints(item) && piece_at(item.effects()).is_some()
}
/// `leaf`, a path or compound path with a fill or stroke whose own Transform effect has Transform
@@ -2282,12 +2377,17 @@ fn item_makes_piece(item: &AppearanceItem) -> bool {
/// as [`transform_leaf`] transforms an object with that effect's map, copies and options, so the
/// stroke's weight and dashes, the distances of the effects before the Transform effect and its
/// pattern follow the map, and the raster effects before it that follow it take their followed
/// values ([`follow_piece`]). The effects after it keep their values and apply to what it made
/// values ([`follow_piece`]), on each copy the values that copy's map gives them
/// ([`follow_copies`]). The effects after it keep their values and apply to what it made
/// ([`keep_listed`]), and with Transform Objects off so do the effects before it. The reference box
/// is that geometry's bounds and the seed is the leaf's id, as the renderer draws a fill's or
/// stroke's own effects. The geometry effects after the Transform effect then
/// stroke's own effects. A fill or stroke whose first such Transform effect makes copies that carry
/// the raster effects before it ([`copied_row_raster_at`]) becomes a path of its own the same way,
/// with neither option. The geometry effects after the Transform effect then
/// apply to the transformed path and its copies as one piece ([`transform_piece`]), and its other
/// effects stay on each of them. The other fills and strokes stay together on paths of the leaf's
/// effects stay on each of them, except that without either option the raster effects after a
/// Transform effect that makes copies paint once around all of them ([`lift_later_raster`]). The
/// other fills and strokes stay together on paths of the leaf's
/// geometry between them, with their own effects. `max` is the budget of the whole art and `used`
/// what it has spent.
///
@@ -2333,7 +2433,7 @@ fn transform_item_leaf(leaf: &mut Node, max: Budget, used: &mut Budget, doc: Opt
let later = |i: usize| (i + 1..transformed.len()).filter(|&j| transformed[j] || j == i + 1 || transformed[j - 1]).count();
for (i, item) in original.appearance.items.iter().enumerate() {
let fx = item.effects();
let Some(at) = fx.iter().position(makes_piece).filter(|_| crate::paints(item)) else {
let Some(at) = piece_at(fx).filter(|_| crate::paints(item)) else {
plain.push(item.clone());
continue;
};
@@ -2411,13 +2511,24 @@ fn transform_item_leaf(leaf: &mut Node, max: Budget, used: &mut Budget, doc: Opt
set_geometry(&mut p, g.clone(), rule);
let after = kept_before.len();
let keep = |k: usize| k >= after || !options.objects;
let (made, moved) = transform_leaf(&mut p, &g, map, copies, options, room, false, Some((&rest, &keep)));
*used = used.plus(made);
let from = crate::raster::held_back(before);
if moved && !held_later {
// Each copy carries the raster effects before the Transform effect, following that copy's
// map, unless a Transform effect before or after it holds them back.
let copied = copies > 0 && !held_later && from == 0;
let (made, moved) = transform_leaf(&mut p, &g, map, copies, options, room, copied, Some((&rest, &keep)));
*used = used.plus(made);
if moved && copied {
follow_copies(&mut p, map, Some(0..after));
} else if moved && !held_later {
follow_piece(&mut p, kept_before.get(from..).unwrap_or_default(), from, &fx[at]);
}
transform_piece(&mut p, (ctx.seed, i, &kept), crate::raster::held_back(&fx[..=at]), false, limit, used, doc);
// Without Transform Patterns and Scale Strokes & Effects, the raster effects after the
// Transform effect paint once around all the copies, as they paint around the one path of
// every copy.
if copies > 0 && !options.reach_appearance() {
lift_later_raster(&mut p, after);
}
pieces.push(Arc::new(p));
}
if !plain.is_empty() {
@@ -2468,6 +2579,7 @@ fn transform_piece(
count = count.max(item.effects().len());
}
});
let outer = held;
// The effects before a Transform effect among the piece's effects that makes copies or moves at
// random are held back from the Transform effects before it too.
let mut held = held;
@@ -2488,7 +2600,7 @@ fn transform_piece(
let from = held.min(j);
let mut holds = false;
let stage = vectorcraft_plugins::deferred::Stage { object: seed, effect: kept.get(j).copied().unwrap_or(j), item: Some(source) };
let at = PieceStage { j, from, seed, bounds, doc, stage };
let at = PieceStage { j, from, outer, seed, bounds, doc, stage };
// Stage `j` on `leaf`, a path `used` counts at `piece_cost` when `share`: whether `used`
// counts each path it became so, or `None` when it stays as it was.
let mut on_leaf = |leaf: &mut Node, share: bool| -> Option<Vec<bool>> {
@@ -2709,12 +2821,14 @@ thread_local! {
/// Where a stage of [`transform_piece`] runs: `j`, the index of its effect among the piece's
/// effects; `from`, the first of the effects before it whose raster effects follow a Transform
/// effect; the object's `seed`; the reference box `bounds` of all the piece's paths; the document
/// that painted pieces' swatches and patterns must be in; and the `stage` a deferred live-effect
/// plug-in is listed by.
/// effect; `outer`, how many of the piece's effects a Transform effect before them holds back; the
/// object's `seed`; the reference box `bounds` of all the piece's paths; the document that painted
/// pieces' swatches and patterns must be in; and the `stage` a deferred live-effect plug-in is
/// listed by.
struct PieceStage<'a> {
j: usize,
from: usize,
outer: usize,
seed: u64,
bounds: Rect,
doc: Option<&'a Document>,
@@ -2757,15 +2871,30 @@ fn piece_stage(leaf: &mut Node, e: &Effect, at: &PieceStage, (appearance, index)
let params = merged_params(&e.id, &e.params);
return paint_piece(leaf, &item, (appearance, index), (plugin, &params), at.bounds, room, at.doc, Some(at.stage));
}
if reaches_appearance(e) {
let copied = copies_carry(item.effects(), e, at);
if reaches_appearance(e) || copied {
let params = merged_params(&e.id, &e.params);
let (_, copies) = crate::distort::transform_map(at.bounds, &params, at.seed);
let options = crate::distort::TransformOptions::of(&params);
let map = crate::distort::transform_affine(at.bounds, &params, at.seed);
let j = at.j;
let keep = |k: usize| k > j || (k < j && !options.objects);
let (made, moved) = transform_leaf(leaf, &path, map, copies, options, room, false, Some((item.effects(), &keep)));
if moved {
let (made, moved) = transform_leaf(leaf, &path, map, copies, options, room, copied, Some((item.effects(), &keep)));
if moved && copied {
// Each copy's raster effects before the Transform effect follow that copy's map. The
// Transform effects before it have already moved them, so each run between two of
// them follows on its own.
let fx = item.effects();
let mut start = 0;
for k in 0..=j {
if k == j || fx.get(k).is_some_and(|f| f.id == "distort.transform") {
if start < k {
follow_copies(leaf, map, Some(start..k));
}
start = k + 1;
}
}
} else if moved {
follow_piece(leaf, was, at.from, e);
}
return Some(made);
@@ -2790,6 +2919,37 @@ fn piece_stage(leaf: &mut Node, e: &Effect, at: &PieceStage, (appearance, index)
Some(made)
}
/// Does Transform effect `e`, at stage `at` of [`transform_piece`] of a fill or stroke whose effects
/// are `fx`, make copies that each carry the raster effects listed before it, following that copy's
/// map ([`follow_copies`]), as the copies of the piece's first Transform effect do
/// ([`transform_item_leaf`])? It does when it makes copies with Transform Objects on, a visible
/// raster effect that follows a Transform effect ([`crate::raster::follows`]) is listed before it,
/// and no Transform effect that makes copies or moves at random holds those raster effects back:
/// none before the piece's effects, none listed before it after such a raster effect, and none
/// after it. Without Transform Patterns and Scale Strokes & Effects, every other visible effect
/// before it must also be a geometry effect or such a raster effect, and no visible raster effect
/// may be listed after it, as for [`copied_row_raster_at`].
fn copies_carry(fx: &[Effect], e: &Effect, at: &PieceStage) -> bool {
if !e.visible || e.id != "distort.transform" || at.outer > 0 {
return false;
}
let params = merged_params(&e.id, &e.params);
if !crate::distort::TransformOptions::of(&params).objects || crate::distort::transform_map(Rect::ZERO, &params, 0).1 == 0 {
return false;
}
let before = fx.get(..at.j).unwrap_or_default();
let after = fx.get(at.j + 1..).unwrap_or_default();
if crate::raster::held_back(before) > 0
|| !before.iter().any(|f| f.visible && crate::raster::follows(&f.id))
|| after.iter().any(crate::raster::holds_back)
{
return false;
}
reaches_appearance(e)
|| (before.iter().all(|f| !f.visible || is_geometry(&f.id) || crate::raster::follows(&f.id))
&& !after.iter().any(|f| f.visible && crate::is_raster(&f.id)))
}
/// Are `a` and `b` paths or compound paths that differ only in their fills and strokes?
fn same_path(a: &Node, b: &Node) -> bool {
let leaf = |n: &Node| matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. });
@@ -2862,6 +3022,52 @@ fn follow_piece(leaf: &mut Node, was: &[Effect], from: usize, t: &Effect) {
}
}
/// Make the raster effects that follow a Transform effect ([`crate::raster::follows`]) on the fills
/// and strokes of each copy [`copy_leaf`] made of `leaf` with map `m` follow that copy's map: the
/// copy `k` places below the original takes the linear part of `m` `k` times
/// ([`crate::raster::follow_contents`]), and the original, on top, keeps its effects. `range`, when
/// given, is which of each fill's or stroke's effects follow; the others keep their values.
fn follow_copies(leaf: &mut Node, m: Affine, range: Option<std::ops::Range<usize>>) {
let step = m.with_translation(vectorcraft_geom::Vec2::ZERO);
let Some(children) = leaf.children_mut() else { return };
let mut a = Affine::IDENTITY;
for c in children.iter_mut().rev().skip(1) {
a *= step;
for item in &mut Arc::make_mut(c).appearance.items {
let fx = item.effects_mut();
let fx = match &range {
Some(r) => fx.get_mut(r.clone()).unwrap_or_default(),
None => fx.as_mut_slice(),
};
crate::raster::follow_contents(fx, a, Affine::IDENTITY);
}
}
}
/// Move the raster effects from index `after` on of the fills and strokes of the paths under `p`,
/// a group of copies of one fill or stroke with the same effects, onto `p` itself, so they paint
/// once around all of the copies. The other effects stay where they are.
fn lift_later_raster(p: &mut Node, after: usize) {
if p.children().is_none() {
return;
}
let mut lifted: Option<Vec<Effect>> = None;
for_each_leaf(p, &mut |l| {
for item in &mut l.appearance.items {
let fx = item.effects_mut();
if fx.len() <= after {
continue;
}
let (raster, other): (Vec<Effect>, Vec<Effect>) = fx.split_off(after).into_iter().partition(|e| crate::is_raster(&e.id));
fx.extend(other);
lifted.get_or_insert(raster);
}
});
if let Some(raster) = lifted {
p.appearance.effects.extend(raster);
}
}
/// The bounds of each group of type's outlines under `n` ([`outline_text`]), `n` included, in
/// order. A group inside one of them is part of it.
fn type_outline_bounds(n: &Node, out: &mut Vec<Option<Rect>>) {
+46 -33
View File
@@ -5,7 +5,7 @@ use std::sync::Arc;
use serde_json::Value;
use vectorcraft_doc::color::{Color, Paint};
use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, FillLayer, Node, NodeId, NodeKind};
use vectorcraft_geom::{PathData, PathEl, Point, Rect, Vec2};
use vectorcraft_geom::{FillRule, PathData, PathEl, Point, Rect, Vec2};
use vectorcraft_three_d::{Edge, Revolve, SolidFaces};
use crate::solids::wireframe::{WireFace, wireframe_params};
@@ -105,6 +105,7 @@ pub fn revolve_options(p: &Value) -> Revolve {
shade: flag(p, "shade", true),
smooth_shading: true,
cap_ends: flag(p, "cap", true),
fill_rule: FillRule::NonZero,
curve_samples: None,
map_surface: false,
}
@@ -231,7 +232,7 @@ fn check_shadow<'a>(p: &Value, paths: impl IntoIterator<Item = &'a PathData>, b:
return Ok(());
}
let mut caster = vectorcraft_three_d::ShadowCaster::new();
paths.into_iter().try_for_each(|path| caster.revolve(path, vectorcraft_geom::FillRule::NonZero, b, options).map(|_| ()))
paths.into_iter().try_for_each(|path| caster.revolve(path, options.fill_rule, b, options).map(|_| ()))
}
/// [`validate_revolve`] for a Revolve with parameters `p` at index `index` of the effects of
@@ -418,7 +419,7 @@ fn cast_surface(
None => {
#[cfg(test)]
crate::solids::SOLIDS_BUILT.with(|n| n.set(n.get() + 1));
caster.revolve(path, vectorcraft_geom::FillRule::NonZero, b, options)
caster.revolve(path, options.fill_rule, b, options)
}
}
}
@@ -449,7 +450,7 @@ fn group_shadow(
if !ink.casts() {
continue;
}
let faces = cast_surface(&mut caster, &s.path, b, options, kept)?;
let faces = cast_surface(&mut caster, &s.path, b, Revolve { fill_rule: s.rule, ..options }, kept)?;
cast.push((s.scopes.as_slice(), ink, faces));
}
Ok(crate::solids::shadow::scoped_art(id, &caster, settings, cast, crate::solids::has_masks(shapes)))
@@ -703,13 +704,16 @@ fn in_order<T>(items: Vec<T>, order: &[usize]) -> Vec<T> {
order.iter().filter_map(|&k| slots.get_mut(k).and_then(Option::take)).collect()
}
/// A surface of one object about the bounds of `path`, built with options derived from `fx`, and
/// when `fx` casts a shadow from it, the faces it is cast from ([`surface`]). `copies` is the count
/// [`surface`] adds to; its graphics take the symbols of `doc`.
/// A surface of one object about the bounds of `path`, filled with `rule`, built with options
/// derived from `fx` ([`rule_options`]), and when `fx` casts a shadow from it, the faces it is cast
/// from ([`surface`]). `copies` is the count [`surface`] adds to; its graphics take the symbols of
/// `doc`.
#[allow(clippy::too_many_arguments)]
fn object_surface(
doc: Option<&Document>,
n: &Node,
path: &PathData,
rule: FillRule,
fx: &Effect,
item: &AppearanceItem,
expand: bool,
@@ -718,10 +722,16 @@ fn object_surface(
let b = path.bounds()?;
let (paint, opacity, blend) = paint_of(item);
let cast = casts(fx, opacity);
surface(doc, n, path, b, fx_options(fx), fx, paint, opacity, blend, expand, copies, cast)
surface(doc, n, path, b, rule_options(fx, rule), fx, paint, opacity, blend, expand, copies, cast)
.map(|(_, art, kept, seal)| (sealed_surface(n.id, art, seal), kept))
}
/// The options effect `fx` sweeps the surface of a profile filled with `rule` with: its cut sides
/// leave open the holes `rule` leaves in the profile.
fn rule_options(fx: &Effect, rule: FillRule) -> Revolve {
Revolve { fill_rule: rule, ..fx_options(fx) }
}
/// The paint of a graphic's solid color `c` on `face`, shaded as the face shades a solid fill of
/// that color: across the face with its smooth shading, under colored lights (`colored`) with
/// their color.
@@ -840,13 +850,13 @@ pub(crate) fn revolve_face_paths(doc: Option<&Document>, n: &Node) -> Result<cra
let options = shared_options(&shapes, fx_options(fx))?;
let mut out = vec![];
for s in shapes.iter().filter(|s| surface_item(&s.items).is_some()) {
out.extend(faces(&s.path, b, fx, options)?);
out.extend(faces(&s.path, b, fx, Revolve { fill_rule: s.rule, ..options })?);
}
// In wireframe mode the canvas draws no shadow.
let shadow = if crate::solids::renders_wireframe(fx) { vec![] } else { group_shadow(n.id, fx, &shapes, b, options, vec![])? };
return Ok((out, shadow));
}
let (path, _) = object_profile(n, "Revolve")?;
let (path, rule) = object_profile(n, "Revolve")?;
let ctx = GeomContext::of(n);
if let Some(index) = n.appearance.effects.iter().position(|e| e.visible && is_revolve(&e.id)) {
let Some(fx) = n.appearance.effects.get(index) else { return Ok((vec![], vec![])) };
@@ -854,8 +864,8 @@ pub(crate) fn revolve_face_paths(doc: Option<&Document>, n: &Node) -> Result<cra
let paints = solid_paints(n);
let item = surface_item(&paints).ok_or("the revolved object has no fill or stroke")?;
let b = path.bounds().ok_or("Revolve requires a shape with at least two anchors")?;
let surface = faces(&path, b, fx, fx_options(fx))?;
let shadow = if crate::solids::renders_wireframe(fx) { None } else { shadow_of(n.id, fx, &path, item, b, fx_options(fx), None)? };
let surface = faces(&path, b, fx, rule_options(fx, rule))?;
let shadow = if crate::solids::renders_wireframe(fx) { None } else { shadow_of(n.id, fx, &path, item, b, rule_options(fx, rule), None)? };
return Ok((surface, shadow.into_iter().map(Arc::new).collect()));
}
let path = geometry(&path, &n.appearance.effects, &ctx);
@@ -866,7 +876,7 @@ pub(crate) fn revolve_face_paths(doc: Option<&Document>, n: &Node) -> Result<cra
{
let p = geometry(&path, item.effects().get(..index).unwrap_or_default(), &ctx.item(item));
let b = p.bounds().ok_or("Revolve requires a shape with at least two anchors")?;
let surface = faces(&p, b, fx, fx_options(fx))?;
let surface = faces(&p, b, fx, rule_options(fx, rule))?;
out.extend(crate::solids::wireframe::reshaped(surface, item.effects().get(index + 1..).unwrap_or_default(), &GeomContext { doc, ..ctx }));
}
}
@@ -884,13 +894,14 @@ fn wire_faces(path: &PathData, b: Rect, fx: &Effect, options: Revolve) -> Result
Ok(vectorcraft_three_d::revolve(path, b, options)?.iter().map(|f| WireFace { path: f.path(), stroke: SEAM_WIDTH }).collect())
}
/// The art Revolve `fx` in wireframe mode draws for object `id` from the profiles `paths`, all swept
/// about the bounds `b` with `options`: the edges of their faces ([`crate::solids::wireframe::wire_art`]).
/// `None` when a profile can't be swept or past the edge limit, when the canvas draws the source art.
fn wire_art<'a>(id: NodeId, paths: impl IntoIterator<Item = &'a PathData>, b: Rect, fx: &Effect, options: Revolve) -> Option<Arc<Node>> {
/// The art Revolve `fx` in wireframe mode draws for object `id` from the profiles `paths`, each with
/// its fill rule, all swept about the bounds `b` with `options`: the edges of their faces
/// ([`crate::solids::wireframe::wire_art`]). `None` when a profile can't be swept or past the edge
/// limit, when the canvas draws the source art.
fn wire_art<'a>(id: NodeId, paths: impl IntoIterator<Item = (&'a PathData, FillRule)>, b: Rect, fx: &Effect, options: Revolve) -> Option<Arc<Node>> {
let mut faces = vec![];
for path in paths {
faces.extend(wire_faces(path, b, fx, options).ok()?.into_iter().map(|f| f.path));
for (path, rule) in paths {
faces.extend(wire_faces(path, b, fx, Revolve { fill_rule: rule, ..options }).ok()?.into_iter().map(|f| f.path));
}
crate::solids::wireframe::wire_art(id, &faces)
}
@@ -940,11 +951,11 @@ fn art(doc: Option<&Document>, n: &Node, expand: bool) -> Option<Node> {
let expand = expand && !n.appearance.effects.iter().skip(index + 1).any(|e| e.visible && is_geometry(&e.id));
if crate::solids::renders_wireframe(fx) {
// In wireframe mode the edges of the faces, with no shadow.
children.push(wire_art(n.id, [&path], path.bounds()?, fx, fx_options(fx))?);
children.push(wire_art(n.id, [(&path, rule)], path.bounds()?, fx, fx_options(fx))?);
} else {
let (surface, kept) = object_surface(doc, n, &path, fx, item, expand, &mut copies)?;
let (surface, kept) = object_surface(doc, n, &path, rule, fx, item, expand, &mut copies)?;
if let Some(b) = path.bounds()
&& let Some(shadow) = shadow_of(n.id, fx, &path, item, b, fx_options(fx), kept).ok()?
&& let Some(shadow) = shadow_of(n.id, fx, &path, item, b, rule_options(fx, rule), kept).ok()?
{
children.push(Arc::new(shadow));
}
@@ -970,18 +981,19 @@ fn art(doc: Option<&Document>, n: &Node, expand: bool) -> Option<Node> {
let p = geometry(&path, item.effects().get(..index)?, &ctx.item(original));
let expand = expand && !item.effects().iter().skip(index + 1).any(|e| e.visible && is_geometry(&e.id));
if crate::solids::renders_wireframe(fx) {
let mut art = wire_art(n.id, [&p], p.bounds()?, fx, fx_options(fx))?;
let mut art = wire_art(n.id, [(&p, rule)], p.bounds()?, fx, fx_options(fx))?;
Arc::make_mut(&mut art).appearance.effects =
item.effects().iter().skip(index + 1).filter(|e| !is_revolve(&e.id)).cloned().collect();
children.push(art);
continue;
}
let (mut art, kept) = object_surface(doc, n, &p, fx, item, expand, &mut copies)?;
let (mut art, kept) = object_surface(doc, n, &p, rule, fx, item, expand, &mut copies)?;
art.appearance.effects = item.effects().iter().skip(index + 1).filter(|e| !is_revolve(&e.id)).cloned().collect();
if let Some(b) = p.bounds()
&& let Some(mut shadow) = shadow_of(n.id, fx, &p, item, b, fx_options(fx), kept).ok()?
&& let Some(mut shadow) = shadow_of(n.id, fx, &p, item, b, rule_options(fx, rule), kept).ok()?
{
shadow.appearance.effects = art.appearance.effects.clone();
// The shadow keeps its own blur (the light's Softness) below the later effects.
shadow.appearance.effects.extend(art.appearance.effects.iter().cloned());
shadows.push(Arc::new(shadow));
}
children.push(Arc::new(art));
@@ -1127,7 +1139,7 @@ fn group_art(doc: Option<&Document>, n: &Node, expand: bool) -> Option<Node> {
let options = shared_options(&shapes, fx_options(fx)).ok()?;
if crate::solids::renders_wireframe(fx) {
// In wireframe mode the edges of every member's faces, with no shadow.
let paths = shapes.iter().filter(|s| surface_item(&s.items).is_some()).map(|s| &s.path);
let paths = shapes.iter().filter(|s| surface_item(&s.items).is_some()).map(|s| (&s.path, s.rule));
let mut art = n.clone();
art.kind = NodeKind::Group { children: vec![wire_art(n.id, paths, b, fx, options)?], clip: false };
art.appearance = Appearance { effects: past_effect(&n.appearance.effects, index), ..Default::default() }.into();
@@ -1157,6 +1169,7 @@ fn group_art(doc: Option<&Document>, n: &Node, expand: bool) -> Option<Node> {
let expand = expand && s.scopes.is_empty();
let doc = doc.filter(|_| longest == Some(k));
let cast = casts(fx, opacity * s.opacity);
let options = Revolve { fill_rule: s.rule, ..options };
let (depths, art, faces, seal) = surface(doc, n, &s.path, b, options, fx, paint, opacity, blend, expand, &mut copies, cast)?;
surfaces.push((depths, art, s.scopes.as_slice()));
kept.push(faces);
@@ -2088,7 +2101,7 @@ mod tests {
let mut fx = crate::new_effect(id, &json!({})).unwrap();
fx.params = params.clone();
let n = profile_node();
let (path, _) = profile(&n).unwrap();
let (path, rule) = profile(&n).unwrap();
let b = path.bounds().unwrap();
let mut half = n.clone();
if let AppearanceItem::Fill(f) = &mut half.appearance.items[0] {
@@ -2096,9 +2109,9 @@ mod tests {
}
for n in [n, half] {
let item = surface_item(&n.appearance.items).unwrap();
let (_, kept) = object_surface(None, &n, &path, &fx, item, false, &mut Copies::default()).unwrap();
let drawn = shadow_of(n.id, &fx, &path, item, b, fx_options(&fx), kept).unwrap();
let alone = shadow_of(n.id, &fx, &path, item, b, fx_options(&fx), None).unwrap();
let (_, kept) = object_surface(None, &n, &path, rule, &fx, item, false, &mut Copies::default()).unwrap();
let drawn = shadow_of(n.id, &fx, &path, item, b, rule_options(&fx, rule), kept).unwrap();
let alone = shadow_of(n.id, &fx, &path, item, b, rule_options(&fx, rule), None).unwrap();
assert!(alone.is_some() || id == CLASSIC_REVOLVE, "{id} {params}");
assert_eq!(format!("{drawn:?}"), format!("{alone:?}"), "{id} {params}");
}
@@ -2164,11 +2177,11 @@ mod tests {
if let AppearanceItem::Fill(f) = &mut n.appearance.items[0] {
f.opacity = bad;
}
let (path, _) = profile(&n).unwrap();
let (path, rule) = profile(&n).unwrap();
let b = path.bounds().unwrap();
let item = surface_item(&n.appearance.items).unwrap();
assert!(!casts(&fx, bad), "{bad}: the surface keeps no faces for a shadow");
let (_, kept) = object_surface(None, &n, &path, &fx, item, false, &mut Copies::default()).unwrap();
let (_, kept) = object_surface(None, &n, &path, rule, &fx, item, false, &mut Copies::default()).unwrap();
assert_eq!(shadow_of(n.id, &fx, &path, item, b, fx_options(&fx), kept).unwrap(), None, "{bad} drawn");
assert_eq!(shadow_of(n.id, &fx, &path, item, b, fx_options(&fx), None).unwrap(), None, "{bad} alone");
let shadows = group_shadows(&group(bad));
+5 -1
View File
@@ -2177,7 +2177,11 @@ pub fn solid_art_in(doc: Option<&Document>, n: &Node) -> Option<Node> {
Arc::make_mut(&mut art).appearance.effects = later.clone();
art
};
shadows.extend(shadow.into_iter().map(with_later));
// A shadow keeps its own blur (the light's Softness) below the later effects.
shadows.extend(shadow.into_iter().map(|mut art| {
Arc::make_mut(&mut art).appearance.effects.extend(later.iter().cloned());
art
}));
children.extend(surfaces.into_iter().map(with_later));
} else {
let flat = Appearance { items: vec![item.clone()], ..Default::default() };
+17 -8
View File
@@ -1,12 +1,12 @@
//! The shadow of the 3D and Materials effects (Extrude & Bevel, Inflate, Rotate and Revolve): the
//! `shadow` switch with `shadowPosition`, `shadowDistance` and `shadowBounds`, and the shape it
//! draws behind the solids.
//! draws behind the solids, blurred by the first light's Softness.
use std::ops::Range;
use std::sync::Arc;
use serde_json::Value;
use serde_json::{Value, json};
use vectorcraft_doc::color::{BlendMode, Color, Paint};
use vectorcraft_doc::{Appearance, AppearanceItem, FillLayer, Node, NodeId};
use vectorcraft_doc::{Appearance, AppearanceItem, Effect, FillLayer, Node, NodeId};
use vectorcraft_three_d::{Shadow, ShadowCaster, ShadowPlane, ShadowPosition};
use super::Scope;
@@ -15,15 +15,21 @@ use crate::util::{flag, num, text};
/// The shadow's paint: black at this opacity. VectorCraft's own values.
const SHADOW_OPACITY: f32 = 0.5;
/// Blur radii below this, in points, leave the shadow hard-edged.
const MIN_BLUR: f64 = 0.01;
/// The shadow `p` asks for, or `None` with the switch off or when the first light lights nothing
/// (Shading is off or its intensity is 0), so that no shadow is built.
/// (Shading is off or its intensity is 0), so that no shadow is built. Its softness is the first
/// light's.
pub(crate) fn options(p: &Value) -> Option<Shadow> {
let intensity = crate::lighting::lights(p).and_then(|l| l.iter().next().map(|l| l.intensity)).unwrap_or_else(|| num(p, "lightIntensity", 80.0));
let first = crate::lighting::lights(p).and_then(|l| l.iter().next().copied());
let intensity = first.map_or_else(|| num(p, "lightIntensity", 80.0), |l| l.intensity);
let lit = flag(p, "shade", true) && intensity > 0.0;
(lit && flag(p, "shadow", false)).then(|| Shadow {
position: ShadowPosition::parse(text(p, "shadowPosition", "behind")).unwrap_or_default(),
distance: num(p, "shadowDistance", 0.0) / 100.0,
bounds: num(p, "shadowBounds", 100.0) / 100.0,
softness: first.map_or_else(|| num(p, "lightSoftness", 0.0) / 100.0, |l| l.softness),
})
}
@@ -64,8 +70,9 @@ pub(crate) fn casts(opacity: f32) -> bool {
}
/// The shadow of the faces in `caster` as a path of object `id`, cast by art in `ink`: filled
/// black at [`SHADOW_OPACITY`] times its opacity, in its blending mode, with the nonzero rule;
/// `None` when it casts nothing.
/// black at [`SHADOW_OPACITY`] times its opacity, in its blending mode, with the nonzero rule, and
/// with the light's Softness a Gaussian Blur of the plane's radius ([`ShadowPlane::blur`]), which
/// is drawn, measured, exported and expanded as that effect is; `None` when it casts nothing.
pub(crate) fn art(id: NodeId, caster: &ShadowCaster, shadow: Shadow, ink: Ink) -> Option<Node> {
let all = 0..caster.len();
let all = std::slice::from_ref(&all);
@@ -78,7 +85,9 @@ fn piece(id: NodeId, caster: &ShadowCaster, plane: &ShadowPlane, faces: &[Range<
let mut fill = FillLayer::new(Paint::solid(Color::BLACK));
fill.opacity = SHADOW_OPACITY * ink.opacity.clamp(0.0, 1.0);
fill.blend = ink.blend;
Some(Node::path(id, path, Appearance { items: vec![AppearanceItem::Fill(fill)], ..Default::default() }))
let blur = plane.blur();
let effects = if blur >= MIN_BLUR { vec![Effect { id: "blur.gaussian".into(), params: json!({"radius": blur}), visible: true }] } else { vec![] };
Some(Node::path(id, path, Appearance { items: vec![AppearanceItem::Fill(fill)], effects, ..Default::default() }))
}
/// Whether `a` and `b` are the same objects' scopes (each member holds its own copies).
+54
View File
@@ -87,6 +87,40 @@ fn the_shadow_moves_with_its_settings() {
}
}
/// The radius of the Gaussian Blur on shadow `n`; `None` without one.
fn shadow_blur(n: &Node) -> Option<f64> {
match n.appearance.effects.as_slice() {
[] => None,
[e] if e.id == "blur.gaussian" && e.visible => e.params["radius"].as_f64(),
other => panic!("unexpected effects on the shadow: {other:?}"),
}
}
/// The first light's Softness blurs the shadow, more with Softness and with Distance from Object;
/// at 0 % it stays the hard-edged path. A list of lights takes the first light's Softness.
#[test]
fn the_first_lights_softness_blurs_the_shadow() {
for id in CASTING {
let blur = |params: Value| {
let mut n = square_node(1, 0.0);
n.appearance.effects.push(crate::new_effect(id, &params).unwrap());
let lit = art(&n, id).unwrap();
let shadow = &lit.children().unwrap()[0];
assert!(is_shadow(shadow), "{id} {params}");
shadow_blur(shadow)
};
assert_eq!(blur(json!({"shadow": true})), None, "{id}: hard at 0 %");
let soft = blur(json!({"shadow": true, "lightSoftness": 50})).unwrap_or_else(|| panic!("{id}"));
let softer = blur(json!({"shadow": true, "lightSoftness": 100})).unwrap();
let far = blur(json!({"shadow": true, "lightSoftness": 100, "shadowDistance": 100})).unwrap();
assert!(soft > 0.0 && softer > soft && far > softer, "{id}: {soft} {softer} {far}");
let first = json!({"shadow": true, "lightSoftness": 0, "lights": [{"softness": 100}, {"softness": 0}]});
assert_eq!(blur(first), Some(softer), "{id}: the first light's");
let second = json!({"shadow": true, "lightSoftness": 100, "lights": [{"softness": 0}, {"softness": 100}]});
assert_eq!(blur(second), None, "{id}: only the first light casts");
}
}
#[test]
fn shadow_settings_out_of_range_or_of_the_wrong_kind_are_refused() {
for id in CASTING {
@@ -203,6 +237,26 @@ fn the_shadows_of_every_fill_go_behind_every_fill_s_solid() {
}
}
/// A fill's own 3D effect blurs its shadow by the light's Softness too, and the effects after it
/// in the fill's list follow the blur.
#[test]
fn a_fills_own_3d_effect_keeps_the_blur_below_its_later_effects() {
for id in CASTING {
for later in [None, Some(crate::new_effect("distort.roughen", &json!({})).unwrap())] {
let mut n = square_node(1, 0.0);
let fill = n.appearance.items.iter_mut().find(|i| matches!(i, AppearanceItem::Fill(_))).unwrap();
fill.effects_mut().push(crate::new_effect(id, &json!({"shadow": true, "lightSoftness": 100})).unwrap());
fill.effects_mut().extend(later.clone());
let lit = art(&n, id).unwrap_or_else(|| panic!("{id}"));
let shadow = &lit.children().unwrap()[0];
assert!(is_shadow(shadow), "{id}");
let ids: Vec<&str> = shadow.appearance.effects.iter().map(|e| e.id.as_str()).collect();
let want: Vec<&str> = std::iter::once("blur.gaussian").chain(later.as_ref().map(|e| e.id.as_str())).collect();
assert_eq!(ids, want, "{id}");
}
}
}
#[test]
fn expand_appearance_keeps_the_shadow_as_a_path() {
for id in CASTING {
+28 -16
View File
@@ -8,7 +8,8 @@
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use resvg::{tiny_skia, usvg};
use craft_svg::tree::draw::{resvg, tiny_skia};
use craft_svg::tree::usvg;
use serde_json::Value;
use usvg::roxmltree;
use vectorcraft_doc::SvgFilter;
@@ -624,17 +625,27 @@ fn write_drop_shadow(n: roxmltree::Node, input: &str, result: Option<&str>, name
/// first bytes whatever its `data:` URL says, of at most [`MAX_IMAGE_PIXELS`] pixels by its header.
/// `None` for anything else, SVG and compressed SVG included.
fn raster_image_sized(data: Arc<Vec<u8>>) -> Option<(usvg::ImageKind, u64)> {
let format = image::guess_format(&data).ok()?;
let (w, h) = image::ImageReader::with_format(std::io::Cursor::new(data.as_slice()), format).into_dimensions().ok()?;
let format = craft_image_codecs::detect(&data)?;
let (w, h) = match format {
craft_image_codecs::Format::Png => {
if data.len() < 24 || &data[..8] != b"\x89PNG\r\n\x1a\n" || &data[12..16] != b"IHDR" {
return None;
}
(u32::from_be_bytes(data[16..20].try_into().ok()?), u32::from_be_bytes(data[20..24].try_into().ok()?))
}
craft_image_codecs::Format::Jpeg => craft_image_codecs::jpeg_info(&data).map(|j| (j.width, j.height))?,
craft_image_codecs::Format::Gif | craft_image_codecs::Format::WebP => craft_image_codecs::probe_size(&data).ok()?,
_ => return None,
};
let pixels = u64::from(w) * u64::from(h);
if pixels == 0 || pixels > MAX_IMAGE_PIXELS {
return None;
}
let kind = match format {
image::ImageFormat::Png => usvg::ImageKind::PNG(data),
image::ImageFormat::Jpeg => usvg::ImageKind::JPEG(data),
image::ImageFormat::Gif => usvg::ImageKind::GIF(data),
image::ImageFormat::WebP => usvg::ImageKind::WEBP(data),
craft_image_codecs::Format::Png => usvg::ImageKind::PNG(data),
craft_image_codecs::Format::Jpeg => usvg::ImageKind::JPEG(data),
craft_image_codecs::Format::Gif => usvg::ImageKind::GIF(data),
craft_image_codecs::Format::WebP => usvg::ImageKind::WEBP(data),
_ => return None,
};
Some((kind, pixels))
@@ -1636,7 +1647,6 @@ fn on_canvas(data: &[u8], w: usize, h: usize, cw: u32, ch: u32, to_canvas: Affin
/// The pixels of `data` (premultiplied RGBA8, `w` wide) in columns x0..x1 and rows y0..y1, as a PNG.
fn png_of(data: &[u8], w: usize, x0: usize, y0: usize, x1: usize, y1: usize) -> Option<Vec<u8>> {
use image::ImageEncoder;
let px = data.as_chunks::<4>().0;
let mut straight = Vec::with_capacity((x1 - x0) * (y1 - y0) * 4);
for y in y0..y1 {
@@ -1646,14 +1656,16 @@ fn png_of(data: &[u8], w: usize, x0: usize, y0: usize, x1: usize, y1: usize) ->
straight.extend_from_slice(&[un(p[0]), un(p[1]), un(p[2]), p[3]]);
}
}
let mut png = vec![];
let encoder = image::codecs::png::PngEncoder::new_with_quality(
&mut png,
image::codecs::png::CompressionType::Fast,
image::codecs::png::FilterType::NoFilter,
);
encoder.write_image(&straight, (x1 - x0) as u32, (y1 - y0) as u32, image::ExtendedColorType::Rgba8).ok()?;
Some(png)
let raw = craft_image_codecs::Image::from_raw(
(x1 - x0) as u32,
(y1 - y0) as u32,
craft_image_codecs::ChannelLayout::Rgba,
craft_image_codecs::SampleType::U8,
straight,
)
.ok()?;
let opts = craft_image_codecs::EncodeOptions { png_compression: craft_image_codecs::PngCompression::Fast, ..Default::default() };
craft_image_codecs::encode(&raw, craft_image_codecs::Format::Png, &opts).ok()
}
/// `a` as an SVG `matrix(…)`.
+11 -8
View File
@@ -520,16 +520,15 @@ fn the_filter_is_drawn_and_written_from_its_filter_parts_alone() {
#[test]
fn filter_images_are_small_raster_images() {
fn png(w: u32, h: u32) -> Vec<u8> {
let mut out = vec![];
image::ImageEncoder::write_image(
image::codecs::png::PngEncoder::new(&mut out),
&vec![0; (w * h * 4) as usize],
let img = craft_image_codecs::Image::from_raw(
w,
h,
image::ExtendedColorType::Rgba8,
craft_image_codecs::ChannelLayout::Rgba,
craft_image_codecs::SampleType::U8,
vec![0; (w * h * 4) as usize],
)
.unwrap();
out
craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap()
}
let raster_image = |data| raster_image_sized(data).map(|(kind, _)| kind);
assert!(matches!(raster_image(Arc::new(png(2, 2))), Some(usvg::ImageKind::PNG(_))));
@@ -547,8 +546,12 @@ fn filter_images_are_small_raster_images() {
/// A 2 × 2 PNG whose header claims `w` × `h` pixels (its IHDR rewritten, with the CRC fixed).
fn png_claiming(w: u32, h: u32) -> Vec<u8> {
let mut out = vec![];
image::ImageEncoder::write_image(image::codecs::png::PngEncoder::new(&mut out), &[0; 16], 2, 2, image::ExtendedColorType::Rgba8).unwrap();
let mut out = craft_image_codecs::encode(
&craft_image_codecs::Image::from_raw(2, 2, craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, vec![0; 16]).unwrap(),
craft_image_codecs::Format::Png,
&craft_image_codecs::EncodeOptions::default(),
)
.unwrap();
out[16..20].copy_from_slice(&w.to_be_bytes());
out[20..24].copy_from_slice(&h.to_be_bytes());
let crc = crc32(&out[12..29]);
+26 -20
View File
@@ -15,10 +15,13 @@ fn fx(id: &str) -> Effect {
}
/// `img` encoded as `format`.
fn encoded(img: image::DynamicImage, format: image::ImageFormat) -> Vec<u8> {
let mut out = vec![];
img.write_to(&mut std::io::Cursor::new(&mut out), format).unwrap();
out
fn encoded(img: image::DynamicImage, format: craft_image_codecs::Format) -> Vec<u8> {
let (layout, data) = match format {
craft_image_codecs::Format::Jpeg => (craft_image_codecs::ChannelLayout::Rgb, img.to_rgb8().into_raw()),
_ => (craft_image_codecs::ChannelLayout::Rgba, img.to_rgba8().into_raw()),
};
let raw = craft_image_codecs::Image::from_raw(img.width(), img.height(), layout, craft_image_codecs::SampleType::U8, data).unwrap();
craft_image_codecs::encode(&raw, format, &craft_image_codecs::EncodeOptions::default()).unwrap()
}
/// A 100×100 RGBA image, transparent but for an opaque disc of radius 30 in its middle.
@@ -130,7 +133,7 @@ fn outline_object_follows_the_opaque_area_of_an_image_with_alpha() {
let gray_alpha = image::DynamicImage::ImageLumaA8(disc().to_luma_alpha8());
let deep = image::DynamicImage::ImageRgba16(disc().to_rgba16());
for (name, img) in [("rgba", disc()), ("gray and alpha", gray_alpha), ("16 bits a channel", deep)] {
let (d, n) = image_doc(encoded(img, image::ImageFormat::Png), vec![stroke(vec![fx("path.outlineObject")])], 1);
let (d, n) = image_doc(encoded(img, craft_image_codecs::Format::Png), vec![stroke(vec![fx("path.outlineObject")])], 1);
let rows = row_bounds(&d, &n);
assert_eq!(rows.len(), 1, "{name}");
// The disc runs from 70 to 130; the frame from 50 to 150.
@@ -143,9 +146,9 @@ fn outline_object_follows_the_frame_of_an_image_without_transparency() {
let opaque = image::DynamicImage::ImageRgb8(image::RgbImage::from_pixel(100, 100, image::Rgb([0, 0, 255])));
let solid = image::DynamicImage::ImageRgba8(image::RgbaImage::from_pixel(100, 100, image::Rgba([0, 0, 255, 200])));
let formats = [
("jpeg", encoded(opaque.clone(), image::ImageFormat::Jpeg)),
("rgb png", encoded(opaque, image::ImageFormat::Png)),
("rgba png, every pixel more than half opaque", encoded(solid, image::ImageFormat::Png)),
("jpeg", encoded(opaque.clone(), craft_image_codecs::Format::Jpeg)),
("rgb png", encoded(opaque, craft_image_codecs::Format::Png)),
("rgba png, every pixel more than half opaque", encoded(solid, craft_image_codecs::Format::Png)),
];
for (name, bytes) in formats {
let (d, n) = image_doc(bytes, vec![stroke(vec![fx("path.outlineObject")])], 1);
@@ -165,7 +168,7 @@ fn convert_to_shape_keeps_the_frame_beside_outline_object() {
let mut fill = FillLayer::new(Paint::solid(Color::rgb(0.0, 1.0, 0.0)));
fill.effects = vec![rect.clone()];
let items = vec![AppearanceItem::Fill(fill), stroke(vec![fx("path.outlineObject")]), stroke(vec![rect, fx("path.outlineObject")])];
let (d, n) = image_doc(encoded(disc(), image::ImageFormat::Png), items, 2);
let (d, n) = image_doc(encoded(disc(), craft_image_codecs::Format::Png), items, 2);
let rows = row_bounds(&d, &n);
assert_eq!(rows.len(), 3, "{rows:?}");
assert!(near(rows[0], [50.0, 50.0, 150.0, 150.0], 1e-9), "{rows:?}");
@@ -179,7 +182,7 @@ fn convert_to_shape_keeps_the_frame_beside_outline_object() {
#[test]
fn a_transparent_image_gives_outline_object_nothing_to_paint() {
let clear = image::DynamicImage::ImageRgba8(image::RgbaImage::from_pixel(100, 100, image::Rgba([0, 0, 0, 100])));
let (d, n) = image_doc(encoded(clear, image::ImageFormat::Png), vec![stroke(vec![fx("path.outlineObject")])], 1);
let (d, n) = image_doc(encoded(clear, craft_image_codecs::Format::Png), vec![stroke(vec![fx("path.outlineObject")])], 1);
assert!(row_bounds(&d, &n).is_empty());
let art = reshape::reshape(Some(&d), &n, None).unwrap();
assert!(matches!(art.children().unwrap().as_slice(), [only] if matches!(only.kind, NodeKind::Image(_))));
@@ -190,7 +193,7 @@ fn the_outline_follows_the_images_own_pixels_and_placement() {
// Pixels kept on the image itself (art made outside a document), placed at half size.
let (_, mut n) = image_doc(vec![], vec![stroke(vec![fx("path.outlineObject")])], 1);
if let NodeKind::Image(im) = &mut n.kind {
im.pixels = Some(Arc::new(ImageBlob::new("image/png", encoded(disc(), image::ImageFormat::Png))));
im.pixels = Some(Arc::new(ImageBlob::new("image/png", encoded(disc(), craft_image_codecs::Format::Png))));
im.xf = Affine::translate((10.0, 20.0)) * Affine::scale(0.5);
}
let art = reshape::reshape(None, &n, None).unwrap();
@@ -206,7 +209,7 @@ fn an_off_center_outline_turns_and_reflects_with_a_smaller_copy_of_the_pixels()
let half = image::DynamicImage::ImageRgba8(image::RgbaImage::from_fn(60, 30, |x, y| {
image::Rgba([255, 0, 0, if (6..20).contains(&x) && (3..12).contains(&y) { 255 } else { 0 }])
}));
let (d, mut n) = image_doc(encoded(half, image::ImageFormat::Png), vec![stroke(vec![fx("path.outlineObject")])], 1);
let (d, mut n) = image_doc(encoded(half, craft_image_codecs::Format::Png), vec![stroke(vec![fx("path.outlineObject")])], 1);
let xf = Affine::translate((100.0, 40.0)) * Affine::rotate(std::f64::consts::FRAC_PI_2) * Affine::scale_non_uniform(-1.0, 1.0);
if let NodeKind::Image(im) = &mut n.kind {
(im.width, im.height, im.xf) = (120, 60, xf);
@@ -221,7 +224,7 @@ fn an_off_center_outline_turns_and_reflects_with_a_smaller_copy_of_the_pixels()
#[test]
fn an_image_in_a_group_exports_with_its_outline() {
let (mut d, n) = image_doc(encoded(disc(), image::ImageFormat::Png), vec![stroke(vec![fx("path.outlineObject")])], 1);
let (mut d, n) = image_doc(encoded(disc(), craft_image_codecs::Format::Png), vec![stroke(vec![fx("path.outlineObject")])], 1);
let l = d.layers[0].id;
d.remove(n.id).unwrap();
let g = d.alloc_id();
@@ -256,7 +259,7 @@ fn baked_strokes(d: &Document) -> Vec<Rect> {
fn an_image_under_a_clipping_mask_or_with_an_opacity_mask_exports_with_its_outline() {
let disc_outline = |paths: &[Rect]| matches!(paths, [b] if near(*b, [70.0, 70.0, 130.0, 130.0], 0.5));
// Under a clipping mask that covers the whole image.
let (mut d, n) = image_doc(encoded(disc(), image::ImageFormat::Png), vec![stroke(vec![fx("path.outlineObject")])], 1);
let (mut d, n) = image_doc(encoded(disc(), craft_image_codecs::Format::Png), vec![stroke(vec![fx("path.outlineObject")])], 1);
let l = d.layers[0].id;
d.remove(n.id).unwrap();
let clip = Node::path(d.alloc_id(), vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 200.0, 200.0)), Default::default());
@@ -265,7 +268,7 @@ fn an_image_under_a_clipping_mask_or_with_an_opacity_mask_exports_with_its_outli
let paths = baked_strokes(&d);
assert!(disc_outline(&paths), "{paths:?}");
// With an opacity mask.
let (mut d, mut n) = image_doc(encoded(disc(), image::ImageFormat::Png), vec![stroke(vec![fx("path.outlineObject")])], 1);
let (mut d, mut n) = image_doc(encoded(disc(), craft_image_codecs::Format::Png), vec![stroke(vec![fx("path.outlineObject")])], 1);
let mut white = Node::path(NodeId(999), vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 200.0, 200.0)), Default::default());
white.appearance.set_fill(Paint::solid(Color::WHITE));
n.extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(Node::group(NodeId(998), vec![Arc::new(white)]), true)));
@@ -279,7 +282,7 @@ fn an_image_under_a_clipping_mask_or_with_an_opacity_mask_exports_with_its_outli
fn outline_object_on_a_fill_and_on_an_indexed_image_follows_the_opaque_area() {
let mut fill = FillLayer::new(Paint::solid(Color::rgb(0.0, 1.0, 0.0)));
fill.effects = vec![fx("path.outlineObject")];
let (d, n) = image_doc(encoded(disc(), image::ImageFormat::Png), vec![AppearanceItem::Fill(fill)], 1);
let (d, n) = image_doc(encoded(disc(), craft_image_codecs::Format::Png), vec![AppearanceItem::Fill(fill)], 1);
let rows = row_bounds(&d, &n);
assert!(matches!(rows.as_slice(), [b] if near(*b, [70.0, 70.0, 130.0, 130.0], 0.5)), "{rows:?}");
// A palette image whose first color is transparent (a tRNS chunk).
@@ -308,15 +311,18 @@ fn an_image_too_large_or_too_complex_to_outline_keeps_its_frame() {
}
// A checkerboard of 2 px squares, whose outline would need more than 100,000 anchor points.
let checker = image::RgbaImage::from_fn(640, 640, |x, y| image::Rgba([0, 0, 0, if (x / 2 + y / 2) % 2 == 0 { 255 } else { 0 }]));
let (d, n) =
image_doc(encoded(image::DynamicImage::ImageRgba8(checker), image::ImageFormat::Png), vec![stroke(vec![fx("path.outlineObject")])], 1);
let (d, n) = image_doc(
encoded(image::DynamicImage::ImageRgba8(checker), craft_image_codecs::Format::Png),
vec![stroke(vec![fx("path.outlineObject")])],
1,
);
assert!(matches!(row_bounds(&d, &n).as_slice(), [b] if near(*b, [50.0, 50.0, 150.0, 150.0], 1e-9)));
}
#[test]
fn an_outline_is_traced_once_for_its_pixels_and_dropped_with_them() {
let traces = || reshape::TRACES.with(std::cell::Cell::get);
let (d, n) = image_doc(encoded(disc(), image::ImageFormat::Png), vec![stroke(vec![fx("path.outlineObject")])], 1);
let (d, n) = image_doc(encoded(disc(), craft_image_codecs::Format::Png), vec![stroke(vec![fx("path.outlineObject")])], 1);
let NodeKind::Image(im) = &n.kind else { panic!("not an image") };
let before = traces();
let first = reshape::opaque_area(&[Some(&d)], im).unwrap();
@@ -331,7 +337,7 @@ fn an_outline_is_traced_once_for_its_pixels_and_dropped_with_them() {
// Once the document and its pixels are gone, the next trace drops their entry.
drop(d);
assert!(pixels.upgrade().is_none());
let (other, _) = image_doc(encoded(disc(), image::ImageFormat::Png), vec![], 1);
let (other, _) = image_doc(encoded(disc(), craft_image_codecs::Format::Png), vec![], 1);
reshape::opaque_area(&[Some(&other)], im).unwrap();
assert_eq!(traces(), before + 2);
assert!(!reshape::keeps_outline(&pixels));
+206 -3
View File
@@ -816,8 +816,8 @@ fn a_groups_transform_applies_after_its_members_own() {
}
/// An object's Transform effect transforms the raster effects of its fills and strokes with the
/// art, whatever its options: drawn, drawn through the art an option makes, and baked. One that
/// makes copies leaves them.
/// art, whatever its options: drawn, drawn through the art an option makes, and baked. For one that
/// makes copies, see [`each_copy_of_an_objects_transform_carries_its_fills_or_strokes_shadow`].
#[test]
fn an_objects_transform_moves_its_fills_shadows() {
let cases = [
@@ -825,7 +825,6 @@ fn an_objects_transform_moves_its_fills_shadows() {
(json!({"scaleH": 200, "scaleV": 100, "strokes": true}), (20.0, 10.0)),
(json!({"rotate": 90, "patterns": true}), (10.0, -10.0)),
(json!({"rotate": 90, "strokes": true}), (10.0, -10.0)),
(json!({"scaleH": 200, "scaleV": 200, "copies": 1}), (10.0, 10.0)),
];
for (params, want) in cases {
let mut n = fill_square(40, vec![shadow(10.0, 10.0, 0.0)]);
@@ -1217,6 +1216,169 @@ fn copies_past_the_budget_each_keep_their_shadow() {
assert_eq!(shadows_in(&art).len(), paths);
}
/// `n` with only its fill (or only a 4 pt blue stroke, with `stroke`), whose own effects are
/// `effects`.
fn one_row(mut n: Node, stroke: bool, effects: Vec<Effect>) -> Node {
let mut item = if stroke {
vectorcraft_doc::AppearanceItem::Stroke(vectorcraft_doc::StrokeLayer::new(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 4.0))
} else {
n.appearance.items.remove(0)
};
*item.effects_mut() = effects;
n.appearance.items = vec![item];
n
}
/// A case of [`copying_cases`]: the params, each copy's offset and each copy's blur.
type CopyingCase = (Value, Vec<(f64, f64)>, Vec<f64>);
/// The cases of a Transform effect that makes copies with a drop shadow (10, 0) and a blur of 4
/// before it: the params, each copy's offset and each copy's blur, the last copy first.
fn copying_cases() -> Vec<CopyingCase> {
vec![
(json!({"moveH": 100, "copies": 2}), vec![(10.0, 0.0), (10.0, 0.0), (10.0, 0.0)], vec![4.0, 4.0, 4.0]),
// 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), (0.0, -10.0), (10.0, 0.0)], vec![4.0, 4.0, 4.0]),
(json!({"reflectX": true, "moveH": 100, "copies": 1}), vec![(-10.0, 0.0), (10.0, 0.0)], vec![4.0, 4.0]),
(json!({"scaleH": 200, "scaleV": 200, "moveH": 100, "copies": 1}), vec![(20.0, 0.0), (10.0, 0.0)], vec![8.0, 4.0]),
// Scale Strokes & Effects does not scale the shadow a second time, nor leave it unturned.
(
json!({"scaleH": 200, "scaleV": 200, "rotate": 90, "moveH": 100, "copies": 1, "strokes": true}),
vec![(0.0, -20.0), (10.0, 0.0)],
vec![8.0, 4.0],
),
(
json!({"scaleH": 200, "scaleV": 200, "rotate": 90, "moveH": 100, "copies": 1, "patterns": true}),
vec![(0.0, -20.0), (10.0, 0.0)],
vec![8.0, 4.0],
),
]
}
/// Check that `n` is drawn, expanded and baked as `want.len()` paths, each with one shadow at the
/// offset and blur `want` and `blurs` give it, the last copy first.
fn assert_copies_carry(n: &Node, want: &[(f64, f64)], blurs: &[f64], what: &str) {
assert!(crate::has_transform_art(n), "{what}");
for (how, art) in
[("drawn", crate::reshape(None, n, None).unwrap()), ("expanded", expand_outlined(None, n, None).unwrap()), ("baked", baked(n.clone()))]
{
assert_eq!(paths_in(&art), want.len(), "{what}: {how} {art:?}");
let drawn = shadows_in(&art);
assert!(near(&drawn, want), "{what}: {how} {drawn:?}");
let b = shadow_blurs_in(&art);
assert!(b.len() == blurs.len() && b.iter().zip(blurs).all(|(x, y)| (x - y).abs() < 1e-9), "{what}: {how} blurs {b:?}");
}
}
/// A fill's or stroke's own Transform effect that makes copies gives each copy the shadow listed
/// before it in that fill's or stroke's effects, moved, turned, reflected and scaled with that copy,
/// the last copy lowest: drawn, expanded and baked. The original keeps the shadow as it is.
#[test]
fn each_copy_of_a_fills_or_strokes_own_transform_carries_the_shadow_before_it() {
for stroke in [false, true] {
for (params, want, blurs) in copying_cases() {
let n = one_row(square(95, vec![]), stroke, vec![shadow(10.0, 0.0, 4.0), transform(params.clone())]);
assert_copies_carry(&n, &want, &blurs, &format!("stroke {stroke}: {params}"));
}
// A Transform effect that makes copies before the shadow: its copies make one piece, which
// the Transform effect after the shadow copies, each copy with its own shadow.
let effects =
vec![transform(json!({"moveV": 100, "copies": 1})), shadow(10.0, 0.0, 4.0), transform(json!({"rotate": 90, "moveH": 200, "copies": 1}))];
let n = one_row(square(95, vec![]), stroke, effects);
assert!(crate::has_transform_art(&n), "stroke {stroke}");
for (how, art) in
[("drawn", crate::reshape(None, &n, None).unwrap()), ("expanded", expand_outlined(None, &n, None).unwrap()), ("baked", baked(n.clone()))]
{
let drawn = shadows_in(&art);
assert!(near(&drawn, &[(0.0, -10.0), (10.0, 0.0)]), "stroke {stroke}: two copying Transform effects, {how} {drawn:?}");
}
}
}
/// A Transform effect that makes copies, listed after a fill's or stroke's first Transform effect
/// with Transform Patterns on, gives each copy the shadow listed before it, as the first one's
/// copies do, with or without options of its own: drawn, expanded and baked.
#[test]
fn each_copy_of_a_later_copying_transform_carries_the_shadow_before_it() {
for stroke in [false, true] {
for (params, want, blurs) in copying_cases() {
let effects = vec![transform(json!({"patterns": true})), shadow(10.0, 0.0, 4.0), transform(params.clone())];
let n = one_row(square(102, vec![]), stroke, effects);
assert_copies_carry(&n, &want, &blurs, &format!("stroke {stroke}: {params}"));
}
}
}
/// A fill's or stroke's shadow under its object's Transform effect that makes copies is carried by
/// each copy, moved, turned, reflected and scaled with it: for a single fill, a single stroke, and
/// a fill and a stroke that paint each copy below the one before. Drawn, expanded and baked.
#[test]
fn each_copy_of_an_objects_transform_carries_its_fills_or_strokes_shadow() {
for (params, want, blurs) in copying_cases() {
for stroke in [false, true] {
let mut n = one_row(square(96, vec![]), stroke, vec![shadow(10.0, 0.0, 4.0)]);
n.appearance.effects = vec![transform(params.clone())];
assert_copies_carry(&n, &want, &blurs, &format!("stroke {stroke}: {params}"));
}
// Both a fill and a stroke: only the fill has the shadow.
let mut n = square(97, vec![transform(params.clone())]);
if let Some(vectorcraft_doc::AppearanceItem::Stroke(s)) = n.appearance.items.get_mut(1) {
s.paint = Paint::solid(Color::BLACK);
s.width = 2.0;
}
*n.appearance.items[0].effects_mut() = vec![shadow(10.0, 0.0, 4.0)];
assert!(crate::has_transform_art(&n), "{params}");
for (how, art) in
[("drawn", crate::reshape(None, &n, None).unwrap()), ("expanded", expand_outlined(None, &n, None).unwrap()), ("baked", baked(n.clone()))]
{
let drawn = shadows_in(&art);
assert!(near(&drawn, &want), "layered {params}: {how} {drawn:?}");
}
}
}
/// A shadow listed after a fill's own Transform effect that makes copies paints once around all of
/// them, and one listed before it on each copy. A Transform effect that makes no copies, or has
/// Transform Objects off, draws the fill as before, without art.
#[test]
fn a_fills_shadow_after_its_own_copying_transform_paints_once_around_the_copies() {
let effects = vec![shadow(10.0, 0.0, 0.0), transform(json!({"rotate": 90, "copies": 1})), shadow(0.0, 5.0, 0.0)];
let n = one_row(square(98, vec![]), false, effects);
for (how, art) in
[("drawn", crate::reshape(None, &n, None).unwrap()), ("expanded", expand_outlined(None, &n, None).unwrap()), ("baked", baked(n.clone()))]
{
assert!(near(&shadows_in(&art), &[(0.0, 5.0), (0.0, -10.0), (10.0, 0.0)]), "{how}: {:?}", shadows_in(&art));
assert_eq!(paths_in(&art), 2, "{how}");
}
for params in [json!({"rotate": 90}), json!({"rotate": 90, "copies": 1, "objects": false})] {
let n = one_row(square(99, vec![]), false, vec![shadow(10.0, 0.0, 0.0), transform(params.clone())]);
assert!(!crate::has_transform_art(&n), "{params}");
assert!(!crate::has_copied_row_raster(&n), "{params}");
}
// A shadow between two Transform effects that make copies paints on what the second one
// copies, so the fill is drawn as before, without art.
let copies = transform(json!({"rotate": 90, "copies": 1}));
let n = one_row(square(99, vec![]), false, vec![shadow(10.0, 0.0, 0.0), copies.clone(), shadow(0.0, 5.0, 0.0), copies]);
assert!(!crate::has_copied_row_raster(&n));
assert!(!crate::has_transform_art(&n));
}
/// Copies of a fill's own Transform effect that stop at the effect budget each keep their shadow,
/// and so do those of an object's Transform effect for its fill's shadow.
#[test]
fn row_copies_past_the_budget_each_keep_their_shadow() {
let copies = transform(json!({"moveV": 50, "copies": 1000}));
let own = one_row(path_node(100, wavy(30_000), vec![]), false, vec![shadow(1.0, 0.5, 0.0), copies.clone()]);
let mut owner = one_row(path_node(101, wavy(30_000), vec![]), false, vec![shadow(1.0, 0.5, 0.0)]);
owner.appearance.effects = vec![copies];
for n in [own, owner] {
let art = crate::reshape(None, &n, None).unwrap();
let paths = paths_in(&art);
assert!(paths > 1 && paths < 1001, "{paths}");
assert_eq!(shadows_in(&art).len(), paths);
}
}
/// Black 40 pt "IIII" with its baseline at (5, 60) and `effects`.
fn type_node(id: u64, effects: Vec<Effect>) -> Node {
use vectorcraft_doc::text::{CharStyle, TextObject};
@@ -1309,3 +1471,44 @@ fn type_with_a_reshaped_fill_keeps_one_shadow_around_its_copies() {
}));
assert_eq!(crate::outer_effects(&filled).len(), 2);
}
/// Type whose own fill's Transform effect makes copies is drawn as its outlines, and each copy
/// carries the shadow listed before that Transform effect, as a path's copies do: for the fill's
/// first Transform effect and for one listed after a Transform effect with Transform Patterns on.
/// Drawn, expanded and baked.
#[test]
fn type_carries_its_fills_shadow_on_each_copy() {
let filled = |mut n: Node, effects: Vec<Effect>| {
n.appearance.items.push(vectorcraft_doc::AppearanceItem::Fill(vectorcraft_doc::FillLayer {
effects,
..vectorcraft_doc::FillLayer::new(Paint::solid(Color::BLACK))
}));
n
};
let copying = vec![shadow(10.0, 0.0, 0.0), transform(json!({"moveH": 100, "copies": 1}))];
if !crate::outline_text(&type_node(95, vec![])).is_some_and(|o| paths_in(&o) > 0) {
eprintln!("type skipped: built without fonts (enable vectorcraft-text's bundled-fonts to run it)");
return;
}
let later = vec![transform(json!({"patterns": true})), shadow(10.0, 0.0, 0.0), transform(json!({"moveH": 100, "copies": 1}))];
for (what, effects) in [("first", copying), ("later", later)] {
let n = filled(type_node(95, vec![]), effects);
for (how, art) in
[("drawn", crate::reshape(None, &n, None)), ("expanded", expand_outlined(None, &n, None)), ("baked", Some(baked(n.clone())))]
{
let art = art.unwrap_or_else(|| panic!("{what}: {how}"));
assert!(near(&shadows_in(&art), &[(10.0, 0.0), (10.0, 0.0)]), "{what}: {how} {:?}", shadows_in(&art));
// The two shadows are on two objects 100 pt apart: the type and its copy.
let mut lefts = vec![];
art.walk(&mut |m| {
let lists = std::iter::once(&m.appearance.effects).chain(m.appearance.items.iter().map(|i| i.effects()));
let shadows = lists.map(|l| l.iter().filter(|e| e.id == "stylize.dropShadow").count()).sum::<usize>();
if let Some(b) = m.geometric_bounds() {
lefts.extend(std::iter::repeat_n(b.x0, shadows));
}
});
lefts.sort_by(f64::total_cmp);
assert!(lefts.len() == 2 && (lefts[1] - lefts[0] - 100.0).abs() < 1e-6, "{what}: {how} {lefts:?}");
}
}
}
+13 -4
View File
@@ -29,6 +29,8 @@ vectorcraft-tools = { workspace = true }
vectorcraft-text = { workspace = true }
vectorcraft-render = { workspace = true }
vectorcraft-pathops = { workspace = true }
# The panels and hinges of a packaging blank (Packaging Tools' Check Fold Lines).
vectorcraft-three-d = { workspace = true }
vectorcraft-brush = { workspace = true }
vectorcraft-trace = { workspace = true }
vectorcraft-svg = { workspace = true }
@@ -44,10 +46,10 @@ vectorcraft-js = { workspace = true }
# The commands' parameter schemas (schemas.rs).
vectorcraft-apischema = { workspace = true }
image = { workspace = true }
craft-image-codecs = { workspace = true }
jxl-oxide = { workspace = true }
jxl-color = { workspace = true }
jxl-grid = { workspace = true }
hayro-jpeg2000 = { version = "=0.3.5", default-features = false, features = ["std", "simd"] }
# Pure Rust, no unsafe; pinned at the version photocraft-heif uses.
heic-rs = { version = "=0.1.4", default-features = false, features = ["std"], optional = true }
flate2 = { workspace = true }
@@ -78,6 +80,16 @@ heic-rs = { version = "=0.1.4", default-features = false, features = ["std", "pa
rayon = { version = "1.12", optional = true }
[dev-dependencies]
# JPEG XL files for the `.jxl` open and place tests.
zune-jpegxl = { workspace = true }
zune-core = { workspace = true }
# JPEG XL files for the import fuzz tests (tests/import_fuzz.rs).
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 }
vectorcraft-testkit = { workspace = true }
@@ -89,9 +101,6 @@ vectorcraft-pdf = { workspace = true, features = ["read-count"] }
wat = { workspace = true }
# Zstandard streams for the Illustrator editing data fuzz tests.
ruzstd = { workspace = true }
# JPEG XL files for the `.jxl` open and place tests.
zune-jpegxl = { workspace = true }
zune-core = { workspace = true }
# The JavaScript parser's lexer, compared with the script checker's on the same scripts.
vectorcraft-js = { workspace = true }
# A bundled font's own glyph boxes, for the glyph bounds tests.
+4
View File
@@ -893,6 +893,10 @@ pub use buildcmds::live_paint_gaps;
/// Control bar enable it when it changes one).
pub use brushsym::reset_transformation_changes;
/// The Symbols panel's current symbol, as `symbol.list` answers it (the panel reads it on every
/// frame without running the command).
pub use brushsym::current_symbol;
/// The byte order of UTF-16 text without a byte-order mark, by Import Data Sets' rule (the Graph
/// Data window reads files by it too).
pub use variablecmds::utf16_order_without_mark;
+2 -3
View File
@@ -147,9 +147,8 @@ fn is_of_kind(d: &Document, n: &Node, kind: &str) -> bool {
/// Are the encoded image `bytes` grayscale or 1-bit? Reads only the header.
fn is_gray(bytes: &[u8]) -> bool {
use image::ImageDecoder as _;
let decoder = image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format().ok().and_then(|r| r.into_decoder().ok());
decoder.is_some_and(|d| matches!(d.color_type(), image::ColorType::L8 | image::ColorType::La8 | image::ColorType::L16 | image::ColorType::La16))
craft_image_codecs::decode(bytes)
.is_ok_and(|img| matches!(img.layout(), craft_image_codecs::ChannelLayout::Gray | craft_image_codecs::ChannelLayout::GrayA))
}
fn filter(s: &mut Session, p: &Value) -> Result<Value> {
+35 -1
View File
@@ -111,7 +111,41 @@ fn image(s: &mut Session, key: &str, blob: vectorcraft_doc::ImageBlob, x: f64) -
fn png(img: image::DynamicImage) -> vectorcraft_doc::ImageBlob {
let mut bytes = vec![];
img.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap();
{
let __dyn: image::DynamicImage = img;
let (__w, __h) = (__dyn.width(), __dyn.height());
let (__layout, __sample, __raw) = match __dyn {
image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLuma16(b) => (
craft_image_codecs::ChannelLayout::Gray,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageLumaA16(b) => (
craft_image_codecs::ChannelLayout::GrayA,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgb16(b) => (
craft_image_codecs::ChannelLayout::Rgb,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgba16(b) => (
craft_image_codecs::ChannelLayout::Rgba,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()),
};
let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap();
craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default())
.map(|__b| bytes.extend_from_slice(&__b))
}
.unwrap();
vectorcraft_doc::ImageBlob::png(bytes)
}
+35 -1
View File
@@ -228,7 +228,41 @@ fn export_all_open_documents_writes_one_file_each() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 100, "height": 100, "name": "pic"})).unwrap();
let mut png = vec![];
image::RgbaImage::from_pixel(4, 4, image::Rgba([1, 2, 3, 255])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
{
let __dyn: image::DynamicImage = (image::RgbaImage::from_pixel(4, 4, image::Rgba([1, 2, 3, 255]))).into();
let (__w, __h) = (__dyn.width(), __dyn.height());
let (__layout, __sample, __raw) = match __dyn {
image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLuma16(b) => (
craft_image_codecs::ChannelLayout::Gray,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageLumaA16(b) => (
craft_image_codecs::ChannelLayout::GrayA,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgb16(b) => (
craft_image_codecs::ChannelLayout::Rgb,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgba16(b) => (
craft_image_codecs::ChannelLayout::Rgba,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()),
};
let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap();
craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default())
.map(|__b| png.extend_from_slice(&__b))
}
.unwrap();
s.execute("file.place", &json!({"name": "a.png", "dataBase64": vectorcraft_format::base64_encode(&png)})).unwrap();
s.execute("document.save", &json!({"path": dir.join("pic.svg"), "format": "svg", "options": {"images": "link"}})).unwrap();
let saved: Vec<_> = std::fs::read_dir(&dir).unwrap().filter_map(|e| e.ok()).filter(|e| e.path().is_file()).collect();
+83 -38
View File
@@ -13,10 +13,9 @@ mod tests;
pub(crate) use mask::refresh as refresh_color_masks;
use std::collections::{HashMap, HashSet};
use std::io::Cursor;
use std::sync::{Arc, Weak};
use image::{DynamicImage, ImageBuffer, LumaA, Rgba};
use image::{ImageBuffer, Rgba};
use serde_json::{Value, json};
use vectorcraft_color::Color;
use vectorcraft_doc::{ImageBlob, ImageObject, NodeId, NodeKind};
@@ -412,23 +411,36 @@ pub(crate) fn clear(blob: &ImageBlob, settings: &Settings, mut kept: Option<&mut
bad(cmd, "every pixel matches the background: no image would be left")
});
}
let out = match (px, gray) {
(Pixels::Eight(img), false) => DynamicImage::ImageRgba8(img),
(Pixels::Sixteen(img), false) => DynamicImage::ImageRgba16(img),
(Pixels::Eight(img), true) => {
DynamicImage::ImageLumaA8(ImageBuffer::from_fn(w, h, |x, y| LumaA([img.get_pixel(x, y).0[0], img.get_pixel(x, y).0[3]])))
let raw = match (px, gray) {
(Pixels::Eight(img), false) => {
craft_image_codecs::Image::from_raw(w, h, craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, img.into_raw())
}
(Pixels::Sixteen(img), true) => {
DynamicImage::ImageLumaA16(ImageBuffer::from_fn(w, h, |x, y| LumaA([img.get_pixel(x, y).0[0], img.get_pixel(x, y).0[3]])))
}
};
let mut png = Vec::new();
let mut encoder = image::codecs::png::PngEncoder::new(&mut png);
if let Some(icc) = icc {
use image::ImageEncoder as _;
encoder.set_icc_profile(icc).map_err(|e| bad(cmd, e.to_string()))?;
(Pixels::Sixteen(img), false) => craft_image_codecs::Image::from_raw(
w,
h,
craft_image_codecs::ChannelLayout::Rgba,
craft_image_codecs::SampleType::U16,
img.into_raw().into_iter().flat_map(u16::to_ne_bytes).collect(),
),
(Pixels::Eight(img), true) => craft_image_codecs::Image::from_raw(
w,
h,
craft_image_codecs::ChannelLayout::GrayA,
craft_image_codecs::SampleType::U8,
img.pixels().flat_map(|p| [p.0[0], p.0[3]]).collect(),
),
(Pixels::Sixteen(img), true) => craft_image_codecs::Image::from_raw(
w,
h,
craft_image_codecs::ChannelLayout::GrayA,
craft_image_codecs::SampleType::U16,
img.pixels().flat_map(|p| [p.0[0], p.0[3]]).flat_map(u16::to_ne_bytes).collect(),
),
}
out.write_with_encoder(encoder).map_err(|e| bad(cmd, e.to_string()))?;
.map_err(|e| bad(cmd, e.to_string()))?
.with_icc(icc);
let mut png = craft_image_codecs::encode(&raw, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default())
.map_err(|e| bad(cmd, e.to_string()))?;
// The resolution the file declares, which sizes the image at 100% when it is replaced or relinked.
if let Some(r) = ppi::resolution(&blob.bytes) {
png = ppi::with_png_resolution(&png, r);
@@ -436,37 +448,70 @@ pub(crate) fn clear(blob: &ImageBlob, settings: &Settings, mut kept: Option<&mut
Ok(Some(Cleared { blob: ImageBlob::png(png), width: w, height: h, cleared }))
}
/// The image's size and the bytes a pixel of it takes to change, read from its header: its
/// samples as decoded (bitmaps as 8-bit gray, palettes as RGB, or RGBA with a transparent entry),
/// those worked on and kept for the PNG, and the work. A header that gives only the size (one
/// whose file can't hold its pixels) counts the fewest: one 8-bit sample. `None` when the header
/// doesn't say.
fn header_pixels(bytes: &[u8]) -> Option<(u32, u32, u64)> {
use craft_image_codecs::RasterColorType as T;
let Some(i) = craft_image_codecs::inspect_raster(bytes).ok().flatten() else {
return vectorcraft_doc::header_size(bytes).map(|(w, h)| (w, h, 1 + 2 * 4 + WORK_BYTES));
};
let deep = i.bits_per_sample > 8 && i.color_type != T::Indexed;
let channels = match i.color_type {
T::Indexed => 3 + u64::from(i.transparent_index.is_some()),
T::Bitmap => 1,
_ => u64::from(i.channels.max(1)),
};
let samples = channels * if deep { 2 } else { 1 };
Some((i.width, i.height, samples + 2 * if deep { 8 } else { 4 } + WORK_BYTES))
}
/// `blob`'s pixels as straight RGBA, whether they were gray, and its ICC profile. An image that
/// can't be decoded or is too large to change is an error. The pixels are kept in `kept`, when it
/// is given, if a copy of them fits the decode allowance beside the work. Errors are command `cmd`'s.
fn decode(blob: &ImageBlob, kept: Option<&mut DecodedImages>, cmd: &str) -> Result<(Arc<Pixels>, bool, Option<Vec<u8>>)> {
let reader = || {
image::ImageReader::new(Cursor::new(blob.bytes.as_slice())).with_guessed_format().map_err(|_| bad(cmd, "the image's pixels can't be read"))
};
let mut decoder = reader()?.into_decoder().map_err(|e| bad(cmd, format!("the image's pixels can't be read: {e}")))?;
// The ICC profile the colors are in goes with them into the PNG.
let (w, h, kind, icc) = {
use image::ImageDecoder as _;
let (w, h) = decoder.dimensions();
(w, h, decoder.color_type(), decoder.icc_profile().ok().flatten())
};
drop(decoder);
// The file's pixels, those worked on (as many again for the PNG made of them) and the work,
// checked from the header before anything is decoded.
let deep = kind.bytes_per_pixel() > kind.channel_count();
let per_pixel = u64::from(kind.bytes_per_pixel()) + 2 * if deep { 8 } else { 4 } + WORK_BYTES;
if u64::from(w).checked_mul(u64::from(h)).and_then(|n| n.checked_mul(per_pixel)).is_none_or(|n| n > MAX_RASTER_ALLOC) {
let too_large = |w: u32, h: u32, per_pixel: u64| {
u64::from(w).checked_mul(u64::from(h)).and_then(|n| n.checked_mul(per_pixel)).is_none_or(|n| n > MAX_RASTER_ALLOC)
};
let header = header_pixels(&blob.bytes);
if let Some((w, h, per_pixel)) = header
&& too_large(w, h, per_pixel)
{
return Err(bad(cmd, format!("an image of {w} × {h} pixels is too large to change")));
}
let mut opts = craft_image_codecs::DecodeOptions::default();
opts.limits.max_alloc = MAX_RASTER_ALLOC;
let img = craft_image_codecs::decode_with(&blob.bytes, &opts).map_err(|e| match e {
// Within the allowance from its header: a file that can't hold the pixels it declares.
craft_image_codecs::CodecError::LimitExceeded(_) if header.is_none() => bad(cmd, "the image is too large to change"),
_ => bad(cmd, format!("the image's pixels can't be read: {e}")),
})?;
let (w, h) = img.dimensions();
let icc = img.icc.clone();
let deep = img.sample_type() == craft_image_codecs::SampleType::U16;
let gray = matches!(img.layout(), craft_image_codecs::ChannelLayout::Gray | craft_image_codecs::ChannelLayout::GrayA);
let per_pixel = u64::from(img.layout().channels() as u32 * img.sample_type().bytes() as u32) + 2 * if deep { 8 } else { 4 } + WORK_BYTES;
if too_large(w, h, per_pixel) {
return Err(bad(cmd, format!("an image of {w} × {h} pixels is too large to change")));
}
let mut reader = reader()?;
let mut limits = image::Limits::default();
limits.max_alloc = Some(MAX_RASTER_ALLOC);
reader.limits(limits);
let img = reader.decode().map_err(|e| bad(cmd, format!("the image's pixels can't be read: {e}")))?;
#[cfg(test)]
DECODES.with(|c| c.set(c.get() + 1));
let gray = matches!(img.color(), image::ColorType::L8 | image::ColorType::La8 | image::ColorType::L16 | image::ColorType::La16);
let px = Arc::new(if deep { Pixels::Sixteen(img.into_rgba16()) } else { Pixels::Eight(img.into_rgba8()) });
let px = Arc::new(if deep {
let rgba16 = match (img.layout(), img.to_u16_samples()) {
(craft_image_codecs::ChannelLayout::Rgba, Some(v)) => v,
(craft_image_codecs::ChannelLayout::Rgb, Some(v)) => v.as_chunks::<3>().0.iter().flat_map(|c| [c[0], c[1], c[2], u16::MAX]).collect(),
(craft_image_codecs::ChannelLayout::GrayA, Some(v)) => v.as_chunks::<2>().0.iter().flat_map(|c| [c[0], c[0], c[0], c[1]]).collect(),
(craft_image_codecs::ChannelLayout::Gray, Some(v)) => v.into_iter().flat_map(|g| [g, g, g, u16::MAX]).collect(),
_ => img.to_rgba8().into_iter().map(|b| u16::from(b) * 257).collect(),
};
Pixels::Sixteen(ImageBuffer::from_raw(w, h, rgba16).ok_or_else(|| bad(cmd, "invalid 16-bit pixel buffer"))?)
} else {
Pixels::Eight(ImageBuffer::from_raw(w, h, img.to_rgba8()).ok_or_else(|| bad(cmd, "invalid 8-bit pixel buffer"))?)
});
// A kept copy is worked on as a copy: one more set of the pixels worked on.
let with_copy = per_pixel + if deep { 8 } else { 4 };
if let Some(kept) = kept
+1 -3
View File
@@ -287,9 +287,7 @@ fn apply_color_mask(s: &mut Session, p: &Value) -> Result<Value> {
/// The size in pixels of masked pixels `blob` (from its header), or the object's when it can't be
/// read.
fn mask_size(blob: Option<&ImageBlob>, width: u32, height: u32) -> (u32, u32) {
blob.and_then(|b| image::ImageReader::new(std::io::Cursor::new(b.bytes.as_slice())).with_guessed_format().ok()?.into_dimensions().ok())
.filter(|(w, h)| *w > 0 && *h > 0)
.unwrap_or((width, height))
blob.and_then(|b| b.pixel_size()).filter(|(w, h)| *w > 0 && *h > 0).unwrap_or((width, height))
}
/// The mask of image node `n` made again for the image's own pixels, with the masked pixels when
+218 -13
View File
@@ -1,5 +1,3 @@
use std::io::Cursor;
use image::DynamicImage;
use serde_json::{Value, json};
use vectorcraft_color::{Color, Paint};
@@ -15,7 +13,41 @@ const RED: [u8; 4] = [200, 0, 0, 255];
fn png(img: DynamicImage) -> Vec<u8> {
let mut out = Vec::new();
img.write_to(&mut Cursor::new(&mut out), image::ImageFormat::Png).unwrap();
{
let __dyn: image::DynamicImage = img;
let (__w, __h) = (__dyn.width(), __dyn.height());
let (__layout, __sample, __raw) = match __dyn {
image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLuma16(b) => (
craft_image_codecs::ChannelLayout::Gray,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageLumaA16(b) => (
craft_image_codecs::ChannelLayout::GrayA,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgb16(b) => (
craft_image_codecs::ChannelLayout::Rgb,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgba16(b) => (
craft_image_codecs::ChannelLayout::Rgba,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()),
};
let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap();
craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default())
.map(|__b| out.extend_from_slice(&__b))
}
.unwrap();
out
}
@@ -138,7 +170,24 @@ fn applying_the_mask_makes_it_part_of_the_pixels() {
assert_eq!(s.execute(APPLY_COLOR_MASK, &json!({})).unwrap(), json!({"changed": 1, "ids": [id.0]}));
let d = doc(&s);
assert_eq!((image_of(d, id).key, mask_of(d, id)), (m.key.clone(), None));
let px = image::load_from_memory(&d.images[&m.key].bytes).unwrap().to_rgba8();
let px = craft_image_codecs::decode(&d.images[&m.key].bytes)
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap()
.to_rgba8();
assert_eq!((px.get_pixel(0, 0).0[3], px.get_pixel(4, 4).0), (0, RED));
assert_eq!(drawn(d, id, 0, 0)[3], 0);
assert_eq!(undo_len(&s), steps + 1);
@@ -149,7 +198,23 @@ fn applying_the_mask_makes_it_part_of_the_pixels() {
fn svg_image(svg: &str) -> DynamicImage {
let at = svg.find("data:image/png;base64,").expect("an embedded PNG") + "data:image/png;base64,".len();
let end = at + svg[at..].find('"').unwrap();
image::load_from_memory(&vectorcraft_format::base64_decode(&svg[at..end]).unwrap()).unwrap()
craft_image_codecs::decode(&vectorcraft_format::base64_decode(&svg[at..end]).unwrap())
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap()
}
#[test]
@@ -159,7 +224,28 @@ fn outputs_write_the_masked_pixels() {
|s: &Session, format: &str| crate::cmd::fileio::encode_all(doc(s), format, &json!({"useArtboards": true})).unwrap().files.remove(0).1;
let (png0, svg0, pdf0, eps0) = (export(&s, "png"), export(&s, "svg"), export(&s, "pdf"), export(&s, "eps"));
s.execute(COLOR_MASK, &hide_white()).unwrap();
let alpha = |bytes: &[u8]| image::load_from_memory(bytes).unwrap().to_rgba8().get_pixel(0, 0).0[3];
let alpha = |bytes: &[u8]| {
craft_image_codecs::decode(bytes)
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap()
.to_rgba8()
.get_pixel(0, 0)
.0[3]
};
assert_eq!((alpha(&png0), alpha(&export(&s, "png"))), (255, 0), "PNG");
let svg_alpha = |bytes: &[u8]| svg_image(std::str::from_utf8(bytes).unwrap()).to_rgba8().get_pixel(0, 0).0[3];
assert_eq!((svg_alpha(&svg0), svg_alpha(&export(&s, "svg"))), (255, 0), "SVG");
@@ -344,7 +430,24 @@ fn cropping_off_the_pixel_grid_keeps_the_hidden_colors_in_the_pixels() {
let d = doc(&s);
let (im, m) = (image_of(d, id), mask_of(d, id).unwrap());
assert_eq!(m.from, im.key, "the mask is made for the cut pixels");
let own = image::load_from_memory(&d.images[&im.key].bytes).unwrap().to_rgba8();
let own = craft_image_codecs::decode(&d.images[&im.key].bytes)
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap()
.to_rgba8();
assert!(own.pixels().all(|p| p.0[3] == 255), "the cut pixels are the image's own, white included");
assert_eq!(drawn(d, id, 0, 0)[3], 0, "white is hidden");
s.execute(REMOVE_COLOR_MASK, &json!({"ids": [id.0]})).unwrap();
@@ -377,7 +480,24 @@ fn applying_a_mask_made_for_older_pixels_makes_it_again_and_keeps_the_size() {
assert_eq!((im.width, im.height, mask_of(d, id)), (24, 20, None));
let after = d.node(id).unwrap().geometric_bounds().unwrap();
assert!((after.width() - before.width()).abs() < 1e-9 && (after.height() - before.height()).abs() < 1e-9, "{before:?} {after:?}");
let px = image::load_from_memory(&d.images[&im.key].bytes).unwrap().to_rgba8();
let px = craft_image_codecs::decode(&d.images[&im.key].bytes)
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap()
.to_rgba8();
assert_eq!((px.get_pixel(0, 0).0[3], px.get_pixel(10, 10).0), (0, RED));
}
@@ -435,7 +555,24 @@ fn another_image_colorized_with_transparency_does_not_change_the_refusal() {
s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap();
assert_eq!(s.execute(COLOR_MASK, &hide_white()).unwrap()["changed"], 1, "an image colorized with black takes the mask beside the other");
let m = mask_of(doc(&s), id).unwrap();
let masked = image::load_from_memory(&doc(&s).images[&m.key].bytes).unwrap().to_luma_alpha8();
let masked = craft_image_codecs::decode(&doc(&s).images[&m.key].bytes)
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap()
.to_luma_alpha8();
assert_eq!((masked.get_pixel(0, 0).0[1], masked.get_pixel(4, 4).0[1]), (0, 255), "white is hidden and black shows");
}
@@ -580,7 +717,24 @@ fn masks_outside_the_layers_are_made_again() {
let art = &d.node(holder_id).unwrap().extras().mask.as_ref().unwrap().art;
assert_eq!(from(art), key, "in the opacity mask's art");
let m = Document::color_mask_of(art).unwrap();
let px = image::load_from_memory(&d.images[&m.key].bytes).unwrap().to_rgba8();
let px = craft_image_codecs::decode(&d.images[&m.key].bytes)
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap()
.to_rgba8();
assert_eq!((px.get_pixel(0, 0).0[3], px.get_pixel(1, 0).0), (0, RED));
}
@@ -696,7 +850,24 @@ fn a_linked_file_read_again_on_open_takes_the_mask_again() {
let d = doc(&s);
let (im, m) = (image_of(d, id), mask_of(d, id).unwrap());
assert_eq!(m.from, im.key, "made for the file's new pixels");
let px = image::load_from_memory(&d.images[&m.key].bytes).unwrap().to_rgba8();
let px = craft_image_codecs::decode(&d.images[&m.key].bytes)
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap()
.to_rgba8();
assert_eq!((px.get_pixel(0, 0).0[3], px.get_pixel(4, 4).0), (0, [0, 0, 200, 255]));
}
@@ -812,7 +983,24 @@ fn a_live_color_adjustment_recolors_the_image_when_its_masked_pixels_are_missing
let NodeKind::Image(im) = &out.kind else { panic!("an image") };
assert_ne!(im.key, image_of(&d, id).key, "the expanded image is recolored");
assert_eq!(Document::color_mask_of(&out), None, "the expanded image has no mask to make again from the recolored pixels");
let px = image::load_from_memory(&d.images[&im.key].bytes).unwrap().to_rgba8();
let px = craft_image_codecs::decode(&d.images[&im.key].bytes)
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap()
.to_rgba8();
assert_eq!(px.get_pixel(1, 1).0, WHITE, "the expanded image shows the white");
}
@@ -1002,6 +1190,23 @@ fn placing_a_document_brings_the_masked_pixels() {
}
let [(im, placed)] = found.as_slice() else { panic!("one masked image: {found:?}") };
assert!(placed.made_for(im) && placed.from != m.from, "the image was renamed and the mask follows: {placed:?}");
let px = image::load_from_memory(&d.images[&placed.key].bytes).unwrap().to_rgba8();
let px = craft_image_codecs::decode(&d.images[&placed.key].bytes)
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap()
.to_rgba8();
assert_eq!((px.get_pixel(0, 0).0[3], px.get_pixel(4, 4).0), (0, RED));
}
+81 -17
View File
@@ -1,4 +1,3 @@
use std::io::Cursor;
use std::sync::Arc;
use image::{DynamicImage, ImageBuffer, Luma, LumaA, Rgb};
@@ -21,7 +20,41 @@ fn settings(background: Background) -> Settings {
fn png(img: DynamicImage) -> Vec<u8> {
let mut out = Vec::new();
img.write_to(&mut Cursor::new(&mut out), image::ImageFormat::Png).unwrap();
{
let __dyn: image::DynamicImage = img;
let (__w, __h) = (__dyn.width(), __dyn.height());
let (__layout, __sample, __raw) = match __dyn {
image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLuma16(b) => (
craft_image_codecs::ChannelLayout::Gray,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageLumaA16(b) => (
craft_image_codecs::ChannelLayout::GrayA,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgb16(b) => (
craft_image_codecs::ChannelLayout::Rgb,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgba16(b) => (
craft_image_codecs::ChannelLayout::Rgba,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()),
};
let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap();
craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default())
.map(|__b| out.extend_from_slice(&__b))
}
.unwrap();
out
}
@@ -53,7 +86,32 @@ fn bytes_of(s: &Session, id: NodeId) -> Arc<Vec<u8>> {
}
fn pixels(s: &Session, id: NodeId) -> DynamicImage {
image::load_from_memory(&bytes_of(s, id)).unwrap()
craft_image_codecs::decode(&bytes_of(s, id))
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(layout, craft_image_codecs::SampleType::U16) => {
let v = __cimg.to_u16_samples().unwrap();
match layout {
craft_image_codecs::ChannelLayout::Gray => image::DynamicImage::ImageLuma16(ImageBuffer::from_raw(__w, __h, v).unwrap()),
craft_image_codecs::ChannelLayout::GrayA => image::DynamicImage::ImageLumaA16(ImageBuffer::from_raw(__w, __h, v).unwrap()),
craft_image_codecs::ChannelLayout::Rgb => image::DynamicImage::ImageRgb16(ImageBuffer::from_raw(__w, __h, v).unwrap()),
_ => image::DynamicImage::ImageRgba16(ImageBuffer::from_raw(__w, __h, v).unwrap()),
}
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap()
}
fn alpha(img: &DynamicImage, x: u32, y: u32) -> u8 {
@@ -164,13 +222,13 @@ fn preview_steps_on_the_same_pixels_decode_them_once() {
/// image with an ICC profile comes out as a run on freshly decoded pixels gives it.
#[test]
fn reused_pixels_keep_their_depth_gray_and_profile() {
use image::{ImageDecoder as _, ImageEncoder as _};
let icc = b"a profile's bytes".to_vec();
let gray16 = ImageBuffer::from_fn(8, 8, |x, y| Luma([if (2..6).contains(&x) && (2..6).contains(&y) { 7_000u16 } else { 61_000 }]));
let mut bytes = Vec::new();
let mut encoder = image::codecs::png::PngEncoder::new(&mut bytes);
encoder.set_icc_profile(icc.clone()).unwrap();
DynamicImage::ImageLuma16(gray16).write_with_encoder(encoder).unwrap();
let raw: Vec<u8> = gray16.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect();
let mut cimg =
craft_image_codecs::Image::from_raw(8, 8, craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U16, raw).unwrap();
cimg.icc = Some(icc.clone());
let bytes = craft_image_codecs::encode(&cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap();
let decodes = || super::DECODES.with(std::cell::Cell::get);
let (mut s, id) = open(&bytes);
let start = decodes();
@@ -184,8 +242,8 @@ fn reused_pixels_keep_their_depth_gray_and_profile() {
let DynamicImage::ImageLumaA16(out) = pixels(&s, id) else { panic!("16-bit gray with alpha") };
assert_eq!((out.get_pixel(0, 0).0, out.get_pixel(3, 3).0), ([61_000, 0], [7_000, 65_535]));
let result = bytes_of(&s, id);
let mut decoder = image::codecs::png::PngDecoder::new(Cursor::new(result.as_slice())).unwrap();
assert_eq!(decoder.icc_profile().unwrap(), Some(icc));
let decoded = craft_image_codecs::decode_as(craft_image_codecs::Format::Png, result.as_slice()).unwrap();
assert_eq!(decoded.icc, Some(icc));
}
/// Once the background is cleared, most edge pixels are clear and a second run clears nothing: the
@@ -385,16 +443,22 @@ fn a_gray_image_colorized_with_a_process_color_is_refused() {
/// The ICC profile the colors are in stays with them.
#[test]
fn the_color_profile_is_kept() {
use image::{ImageDecoder as _, ImageEncoder as _};
let icc = b"a profile's bytes".to_vec();
let mut bytes = Vec::new();
let mut encoder = image::codecs::png::PngEncoder::new(&mut bytes);
encoder.set_icc_profile(icc.clone()).unwrap();
DynamicImage::ImageRgba8(framed()).write_with_encoder(encoder).unwrap();
let f = framed();
let mut cimg = craft_image_codecs::Image::from_raw(
f.width(),
f.height(),
craft_image_codecs::ChannelLayout::Rgba,
craft_image_codecs::SampleType::U8,
f.into_raw(),
)
.unwrap();
cimg.icc = Some(icc.clone());
let bytes = craft_image_codecs::encode(&cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap();
let blob = ImageBlob::png(bytes);
let out = super::clear(&blob, &settings(Background::Edges), None, super::C).unwrap().unwrap();
let mut decoder = image::codecs::png::PngDecoder::new(Cursor::new(out.blob.bytes.as_slice())).unwrap();
assert_eq!(decoder.icc_profile().unwrap(), Some(icc));
let decoded = craft_image_codecs::decode_as(craft_image_codecs::Format::Png, out.blob.bytes.as_slice()).unwrap();
assert_eq!(decoded.icc, Some(icc));
}
/// The resolution the file declares stays with the pixels, so a later Replace or relink sizes the
+6 -2
View File
@@ -1,9 +1,11 @@
//! Packaging Tools (`addon.packaging.*`), a built-in add-on for the dielines of boxes and other
//! folded packaging. A path is a fold line when its top stroke is painted with the swatch of a line
//! role: Cut, Crease, Partial Cut or Perforation ([`roles`]). The document's role table maps each
//! role to its swatch, so every format that keeps the stroke's swatch keeps the role. Its submenu
//! role to its swatch, so every format that keeps the stroke's swatch keeps the role. Check Fold
//! Lines ([`check`]) finds the panels and hinges the lines make and what is wrong with them. Its submenu
//! (Object › Plug-ins › Packaging Tools) and its Fold Lines panel are the UI's.
mod check;
mod roles;
pub(crate) use roles::{role_swatch_edited, role_swatches_merged};
@@ -11,7 +13,9 @@ pub(crate) use roles::{role_swatch_edited, role_swatches_merged};
use super::super::CommandSpec;
pub fn specs() -> Vec<CommandSpec> {
roles::specs()
let mut v = roles::specs();
v.extend(check::specs());
v
}
#[cfg(test)]
@@ -0,0 +1,179 @@
//! Check Fold Lines (`addon.packaging.check`): the blanks the fold lines make, their panels and
//! hinges, and what is wrong with the lines, found by [`vectorcraft_three_d::fold::blanks`].
use serde_json::{Value, json};
use vectorcraft_doc::{Document, Node, NodeId, NodeKind};
use vectorcraft_geom::PathData;
use vectorcraft_three_d::fold::{FoldLine, IssueCode, LineKind, MAX_SEGMENTS, blanks};
use super::super::super::pathops::length_given;
use super::super::super::{CommandSpec, bad, checked_ids_or_selection, cmd, has_doc, switch_or};
use super::roles::{Role, RoleTable, can_carry, role_targets};
use crate::{Result, Session};
const CHECK: &str = "addon.packaging.check";
/// How far apart the ends of two lines may be and still be joined, in points.
const TOLERANCE: (f64, f64, f64) = (0.01, 0.1, 10.0);
pub fn specs() -> Vec<CommandSpec> {
vec![cmd!(
"addon.packaging.check",
"Check Fold Lines",
["Object", "Plug-ins", "Packaging Tools"],
None,
"{ids?: [id…] (default: the selection), select?: bool (false), tolerance?: pt 0.01..10 (0.1)} check the fold lines (addon.packaging.roles) among the objects (through groups and clip groups), or, while nothing is selected and ids is left out, every fold line of the document; hidden lines are left out, also in a selected group. Cut lines bound the blanks: each connected piece of them that encloses material is one blank, its outline is its largest closed cut line, and a closed cut line inside it is a hole, so a slot drawn as a rectangle across the outline leaves the same material as a notch drawn in it; open cut lines that meet end to end count as one closed cut line. Crease, Partial Cut and Perforation lines divide a blank into panels; the pieces of them between two panels are that pair's hinge. A cut line end that comes within tolerance of another cut line is joined to it. Issues, in this order: noCut, open, looseEnd (errors), gap (a warning: the gap is closed), tooComplex (an error: more than 65,536 segments or 256 panels in a blank), cutOverCrease (an error), duplicate (two cut lines, or two lines that fold of any role), danglingCrease, noSplit, outside (wholly, or in part for tolerance or more), notStraight (a hinge's pieces are not on one straight line), sliver, ambiguous, loosePanel (joined to the largest panel by no chain of hinges), nonPrinting (warnings). With select, the objects the issues name become the selection, unless no issue names one. Changes nothing in the document → {ok (no error), blanks, panels, hinges, holes, issues: [{severity: error|warning, code, message (English), ids, at?: [x, y]}], scope: ids|selection|document}",
has_doc,
check
)]
}
/// The English message for an issue (the Fold Lines panel shows it in the interface language).
fn message(code: IssueCode, scope: &str) -> &'static str {
match code {
IssueCode::NoCut if scope == "document" => "No cut lines are in the document.",
IssueCode::NoCut if scope == "ids" => "No cut lines are among the given objects.",
IssueCode::NoCut => "No cut lines are in the selection.",
IssueCode::Open => "The cut lines do not enclose an area.",
IssueCode::LooseEnd => "A cut line ends without meeting another cut line.",
IssueCode::Gap => "A gap between cut lines was closed.",
IssueCode::TooComplex => "The fold lines are too complex to check.",
IssueCode::CutOverCrease => "A cut line and a crease lie on top of each other.",
IssueCode::Duplicate => "Two fold lines lie on top of each other.",
IssueCode::DanglingCrease => "A crease ends inside a panel.",
IssueCode::NoSplit => "A crease does not divide two panels.",
IssueCode::Outside => "A crease lies outside the cut outline, wholly or in part.",
IssueCode::NotStraight => "The pieces of a hinge are not on one straight line.",
IssueCode::Sliver => "A gap between cut lines is too narrow to tell apart.",
IssueCode::Ambiguous => "A cut-out area holds other fold lines or another blank.",
IssueCode::LoosePanel => "A panel is not joined to the rest by a crease.",
IssueCode::NonPrinting => "A fold line is on a non-printing layer.",
}
}
/// Every object of the document that can carry a role and is shown: on a shown layer, in shown
/// groups, and shown itself.
fn shown_targets(d: &Document) -> Vec<NodeId> {
fn walk(n: &Node, out: &mut Vec<NodeId>) {
if !n.visible {
return;
}
match &n.kind {
NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => children.iter().for_each(|c| walk(c, out)),
_ if can_carry(n) => out.push(n.id),
_ => {}
}
}
let mut out = vec![];
d.layers.iter().for_each(|l| walk(l, &mut out));
out
}
/// The path of object `n` in document coordinates: a path's own, or a compound path's members'.
fn path_of(n: &Node) -> Option<PathData> {
match &n.kind {
NodeKind::Path { path, .. } => Some(path.clone()),
NodeKind::Compound { children, .. } => Some(PathData::new(
children
.iter()
.filter_map(|c| match &c.kind {
NodeKind::Path { path, .. } => Some(path.subpaths.iter().cloned()),
_ => None,
})
.flatten()
.collect(),
)),
_ => None,
}
}
/// Whether object `id` is on a layer, or a sublayer, that does not print.
fn on_non_printing_layer(d: &Document, id: NodeId) -> bool {
d.ancestry(id).unwrap_or_default().iter().filter_map(|a| d.node(*a)).any(|n| matches!(n.kind, NodeKind::Layer { printable: false, .. }))
}
fn kind(role: Role) -> LineKind {
match role {
Role::Cut => LineKind::Cut,
Role::Crease => LineKind::Crease,
Role::PartialCut => LineKind::PartialCut,
Role::Perforation => LineKind::Perforation,
}
}
fn check(s: &mut Session, p: &Value) -> Result<Value> {
let select = switch_or(p, "select", false, CHECK)?;
let tolerance = match length_given(p, "tolerance", CHECK)? {
None => TOLERANCE.1,
Some(t) if (TOLERANCE.0..=TOLERANCE.2).contains(&t) => t,
Some(_) => return Err(bad(CHECK, format!("`tolerance` must be from {} to {} pt", TOLERANCE.0, TOLERANCE.2))),
};
let given = p.get("ids").is_some_and(|v| !v.is_null());
let roots = checked_ids_or_selection(s, p, CHECK)?;
let d = &s.doc()?.doc;
// Hidden lines are left out in every scope, members of a selected group included.
let shown = |ids: Vec<NodeId>| ids.into_iter().filter(|id| d.is_visible(*id)).collect::<Vec<_>>();
let (scope, targets) = match (given, roots.is_empty()) {
(true, _) => ("ids", shown(role_targets(d, &roots, false).0)),
(false, false) => ("selection", shown(role_targets(d, &roots, false).0)),
(false, true) => ("document", shown_targets(d)),
};
let table = RoleTable::of(d);
let mut lines = vec![];
let mut non_printing = vec![];
let mut segments = 0usize;
for id in targets {
// Once the lines have more segments than the check takes, it reports them as too complex:
// the rest are not copied.
if segments > MAX_SEGMENTS {
break;
}
let Some(n) = d.node(id) else { continue };
let (Some(role), Some(path)) = (table.role_of(n), path_of(n)) else { continue };
if on_non_printing_layer(d, id) {
non_printing.push(id.0);
}
segments = segments.saturating_add(path.subpaths.iter().map(|sp| sp.segment_count()).sum());
lines.push(FoldLine { path, kind: kind(role), key: id.0 });
}
let (found, mut issues) = blanks(&lines, tolerance);
if !non_printing.is_empty() {
issues.push(vectorcraft_three_d::fold::Issue { code: IssueCode::NonPrinting, keys: non_printing, at: None });
}
let ok = !issues.iter().any(|i| i.code.is_error());
let rows: Vec<Value> = issues
.iter()
.map(|i| {
let mut row = json!({
"severity": if i.code.is_error() { "error" } else { "warning" },
"code": i.code.id(),
"message": message(i.code, scope),
"ids": i.keys,
});
if let (Some(at), Some(o)) = (i.at, row.as_object_mut()) {
o.insert("at".into(), json!([at.x, at.y]));
}
row
})
.collect();
if select {
let mut ids: Vec<NodeId> = issues.iter().flat_map(|i| i.keys.iter().map(|k| NodeId(*k))).filter(|id| d.node(*id).is_some()).collect();
ids.sort_unstable_by_key(|id| id.0);
ids.dedup();
if !ids.is_empty() {
s.select(|_, sel| sel.set(ids.iter().copied()))?;
}
}
Ok(json!({
"ok": ok,
"blanks": found.len(),
"panels": found.iter().map(|b| b.panels.len()).sum::<usize>(),
"hinges": found.iter().map(|b| b.hinges.len()).sum::<usize>(),
"holes": found.iter().map(|b| b.holes.len()).sum::<usize>(),
"issues": rows,
"scope": scope,
}))
}
#[cfg(test)]
mod tests;
@@ -0,0 +1,180 @@
//! Tests for Check Fold Lines: the blanks, panels, hinges and issues of fold lines drawn in a
//! document.
use serde_json::{Value, json};
use crate::*;
fn session() -> Session {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 600, "height": 600})).unwrap();
s
}
fn path(s: &mut Session, d: &str) -> u64 {
s.execute("path.create", &json!({ "d": d })).unwrap()["id"].as_u64().unwrap()
}
fn role(s: &mut Session, role: &str, ids: &[u64]) {
s.execute("addon.packaging.setRole", &json!({ "role": role, "ids": ids })).unwrap();
}
fn check(s: &mut Session, p: Value) -> Value {
s.execute("addon.packaging.check", &p).unwrap()
}
fn codes(r: &Value) -> Vec<&str> {
r["issues"].as_array().unwrap().iter().map(|i| i["code"].as_str().unwrap()).collect()
}
/// A tray blank: a 100 pt base with a 40 pt wall on each side, its outline a cut line and the
/// base's four sides creases → (outline, creases).
fn tray(s: &mut Session) -> (u64, Vec<u64>) {
let outline = path(s, "M140 100 L240 100 L240 140 L280 140 L280 240 L240 240 L240 280 L140 280 L140 240 L100 240 L100 140 L140 140 Z");
let creases = vec![path(s, "M140 140 L240 140"), path(s, "M240 140 L240 240"), path(s, "M240 240 L140 240"), path(s, "M140 240 L140 140")];
role(s, "cut", &[outline]);
role(s, "crease", &creases);
s.execute("select.none", &json!({})).unwrap();
(outline, creases)
}
#[test]
fn a_tray_checks_clean_with_five_panels_and_four_hinges() {
let mut s = session();
tray(&mut s);
let steps = s.doc().unwrap().history.undo.len();
let r = check(&mut s, json!({}));
assert_eq!(r["ok"], true, "{r}");
assert_eq!((r["blanks"].as_u64(), r["panels"].as_u64(), r["hinges"].as_u64(), r["holes"].as_u64()), (Some(1), Some(5), Some(4), Some(0)), "{r}");
assert!(codes(&r).is_empty(), "{r}");
assert_eq!(r["scope"], "document");
assert_eq!(s.doc().unwrap().history.undo.len(), steps, "a check records no undo step");
}
#[test]
fn the_selection_or_ids_limit_the_check_to_their_lines() {
let mut s = session();
let (outline, creases) = tray(&mut s);
s.execute("select.set", &json!({ "ids": [creases[0]] })).unwrap();
let r = check(&mut s, json!({}));
assert_eq!((r["scope"].as_str(), r["ok"].as_bool()), (Some("selection"), Some(false)));
assert_eq!(codes(&r), ["noCut"]);
assert_eq!(r["issues"][0]["message"], "No cut lines are in the selection.");
let r = check(&mut s, json!({ "ids": [outline] }));
assert_eq!((r["scope"].as_str(), r["ok"].as_bool(), r["panels"].as_u64()), (Some("ids"), Some(true), Some(1)), "{r}");
let r = check(&mut s, json!({ "ids": [creases[1]] }));
assert_eq!((r["scope"].as_str(), codes(&r)), (Some("ids"), vec!["noCut"]));
assert_eq!(r["issues"][0]["message"], "No cut lines are among the given objects.");
// No fold lines at all in the document.
let mut s = session();
let r = check(&mut s, json!({}));
assert_eq!(codes(&r), ["noCut"]);
assert_eq!(r["issues"][0]["message"], "No cut lines are in the document.");
}
#[test]
fn issues_name_their_lines_and_select_selects_them() {
let mut s = session();
let (_, creases) = tray(&mut s);
// A slit from the outline that stops in the middle of the base.
let slit = path(&mut s, "M190 100 L190 190");
role(&mut s, "cut", &[slit]);
s.execute("select.none", &json!({})).unwrap();
let r = check(&mut s, json!({}));
assert_eq!(r["ok"], false);
let loose = r["issues"].as_array().unwrap().iter().find(|i| i["code"] == "looseEnd").cloned().unwrap();
assert_eq!((loose["severity"].as_str(), loose["ids"].clone()), (Some("error"), json!([slit])), "{r}");
assert_eq!(loose["at"], json!([190.0, 190.0]));
assert!(s.doc().unwrap().selection.objects.is_empty(), "without select, the selection stays");
let r = check(&mut s, json!({ "select": true }));
let named: std::collections::BTreeSet<u64> =
r["issues"].as_array().unwrap().iter().flat_map(|i| i["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap())).collect();
let selected: std::collections::BTreeSet<u64> = s.doc().unwrap().selection.objects.iter().map(|id| id.0).collect();
assert!(selected.contains(&slit) && selected == named, "{selected:?} {named:?}");
assert!(!selected.contains(&creases[1]));
}
#[test]
fn a_clean_check_with_select_leaves_the_selection_alone() {
let mut s = session();
let (outline, _) = tray(&mut s);
s.execute("select.set", &json!({ "ids": [outline] })).unwrap();
let r = check(&mut s, json!({ "ids": [outline], "select": true }));
assert!(codes(&r).is_empty(), "{r}");
assert_eq!(s.doc().unwrap().selection.objects.iter().map(|id| id.0).collect::<Vec<_>>(), [outline]);
}
#[test]
fn tolerance_is_checked_and_joins_gaps_up_to_it() {
let mut s = session();
tray(&mut s);
for bad in [json!(0.005), json!(10.5), json!("x"), json!(true)] {
let e = s.execute("addon.packaging.check", &json!({ "tolerance": bad })).unwrap_err().to_string();
assert!(e.contains("tolerance"), "{e}");
}
let e = s.execute("addon.packaging.check", &json!({ "select": 1 })).unwrap_err().to_string();
assert!(e.contains("select"), "{e}");
for edge in [json!(0.01), json!(10), json!("2 mm")] {
assert_eq!(check(&mut s, json!({ "tolerance": edge }))["ok"], true);
}
// A slit that stops 0.5 pt short of a crease: a gap at a tolerance of 1 pt, a loose end at 0.1 pt.
let mut s = session();
tray(&mut s);
let slit = path(&mut s, "M190 100 L190 139.5");
role(&mut s, "cut", &[slit]);
s.execute("select.none", &json!({})).unwrap();
assert!(codes(&check(&mut s, json!({ "tolerance": 0.1 }))).contains(&"looseEnd"));
let near = check(&mut s, json!({ "tolerance": 1 }));
assert!(!codes(&near).contains(&"looseEnd"), "{near}");
}
#[test]
fn hidden_lines_are_left_out_and_lines_on_a_non_printing_layer_are_noted() {
let mut s = session();
let (_, creases) = tray(&mut s);
// A hidden crease is not checked while nothing is selected: the tray has three hinges and a
// panel joined by none.
s.execute("layer.setProps", &json!({ "ids": [creases[0]], "visible": false })).unwrap();
s.execute("select.none", &json!({})).unwrap();
let r = check(&mut s, json!({}));
assert_eq!((r["panels"].as_u64(), r["hinges"].as_u64()), (Some(4), Some(3)), "{r}");
// The same in a selected group, and with the group named by `ids`: the hidden member is left
// out too.
let mut s = session();
let (outline, creases) = tray(&mut s);
s.execute("select.set", &json!({ "ids": [outline, creases[0], creases[1], creases[2], creases[3]] })).unwrap();
let group = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap();
s.execute("layer.setProps", &json!({ "ids": [creases[0]], "visible": false })).unwrap();
s.execute("select.set", &json!({ "ids": [group] })).unwrap();
for p in [json!({}), json!({ "ids": [group] })] {
let r = check(&mut s, p);
assert_eq!((r["panels"].as_u64(), r["hinges"].as_u64()), (Some(4), Some(3)), "{r}");
}
// A cut line on a layer that does not print.
let mut s = session();
s.execute("layer.new", &json!({ "printable": false })).unwrap();
let (outline, _) = tray(&mut s);
let r = check(&mut s, json!({}));
assert_eq!(r["ok"], true, "a warning only");
let note = r["issues"].as_array().unwrap().iter().find(|i| i["code"] == "nonPrinting").cloned().unwrap();
assert_eq!(note["severity"], "warning");
assert!(note["ids"].as_array().unwrap().contains(&json!(outline)), "{note}");
assert_eq!(note["message"], "A fold line is on a non-printing layer.");
}
#[test]
fn a_compound_path_and_a_grouped_line_are_checked() {
let mut s = session();
let (outline, creases) = tray(&mut s);
// A window: a closed cut line in the base, made a compound path with nothing else.
let window = path(&mut s, "M170 170 L210 170 L210 210 L170 210 Z");
s.execute("select.set", &json!({ "ids": [window] })).unwrap();
let compound = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64();
let window = compound.unwrap_or(window);
role(&mut s, "cut", &[window]);
s.execute("select.set", &json!({ "ids": [outline, creases[0], creases[1], creases[2], creases[3], window] })).unwrap();
s.execute("object.group", &json!({})).unwrap();
let r = check(&mut s, json!({}));
assert_eq!(r["scope"], "selection");
assert_eq!((r["ok"].as_bool(), r["panels"].as_u64(), r["holes"].as_u64()), (Some(true), Some(5), Some(1)), "{r}");
}
@@ -186,7 +186,7 @@ fn free_role_name(d: &Document, table: &RoleTable, role: Role) -> String {
/// Whether `n` can carry a role: a path (a live shape too) that is neither a clipping path nor a
/// guide, or a compound path.
fn can_carry(n: &Node) -> bool {
pub(super) fn can_carry(n: &Node) -> bool {
match &n.kind {
NodeKind::Path { clipping, guide, .. } => !clipping && !guide,
NodeKind::Compound { .. } => true,
@@ -199,7 +199,7 @@ fn can_carry(n: &Node) -> bool {
/// how many of `roots` and their members can't (text, images, symbol instances and other objects).
/// With `editable`, objects that are locked or hidden, are in a locked or hidden group or layer, or
/// are on a locked artboard are left out and counted as skipped.
fn role_targets(d: &Document, roots: &[NodeId], editable: bool) -> (Vec<NodeId>, usize) {
pub(super) fn role_targets(d: &Document, roots: &[NodeId], editable: bool) -> (Vec<NodeId>, usize) {
fn walk(n: &Node, out: &mut Vec<NodeId>, skipped: &mut usize) {
match &n.kind {
NodeKind::Group { children, .. } => {
+4 -1
View File
@@ -3,7 +3,8 @@
//! anchor edits, Split / Add Points at Crossings, Slide Anchor Along Path, the Corner Tool's corners
//! ([`corners`]), the Parametric Shape Tool's shapes ([`shape`]), the Shared Edge Merge Tool's
//! merges with Keep Shared Points Together ([`shared_edge`]), Divide into Dashes, Expand Dashes
//! into Paths, Trim at Crossings ([`trim`]) and Tangent Circle ([`tangent_circle`]).
//! into Paths, Trim at Crossings ([`trim`]), Common Tangents ([`tangents`]) and Tangent Circle
//! ([`tangent_circle`]).
//! Its tools, panels and submenu (Object › Plug-ins › Path Precision Tools) are the tools crate's
//! and the UI's.
@@ -13,6 +14,7 @@ mod effect_tests;
mod shape;
mod shared_edge;
mod tangent_circle;
mod tangents;
#[cfg(test)]
mod tests;
mod trim;
@@ -182,6 +184,7 @@ pub fn specs() -> Vec<CommandSpec> {
v.extend(shared_edge::specs());
v.extend(trim::specs());
v.extend(tangent_circle::specs());
v.extend(tangents::specs());
v
}
@@ -0,0 +1,131 @@
//! Common Tangents (`addon.pathtools.commonTangents`): the straight lines that touch two selected
//! convex closed paths (ellipses at any rotation and scale, and convex Bézier paths) without
//! crossing into either, added as separate open paths, with the line joining their centers if
//! asked. The geometry is `vectorcraft_pathops::addons::pathtools::common_tangents`.
#[cfg(test)]
mod tests;
use serde_json::{Value, json};
use vectorcraft_color::{Color, Paint};
use vectorcraft_doc::{AppearanceItem, Document, LiveShape, Node, NodeId, NodeKind};
use vectorcraft_geom::kurbo::Affine;
use vectorcraft_geom::{FillRule, PathData, Point, SubPath};
use vectorcraft_pathops::addons::pathtools as pt;
use super::super::super::object::choice;
use super::super::super::{CommandSpec, bad, checked_ids_or_selection, cmd, has_selection, switch_or};
use crate::{EngineError, Result, Session};
/// The command's id.
pub const COMMON_TANGENTS: &str = "addon.pathtools.commonTangents";
/// The undo step's name.
const LABEL: &str = "Common Tangents";
/// The kinds of tangent `tangents` picks.
const KINDS: [&str; 3] = ["external", "internal", "all"];
pub(super) fn specs() -> Vec<CommandSpec> {
vec![cmd!(
"addon.pathtools.commonTangents",
"Common Tangents",
["Object", "Plug-ins", "Path Precision Tools"],
None,
"{tangents?: \"external\" (both paths on the same side of each line) | \"internal\" (the lines that run between them) | \"all\" (\"all\"), centerline?: bool (false: true also adds the line joining the two centers, an ellipse's center or a path's center of area), ids?: [id, id] (default: the selection)} add the common tangent lines of two convex closed paths as separate open paths, each from where it touches the first path to where it touches the second (the whole stretch where a straight side lies along it), stroked with the current stroke color and weight (black when the stroke is None) and unfilled, directly above the upper of the two, as one undo step; the new lines are selected. An ellipse drawn with the Ellipse tool, turned or scaled, is measured as an exact ellipse; any other path must be closed, have one outline, bend the same way all around and have at most 10000 segments. Separate paths have two external and two internal tangents; overlapping paths only external ones; one path inside the other has none. Paths that touch, from outside or from inside, share one tangent there instead: a line centered on the point where they touch and as long as the narrower path is wide along it; paths that meet at a corner or along a shared stretch of outline get one such line, at the middle of the directions that touch both. Paths count as touching when the gap between them is less than a billionth of the larger of their sizes and the distance between their centers. When there is no tangent of the kind asked for, nothing changes and the result has a `warning` → {ids, external, internal, centerline (its id or null), warning?}",
has_selection,
common_tangents
)]
}
/// The outline of path `id` as the geometry takes it: an exact ellipse for a whole live ellipse,
/// else the path's one closed convex subpath.
fn outline_of(d: &Document, id: NodeId) -> Result<pt::Outline> {
const C: &str = COMMON_TANGENTS;
let n = d.node(id).ok_or(EngineError::NoNode(id))?;
let NodeKind::Path { path, live, .. } = &n.kind else { return Err(bad(C, "select two closed paths")) };
let [sp] = path.subpaths.as_slice() else { return Err(bad(C, "select two closed paths")) };
if let Some(LiveShape::Ellipse { w, h, pie, xf }) = live.as_deref() {
let span = (pie.1 - pie.0).rem_euclid(360.0);
if span < 1e-9 || 360.0 - span < 1e-9 {
let unit = *xf * Affine::new([w / 2.0, 0.0, 0.0, h / 2.0, w / 2.0, h / 2.0]);
return pt::Outline::ellipse(unit).map_err(refusal);
}
}
pt::Outline::convex(sp).map_err(refusal)
}
fn refusal(e: pt::OutlineError) -> EngineError {
bad(
COMMON_TANGENTS,
match e {
pt::OutlineError::Open => "a selected path is open",
pt::OutlineError::NotConvex => "a selected path is not convex",
pt::OutlineError::Empty => "a selected path has no area",
pt::OutlineError::TooComplex => "a selected path has more than 10000 segments",
},
)
}
fn common_tangents(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = COMMON_TANGENTS;
let kinds = choice(p, C, "tangents", &KINDS)?.unwrap_or("all");
let centerline = switch_or(p, "centerline", false, C)?;
let roots = checked_ids_or_selection(s, p, C)?;
let d = &s.doc()?.doc;
let ordered = d.paint_order(roots.iter().copied());
let [first, second] = ordered.as_slice() else { return Err(bad(C, "select two closed paths")) };
let (a, b) = (outline_of(d, *first)?, outline_of(d, *second)?);
let all = pt::common_tangents(&a, &b).map_err(|_| bad(C, "the two paths have the same outline"))?;
let external = all.iter().filter(|t| t.kind == pt::TangentKind::External).count();
let keep = |t: &&pt::Tangent| match kinds {
"external" => t.kind == pt::TangentKind::External,
"internal" => t.kind == pt::TangentKind::Internal,
_ => true,
};
let kept: Vec<&pt::Tangent> = all.iter().filter(keep).collect();
let count = |kind: pt::TangentKind| kept.iter().filter(|t| t.kind == kind).count();
let (external_kept, internal_kept) = (count(pt::TangentKind::External), count(pt::TangentKind::Internal));
let lines: Vec<(Point, Point)> = kept.iter().map(|t| (t.from, t.to)).collect();
if lines.is_empty() {
// Written as `EngineError::Other` so that the i18n message scan finds them. Exactly one
// external tangent means one path lies inside the other and touches it there; paths that
// overlap without one inside the other have at least two.
let warning = match external {
0 => EngineError::Other("One path lies inside the other, so they have no common tangents".into()),
1 => EngineError::Other("One path lies inside the other, so they have no internal tangents".into()),
_ => EngineError::Other("The paths overlap, so they have no internal tangents".into()),
};
return Ok(json!({ "ids": [], "external": 0, "internal": 0, "centerline": null, "warning": warning.to_string() }));
}
// Centers closer than a billionth of the larger path's size count as one point: no line.
let center = (centerline && (a.center() - b.center()).hypot() > 1e-9 * a.size().max(b.size())).then(|| (a.center(), b.center()));
let fill = Paint::None;
let stroke = if s.paint.stroke.is_none() { Paint::solid(Color::BLACK) } else { s.paint.stroke.clone() };
let mut look = s.new_art_look(fill, stroke, s.paint.stroke_width.max(0.1));
// The new art's look may carry more fills than the top one: none of them is kept.
look.appearance.items.retain(|i| !matches!(i, AppearanceItem::Fill(_)));
let top = *second;
let (ids, center_id) = s.edit(LABEL, |d, sel| {
let (parent, idx, _) = d.position(top).ok_or(EngineError::NoNode(top))?;
let mut ids = vec![];
let mut center_id = None;
for (k, (from, to)) in lines.iter().copied().chain(center).enumerate() {
let id = d.alloc_id();
let path = PathData::single(SubPath::polyline(&[from, to], false));
let mut n = Node::new(id, NodeKind::Path { path, rule: FillRule::NonZero, live: None, clipping: false, guide: false });
look.apply(d, &mut n);
d.insert(parent, idx + 1 + k, n)?;
if k == lines.len() {
center_id = Some(id);
}
ids.push(id);
}
sel.set(ids.iter().copied());
Ok((ids, center_id))
})?;
Ok(json!({
"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(),
"external": external_kept,
"internal": internal_kept,
"centerline": center_id.map(|i| i.0),
}))
}
@@ -0,0 +1,278 @@
//! Common Tangents: the lines for circles, turned ellipses and convex paths, the centerline,
//! the paint, one undo step, the cases with no tangent, and refused selections and params.
use serde_json::{Value, json};
use vectorcraft_color::{Color, Paint};
use vectorcraft_doc::{AppearanceItem, NodeId, NodeKind};
use vectorcraft_geom::{Point, Vec2};
use crate::Session;
const C: &str = super::COMMON_TANGENTS;
fn session() -> Session {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap();
s
}
fn id_of(v: &Value) -> NodeId {
NodeId(v["id"].as_u64().unwrap())
}
fn circle(s: &mut Session, cx: f64, cy: f64, r: f64) -> NodeId {
id_of(&s.execute("shape.ellipse", &json!({"x": cx - r, "y": cy - r, "width": 2.0 * r, "height": 2.0 * r})).unwrap())
}
fn select(s: &mut Session, ids: &[NodeId]) {
s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})).unwrap();
}
fn steps(s: &Session) -> usize {
s.doc().unwrap().history.undo.len()
}
/// The ends of each new line, as `ids` lists them.
fn lines(s: &Session, r: &Value) -> Vec<(Point, Point)> {
let d = &s.doc().unwrap().doc;
r["ids"]
.as_array()
.unwrap()
.iter()
.map(|v| {
let n = d.node(NodeId(v.as_u64().unwrap())).unwrap();
let NodeKind::Path { path, .. } = &n.kind else { panic!("not a path") };
assert_eq!(path.subpaths.len(), 1);
let sp = &path.subpaths[0];
assert!(!sp.closed);
assert_eq!(sp.anchors.len(), 2);
(sp.anchors[0].p, sp.anchors[1].p)
})
.collect()
}
fn near(p: Point, q: Point) -> bool {
p.distance(q) < 1e-6
}
fn has_line(found: &[(Point, Point)], p: Point, q: Point) -> bool {
found.iter().any(|(a, b)| (near(*a, p) && near(*b, q)) || (near(*a, q) && near(*b, p)))
}
#[test]
fn two_circles_get_four_tangents_at_the_exact_points_as_one_undo_step() {
let mut s = session();
let a = circle(&mut s, 100.0, 200.0, 20.0);
let b = circle(&mut s, 300.0, 200.0, 40.0);
select(&mut s, &[a, b]);
let before = steps(&s);
let r = s.execute(C, &json!({})).unwrap();
assert_eq!((r["external"].as_u64(), r["internal"].as_u64(), r["centerline"].is_null()), (Some(2), Some(2), true), "{r}");
assert_eq!(steps(&s), before + 1);
let found = lines(&s, &r);
assert_eq!(found.len(), 4);
let (c1, c2) = (Point::new(100.0, 200.0), Point::new(300.0, 200.0));
// External: (c1 - c2) · n = r2 - r1, n.x = -0.1; internal: (c1 - c2) · n = -(r1 + r2), n.x = 0.3.
for (nx, external) in [(-0.1f64, true), (0.3, false)] {
for sy in [1.0, -1.0] {
let n = Vec2::new(nx, sy * (1.0 - nx * nx).sqrt());
let far = if external { c2 + n * 40.0 } else { c2 - n * 40.0 };
assert!(has_line(&found, c1 + n * 20.0, far), "{n:?} in {found:?}");
}
}
// The lines are the selection, above the two circles.
let st = s.doc().unwrap();
assert_eq!(st.selection.objects.len(), 4);
let ids: Vec<NodeId> = r["ids"].as_array().unwrap().iter().map(|v| NodeId(v.as_u64().unwrap())).collect();
let order = st.doc.paint_order([a, b].into_iter().chain(ids.iter().copied()));
assert_eq!(&order[..2], &[a, b]);
s.execute("edit.undo", &json!({})).unwrap();
assert!(ids.iter().all(|id| s.doc().unwrap().doc.node(*id).is_none()), "one undo step removes them all");
}
#[test]
fn turned_ellipses_are_measured_exactly() {
let mut s = session();
let a = id_of(&s.execute("shape.ellipse", &json!({"x": 60, "y": 170, "width": 80, "height": 30})).unwrap());
select(&mut s, &[a]);
s.execute("object.rotate", &json!({"angle": 30, "origin": [100, 185]})).unwrap();
let b = id_of(&s.execute("shape.ellipse", &json!({"x": 330, "y": 120, "width": 50, "height": 120})).unwrap());
select(&mut s, &[b]);
s.execute("object.rotate", &json!({"angle": -70, "origin": [355, 180]})).unwrap();
select(&mut s, &[a, b]);
let r = s.execute(C, &json!({"tangents": "all"})).unwrap();
assert_eq!((r["external"].as_u64(), r["internal"].as_u64()), (Some(2), Some(2)), "{r}");
// Each end lies on its ellipse, where the ellipse runs along the line: turned back about the
// center, (x/rx)² + (y/ry)² = 1 and the gradient is square to the line.
let on = |p: Point, center: Point, rx: f64, ry: f64, deg: f64, dir: Vec2| {
let turn = vectorcraft_geom::kurbo::Affine::rotate(-deg.to_radians());
// `object.rotate` turns counter-clockwise on the page (y down): undo it in page terms.
let page = |v: Vec2| Vec2::new(v.x, -v.y);
let q = page((turn * page(p - center).to_point()).to_vec2());
let d = page((turn * page(dir).to_point()).to_vec2());
let value = (q.x / rx).powi(2) + (q.y / ry).powi(2);
let grad = Vec2::new(q.x / (rx * rx), q.y / (ry * ry));
(value - 1.0).abs() < 1e-9 && (grad.dot(d) / (grad.hypot() * d.hypot())).abs() < 1e-7
};
for (p, q) in lines(&s, &r) {
let dir = q - p;
assert!(on(p, Point::new(100.0, 185.0), 40.0, 15.0, 30.0, dir), "{p:?} on the first ellipse");
assert!(on(q, Point::new(355.0, 180.0), 25.0, 60.0, -70.0, dir), "{q:?} on the second ellipse");
}
}
#[test]
fn a_convex_bezier_path_and_the_centerline() {
let mut s = session();
let anchors = json!([
{"x": 0, "y": 40, "in": [0, 70], "out": [0, 10]},
{"x": 50, "y": 0, "in": [20, 0], "out": [90, 0]},
{"x": 110, "y": 50, "in": [110, 20], "out": [110, 90]},
{"x": 40, "y": 100, "in": [80, 100], "out": [10, 100]}
]);
let blob = id_of(&s.execute("path.create", &json!({"anchors": anchors, "closed": true})).unwrap());
let round = circle(&mut s, 300.0, 200.0, 30.0);
let r = s.execute(C, &json!({"ids": [blob.0, round.0], "centerline": true})).unwrap();
assert_eq!((r["external"].as_u64(), r["internal"].as_u64()), (Some(2), Some(2)), "{r}");
let found = lines(&s, &r);
assert_eq!(found.len(), 5, "four tangents and the centerline");
// The centerline is the last line and its id is given: from the blob's center of area to the
// circle's center.
assert_eq!(r["centerline"], r["ids"][4]);
let (from, to) = found[4];
assert!(near(to, Point::new(300.0, 200.0)), "{to:?}");
assert!(from.x > 30.0 && from.x < 80.0 && from.y > 30.0 && from.y < 70.0, "{from:?}");
// A tangent touches without crossing: every point of both paths is on one side of it.
let d = &s.doc().unwrap().doc;
let points = |id: NodeId| {
let sp = d.node(id).unwrap().path_data().unwrap().subpaths[0].clone();
let segments: Vec<_> = (0..sp.segment_count()).map(|k| sp.segment(k)).collect();
segments.iter().flat_map(|seg| (0..200).map(|j| vectorcraft_geom::kurbo::ParamCurve::eval(seg, j as f64 / 200.0))).collect::<Vec<_>>()
};
let (pa, pb) = (points(blob), points(round));
for (p, q) in &found[..4] {
let n = Vec2::new(-(q.y - p.y), q.x - p.x).normalize();
for pts in [&pa, &pb] {
let side: Vec<f64> = pts.iter().map(|x| (*x - *p).dot(n)).collect();
let (lo, hi) = side.iter().fold((f64::MAX, f64::MIN), |(lo, hi), v| (lo.min(*v), hi.max(*v)));
// The circle is measured as an exact circle, which its four curves follow to within
// about 0.03% of the radius.
assert!(lo > -1e-2 || hi < 1e-2, "crosses: {lo} .. {hi}");
}
}
}
#[test]
fn tiny_paths_close_together_still_get_the_centerline() {
// Two circles a ten-billionth of a point wide, half a billionth apart: separate, with all four
// tangents, and centers apart by far more than their sizes' rounding.
let mut s = session();
let a = circle(&mut s, 1.0, 1.0, 1e-10);
let b = circle(&mut s, 1.0 + 5e-10, 1.0, 1e-10);
let r = s.execute(C, &json!({"ids": [a.0, b.0], "centerline": true})).unwrap();
assert_eq!((r["external"].as_u64(), r["internal"].as_u64()), (Some(2), Some(2)), "{r}");
assert_eq!(r["ids"].as_array().map(Vec::len), Some(5), "{r}");
assert_eq!(r["centerline"], r["ids"][4]);
}
#[test]
fn the_lines_take_the_current_stroke_and_no_fill() {
let mut s = session();
let a = circle(&mut s, 100.0, 100.0, 20.0);
let b = circle(&mut s, 300.0, 100.0, 20.0);
s.execute("select.none", &json!({})).unwrap();
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
let r = s.execute(C, &json!({"ids": [a.0, b.0], "tangents": "external"})).unwrap();
assert_eq!((r["external"].as_u64(), r["internal"].as_u64()), (Some(2), Some(0)), "{r}");
let d = &s.doc().unwrap().doc;
for v in r["ids"].as_array().unwrap() {
let n = d.node(NodeId(v.as_u64().unwrap())).unwrap();
assert!(n.appearance.fill().is_none_or(|f| f.paint.is_none()), "no fill");
let st = n.appearance.stroke().expect("stroked");
assert!(!st.paint.is_none(), "black when the stroke is None");
}
// A new-art appearance with two fills and a stroke: the lines keep the stroke and neither fill.
let mut look = vectorcraft_doc::Appearance::basic(Paint::solid(Color::BLACK), Paint::solid(Color::BLACK), 2.0);
let fill = look.items.iter().find(|i| matches!(i, AppearanceItem::Fill(_))).cloned().unwrap();
look.items.push(fill);
s.paint.appearance = Some(look);
s.paint.inherited = false;
let r2 = s.execute(C, &json!({"ids": [a.0, b.0], "tangents": "external"})).unwrap();
let d2 = &s.doc().unwrap().doc;
for v in r2["ids"].as_array().unwrap() {
let n = d2.node(NodeId(v.as_u64().unwrap())).unwrap();
assert!(!n.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Fill(_))), "no fill at all");
assert!(n.appearance.stroke().is_some());
}
// Two equal circles: the external tangents run along their tops and bottoms.
assert!(has_line(&lines(&s, &r), Point::new(100.0, 80.0), Point::new(300.0, 80.0)));
assert!(has_line(&lines(&s, &r), Point::new(100.0, 120.0), Point::new(300.0, 120.0)));
}
#[test]
fn nested_and_overlapping_paths_change_nothing_and_say_why() {
let mut s = session();
let big = circle(&mut s, 200.0, 200.0, 100.0);
let small = circle(&mut s, 220.0, 200.0, 20.0);
let before = (steps(&s), s.doc().unwrap().doc.node_count());
let r = s.execute(C, &json!({"ids": [big.0, small.0]})).unwrap();
assert_eq!(r["ids"], json!([]));
assert!(r["warning"].as_str().unwrap().contains("inside the other"), "{r}");
assert_eq!((steps(&s), s.doc().unwrap().doc.node_count()), before, "nothing changes");
// Overlapping circles have external tangents only.
let a = circle(&mut s, 100.0, 100.0, 30.0);
let b = circle(&mut s, 140.0, 100.0, 30.0);
let before = (steps(&s), s.doc().unwrap().doc.node_count());
let r = s.execute(C, &json!({"ids": [a.0, b.0], "tangents": "internal"})).unwrap();
assert!(r["warning"].as_str().unwrap().contains("overlap"), "{r}");
assert_eq!((steps(&s), s.doc().unwrap().doc.node_count()), before);
let r = s.execute(C, &json!({"ids": [a.0, b.0]})).unwrap();
assert_eq!((r["external"].as_u64(), r["internal"].as_u64()), (Some(2), Some(0)), "{r}");
// Circles that touch share the tangent where they touch.
let c = circle(&mut s, 100.0, 300.0, 10.0);
let e = circle(&mut s, 130.0, 300.0, 20.0);
let r = s.execute(C, &json!({"ids": [c.0, e.0], "tangents": "internal"})).unwrap();
assert_eq!(r["internal"].as_u64(), Some(1), "{r}");
let (p, q) = lines(&s, &r)[0];
assert!((p.x - 110.0).abs() < 1e-5 && (q.x - 110.0).abs() < 1e-5 && (p.distance(q) - 20.0).abs() < 1e-5, "{p:?} {q:?}");
// A circle touching the inside of a larger one: no internal tangent, and the message says the
// one lies inside the other rather than that they overlap.
let outer = circle(&mut s, 400.0, 200.0, 50.0);
let inner = circle(&mut s, 430.0, 200.0, 20.0);
let before = (steps(&s), s.doc().unwrap().doc.node_count());
let r = s.execute(C, &json!({"ids": [outer.0, inner.0], "tangents": "internal"})).unwrap();
assert_eq!(r["ids"], json!([]));
assert!(r["warning"].as_str().unwrap().contains("inside the other, so they have no internal"), "{r}");
assert_eq!((steps(&s), s.doc().unwrap().doc.node_count()), before);
let r = s.execute(C, &json!({"ids": [outer.0, inner.0]})).unwrap();
assert_eq!((r["external"].as_u64(), r["internal"].as_u64()), (Some(1), Some(0)), "{r}");
}
#[test]
fn bad_selections_and_params_are_refused() {
let mut s = session();
let a = circle(&mut s, 100.0, 100.0, 20.0);
let b = circle(&mut s, 300.0, 100.0, 20.0);
let star = id_of(&s.execute("shape.star", &json!({"cx": 200, "cy": 300, "radius1": 40, "radius2": 15, "points": 5})).unwrap());
let open = id_of(&s.execute("path.create", &json!({"anchors": [{"x": 0, "y": 0}, {"x": 50, "y": 0}, {"x": 50, "y": 50}]})).unwrap());
let group_of = |s: &mut Session, ids: &[NodeId]| {
select(s, ids);
id_of(&s.execute("object.group", &json!({})).unwrap())
};
let before = (steps(&s), s.doc().unwrap().doc.node_count());
let err = |s: &mut Session, p: Value| s.execute(C, &p).unwrap_err().to_string();
assert!(err(&mut s, json!({"ids": [a.0, b.0], "tangents": "both"})).contains("tangents"));
assert!(err(&mut s, json!({"ids": [a.0, b.0], "tangents": 3})).contains("tangents"));
assert!(err(&mut s, json!({"ids": [a.0, b.0], "centerline": "yes"})).contains("centerline"));
assert!(err(&mut s, json!({"ids": [a.0, b.0], "which": "all"})).contains("which"), "unknown keys are refused");
assert!(err(&mut s, json!({"ids": [a.0]})).contains("select two closed paths"));
assert!(err(&mut s, json!({"ids": [a.0, b.0, star.0]})).contains("select two closed paths"));
assert!(err(&mut s, json!({"ids": [a.0, star.0]})).contains("not convex"));
assert!(err(&mut s, json!({"ids": [a.0, open.0]})).contains("open"));
assert!(s.execute(C, &json!({"ids": [a.0, a.0]})).is_err(), "the same path twice");
assert_eq!((steps(&s), s.doc().unwrap().doc.node_count()), before, "nothing changes");
let copy = id_of(&s.execute("shape.ellipse", &json!({"x": 80, "y": 80, "width": 40, "height": 40})).unwrap());
assert!(err(&mut s, json!({"ids": [a.0, copy.0]})).contains("same outline"));
let g = group_of(&mut s, &[b]);
assert!(err(&mut s, json!({"ids": [a.0, g.0]})).contains("select two closed paths"));
}
+3
View File
@@ -27,6 +27,9 @@ use crate::EngineError;
/// Whether Reset Transformation changes a symbol instance.
pub use symbols::reset_transformation_changes;
/// The Symbols panel's current symbol, as `symbol.list` answers it.
pub use symbols::current_symbol;
mod brushes;
mod dynamic;
mod symbols;
+12 -11
View File
@@ -162,7 +162,7 @@ pub(super) fn symbol_sort(s: &mut Session, _: &Value) -> Result<Value> {
if d.symbols.is_sorted_by_key(key) {
return ok();
}
let current = current_symbol(d).or_else(|| symbol_names(d).into_iter().next());
let current = current_symbol(d);
s.edit("Sort by Name", |d, _| {
if let Some(name) = current {
d.unknown.insert(CURRENT_SYMBOL.into(), json!(name));
@@ -173,12 +173,15 @@ pub(super) fn symbol_sort(s: &mut Session, _: &Value) -> Result<Value> {
ok()
}
fn symbol_names(d: &Document) -> Vec<String> {
d.symbols.iter().map(|s| s.name.clone()).collect()
}
fn current_symbol(d: &Document) -> Option<String> {
d.unknown.get(CURRENT_SYMBOL).and_then(Value::as_str).filter(|n| d.symbols.iter().any(|s| s.name == *n)).map(str::to_string)
/// The Symbols panel's current symbol, as `symbol.list` answers it: the stored current symbol
/// while `d` has a symbol of that name, else the first symbol; `None` when `d` has no symbols.
pub fn current_symbol(d: &Document) -> Option<String> {
d.unknown
.get(CURRENT_SYMBOL)
.and_then(Value::as_str)
.filter(|n| d.symbols.iter().any(|s| s.name == *n))
.or_else(|| d.symbols.first().map(|s| s.name.as_str()))
.map(str::to_string)
}
pub(super) fn symbol_list(s: &mut Session, _: &Value) -> Result<Value> {
@@ -200,7 +203,7 @@ pub(super) fn symbol_list(s: &mut Session, _: &Value) -> Result<Value> {
})
})
.collect();
Ok(json!({ "symbols": list, "current": current_symbol(d).or_else(|| symbol_names(d).into_iter().next()) }))
Ok(json!({ "symbols": list, "current": current_symbol(d) }))
}
/// Store `art` ([`normalize`]d, of natural size `size`) as symbol `name`, which becomes the
@@ -398,9 +401,7 @@ fn resolve_symbol(d: &Document, p: &Value, cmd: &str) -> Result<String> {
match str_param(p, "name") {
Some(n) if d.symbols.iter().any(|s| s.name == n) => Ok(n.to_string()),
Some(n) => Err(bad(cmd, format!("no symbol named `{n}`"))),
None => {
current_symbol(d).or_else(|| symbol_names(d).into_iter().next()).ok_or_else(|| EngineError::Other("the document has no symbols".into()))
}
None => current_symbol(d).ok_or_else(|| EngineError::Other("the document has no symbols".into())),
}
}
+1 -1
View File
@@ -126,7 +126,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Live Paint Bucket (Stroke)",
[],
None,
"{group: id, point: [x,y], color?|swatch?|none? (default: current stroke), width?: pt (default: current weight), tolerance?: pt (4), scope?: \"one\" (default: the edge alone) | \"connected\" (a double-click: also each edge joined to it, end to end, through edges that draw with stroke paint match) | \"samePaint\" (a triple-click: also every edge of the group that draws with stroke paint match), match?: paint (as the document stores it; scope connected or samePaint only; default: the stroke paint the edge draws with; an edge draws with the paint of its topmost stroke that is shown, with paint, above 0 pt and not fully transparent, and with none when the edge is fully transparent or has no such stroke), through?: [id…] (scope connected only; at most 4096 of the group's edges, each given once, counted as drawing with stroke paint match whatever they draw with, such as another edge a double-click's clicks painted; any other id is an error), tint?: 0..100, keepModel?: bool (both as paint.setFill)} paint the edge nearest point, skipping hidden edges: each edge reached has its strokes replaced by one stroke with the paint and width, shown, fully opaque and blending normally, in the place of its topmost stroke and with the dashes, caps and arrowheads of its topmost shown stroke (a new stroke above the fills when it has none; none leaves one stroke of none), and its fills stay as they are; when every edge it reaches already has only that one stroke (at any width for none), nothing changes (no undo step, and the recent colors stay as they are) → {group, edge, count (edges reached)}",
"{group: id, point: [x,y], color?|swatch?|none? (default: current stroke), width?: pt (default: current weight), tolerance?: pt (4), points?: [[x,y]…] (a drag polyline starting at point; 1 to 4096 finite canvas points; also paints every edge of the group, hidden edges skipped, that the polyline crosses or comes within 0.0001 pt of), continuation?: [[[x,y]…]…] (further path chunks of 1 to 4096 finite canvas points each; each starts at the preceding chunk's last point; requires points), scope?: \"one\" (default: the edge alone) | \"connected\" (a double-click: also each edge joined to it, end to end, through edges that draw with stroke paint match) | \"samePaint\" (a triple-click: also every edge of the group that draws with stroke paint match; \"connected\" and \"samePaint\" are refused with points), match?: paint (as the document stores it; scope connected or samePaint only; default: the stroke paint the edge draws with; an edge draws with the paint of its topmost stroke that is shown, with paint, above 0 pt and not fully transparent, and with none when the edge is fully transparent or has no such stroke), through?: [id…] (scope connected only; at most 4096 of the group's edges, each given once, counted as drawing with stroke paint match whatever they draw with, such as another edge a double-click's clicks painted; any other id is an error), tint?: 0..100, keepModel?: bool (both as paint.setFill)} paint the edge nearest point, skipping hidden edges: each edge reached has its strokes replaced by one stroke with the paint and width, shown, fully opaque and blending normally, in the place of its topmost stroke and with the dashes, caps and arrowheads of its topmost shown stroke (a new stroke above the fills when it has none; none leaves one stroke of none), and its fills stay as they are; when every edge it reaches already has only that one stroke (at any width for none), nothing changes (no undo step, and the recent colors stay as they are) → {group, edge, count (edges reached)}",
has_doc,
lp_stroke_edge
),
+49 -22
View File
@@ -409,43 +409,61 @@ fn match_param(p: &Value, c: &str, allowed: bool, scopes: &str) -> Result<Option
serde_json::from_value::<super::Paint>(v.clone()).map(Some).map_err(|_| bad(c, "match must be a paint as the document stores it"))
}
pub(super) fn lp_fill(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "livePaint.fill";
let pt = point_param(p, "point").filter(|q| finite(*q)).ok_or_else(|| bad(C, "missing point [x,y]"))?;
let scope = scope_param(p, C)?;
let like = match_param(p, C, scope == LpScope::SamePaint, "\"samePaint\"")?;
/// The drag path of `livePaint.fill` or `livePaint.strokeEdge` (command `c`) pressed at `start`:
/// `points` followed by each chunk of `continuation`, where every chunk holds 1 to
/// [`b::LP_FILL_CHUNK_POINTS`] finite canvas points and starts at the last point of the chunk
/// before it (`points` at `start`). None when `points` is left out. With a `scope` other than
/// `one`, `points` is an error.
fn path_param(p: &Value, c: &str, start: Point, scope: LpScope) -> Result<Option<Vec<Vec<Point>>>> {
if scope != LpScope::One && p.get("points").is_some() {
return Err(bad(C, "scope applies to a click: leave out points"));
return Err(bad(c, "scope applies to a click: leave out points"));
}
let parse_chunk = |input: &Value, start: Point| -> Result<Vec<Point>> {
let values = input
.as_array()
.filter(|points| !points.is_empty() && points.len() <= b::LP_FILL_CHUNK_POINTS)
.ok_or_else(|| bad(C, "each path chunk must contain 1 to 4096 points"))?;
.ok_or_else(|| bad(c, "each path chunk must contain 1 to 4096 points"))?;
let points: Vec<_> = values
.iter()
.map(|point| {
let pair = point.as_array().filter(|pair| pair.len() == 2).ok_or_else(|| bad(C, "points must be [x,y] pairs"))?;
let x = pair.first().and_then(Value::as_f64).ok_or_else(|| bad(C, "point x must be a number"))?;
let y = pair.get(1).and_then(Value::as_f64).ok_or_else(|| bad(C, "point y must be a number"))?;
let pair = point.as_array().filter(|pair| pair.len() == 2).ok_or_else(|| bad(c, "points must be [x,y] pairs"))?;
let x = pair.first().and_then(Value::as_f64).ok_or_else(|| bad(c, "point x must be a number"))?;
let y = pair.get(1).and_then(Value::as_f64).ok_or_else(|| bad(c, "point y must be a number"))?;
let point = Point::new(x, y);
if !finite(point) {
return Err(bad(C, "points must be finite canvas points"));
return Err(bad(c, "points must be finite canvas points"));
}
Ok(point)
})
.collect::<Result<_>>()?;
if points.first() != Some(&start) {
return Err(bad(C, "path chunks must share their boundary point"));
return Err(bad(c, "path chunks must share their boundary point"));
}
Ok(points)
};
let points = p.get("points");
let Some(points) = p.get("points") else {
return if p.get("continuation").is_some() { Err(bad(c, "continuation requires points")) } else { Ok(None) };
};
let continuation = match p.get("continuation") {
None => &[][..],
Some(input) if points.is_some() => input.as_array().ok_or_else(|| bad(C, "continuation must be an array of path chunks"))?.as_slice(),
Some(_) => return Err(bad(C, "continuation requires points")),
Some(input) => input.as_array().ok_or_else(|| bad(c, "continuation must be an array of path chunks"))?.as_slice(),
};
let mut chunks: Vec<Vec<Point>> = Vec::with_capacity(continuation.len() + 1);
let mut last = start;
for input in std::iter::once(points).chain(continuation) {
let chunk = parse_chunk(input, last)?;
last = chunk.last().copied().unwrap_or(last);
chunks.push(chunk);
}
Ok(Some(chunks))
}
pub(super) fn lp_fill(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "livePaint.fill";
let pt = point_param(p, "point").filter(|q| finite(*q)).ok_or_else(|| bad(C, "missing point [x,y]"))?;
let scope = scope_param(p, C)?;
let like = match_param(p, C, scope == LpScope::SamePaint, "\"samePaint\"")?;
let path = path_param(p, C, pt, scope)?;
crate::cmd::paint::check_keep_model(p, C)?;
let paint = paint_from(s, p)?.unwrap_or_else(|| s.paint.fill.clone());
let group = object_param(p, "group", C)?;
@@ -472,7 +490,7 @@ pub(super) fn lp_fill(s: &mut Session, p: &Value) -> Result<Value> {
targets.extend(b::faces(n).into_iter().filter(|f| f.visible && f.appearance.fill_paint() == like).map(|f| f.id));
}
}
if let Some(points) = points {
if let Some(chunks) = &path {
let n = d.node(gid).ok_or(EngineError::NoNode(gid))?;
// Use the existing region-crossing probes, so even a face narrower than the distance
// between pointer events is filled. Reversing matches visible_face_at's front first.
@@ -488,11 +506,8 @@ pub(super) fn lp_fill(s: &mut Session, p: &Value) -> Result<Value> {
}
}
let map = b::BuilderMap { regions, ..Default::default() };
let mut last = pt;
for input in std::iter::once(points).chain(continuation) {
let chunk = parse_chunk(input, last)?;
last = chunk.last().copied().unwrap_or(last);
targets.extend(map.hits_along(&chunk, None).regions.iter().filter_map(|i| face_ids.get(*i).copied()));
for chunk in chunks {
targets.extend(map.hits_along(chunk, None).regions.iter().filter_map(|i| face_ids.get(*i).copied()));
}
}
Ok((fid, targets))
@@ -567,6 +582,7 @@ pub(super) fn lp_stroke_edge(s: &mut Session, p: &Value) -> Result<Value> {
let tol = number_or(p, "tolerance", 4.0, C)?.clamp(0.0, 1000.0);
let scope = scope_param(p, C)?;
let like = match_param(p, C, scope != LpScope::One, "\"connected\" or \"samePaint\"")?;
let path = path_param(p, C, pt, scope)?;
let through: Vec<NodeId> = match p.get("through") {
None => vec![],
Some(_) if scope != LpScope::Connected => return Err(bad(C, "through applies to scope \"connected\"")),
@@ -590,7 +606,18 @@ pub(super) fn lp_stroke_edge(s: &mut Session, p: &Value) -> Result<Value> {
let eid = start.id;
let like = like.unwrap_or_else(|| b::lp_stroke_paint(start));
let targets = match scope {
LpScope::One => vec![eid],
// A drag also reaches every edge of the group that is not hidden and that its path
// crosses or touches.
LpScope::One => std::iter::once(eid)
.chain(
path.as_deref()
.map(|chunks| b::visible_edges_along(n, chunks))
.unwrap_or_default()
.into_iter()
.map(|e| e.id)
.filter(|id| *id != eid),
)
.collect(),
LpScope::Connected => b::connected_edges_through(n, eid, &like, &through),
LpScope::SamePaint => std::iter::once(eid)
.chain(b::edges(n).into_iter().filter(|e| e.visible && e.id != eid && b::lp_stroke_paint(e) == like).map(|e| e.id))
+1 -1
View File
@@ -703,7 +703,7 @@ impl Relink {
self.name(Res::ParaStyle, s);
}
}
for r in [&mut l.values_rows, &mut l.categories_rows, &mut l.legend_rows].into_iter().flatten() {
for r in [&mut l.values_rows, &mut l.categories_rows, &mut l.legend_rows, &mut l.axis_rows, &mut l.ring_rows].into_iter().flatten() {
r.paint.fill.iter_mut().chain(r.paint.stroke.iter_mut()).for_each(|p| self.paint(p));
}
}
+51 -19
View File
@@ -64,7 +64,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Arc",
[],
None,
"{x1, y1, x2, y2, closed?, slope?} or {x, y, lengthX, lengthY, reference?, baseAlong?: x|y, slope?, closed?, fillArc?} → {id}",
"{x1, y1, x2, y2, closed?, slope?: −100…100 (default 100), rotation?: deg clockwise about (x1, y1)} or {x, y, lengthX, lengthY, reference?: 0–8 (default 0), baseAlong?: x|y (either case; default x), slope?: −100…100 (default 50), closed?, fillArc?, rotation?: deg clockwise about the reference point (x, y)} (0: upright); a reference or baseAlong given as anything else (null included) or a slope outside its range is an error and draws nothing → {id}",
has_doc,
arc
),
@@ -73,7 +73,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Rectangular Grid",
[],
None,
"{x, y, width, height, rows=5, columns=5, rowSkew=0, columnSkew=0 (−500…500 %: + crowds the horizontal dividers toward the top, the vertical ones toward the right), frame=true (the outside as one rectangle, else its four sides), fill=false (the current fill, else none), rotation?: deg clockwise about the centre (0: upright)} → {id}",
"{x, y, width, height, rows=5, columns=5 (whole numbers; at most 999), rowSkew=0, columnSkew=0 (−500…500 %: + crowds the horizontal dividers toward the top, the vertical ones toward the right), frame=true (the outside as one rectangle, else its four sides), fill=false (the current fill, else none), rotation?: deg clockwise about the centre (0: upright)} → {id}",
has_doc,
rect_grid
),
@@ -82,7 +82,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Polar Grid",
[],
None,
"{x, y, width, height, concentric=5, radial=5, concentricSkew=0, radialSkew=0 (−500…500 %: + crowds the ellipses toward the outside, the radial dividers clockwise of the top one), compound=false (the ellipses pair up into compound-path rings), fill=false (the current fill, else none), rotation?: deg clockwise about the centre (0: upright)} → {id}",
"{x, y, width, height, concentric=5, radial=5 (whole numbers; at most 999), concentricSkew=0, radialSkew=0 (−500…500 %: + crowds the ellipses toward the outside, the radial dividers clockwise of the top one), compound=false (the ellipses pair up into compound-path rings), fill=false (the current fill, else none), rotation?: deg clockwise about the centre (0: upright)} → {id}",
has_doc,
polar_grid
),
@@ -299,7 +299,8 @@ fn path_kind(path: PathData, live: Option<LiveShape>) -> NodeKind {
/// (<https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/rotate-objects-by-specific-angles.html>):
/// 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; a polygon or star turns its base orientation about its centre. The params as they are at
/// 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
/// 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;
@@ -318,6 +319,9 @@ pub fn constrain_click(s: &Session, cmd: &str, mut params: Value, pivot: Point)
"shape.polygon" | "shape.star" => {
o.insert("rotation".into(), json!(rotation));
}
"shape.arc" if o.contains_key("lengthX") || o.contains_key("lengthY") => {
o.insert("rotation".into(), json!(rotation));
}
_ => {}
}
params
@@ -590,26 +594,56 @@ fn spiral(s: &mut Session, p: &Value) -> Result<Value> {
}
fn arc(s: &mut Session, p: &Value) -> Result<Value> {
let rotation = if p.get("rotation").is_some() { f64_req(p, "rotation", "shape.arc")? } else { 0.0 };
if !rotation.is_finite() {
return Err(bad("shape.arc", "rotation must be finite"));
}
let closed = switch_or(p, "closed", false, "shape.arc")?;
let fill_arc = switch_or(p, "fillArc", false, "shape.arc")?;
let base_x = !matches!(p.get("baseAlong").and_then(Value::as_str), Some("y" | "Y"));
let path = if p.get("lengthX").is_some() || p.get("lengthY").is_some() {
// Given values are checked in both forms, null included; only a left-out key takes its default.
let base_x = match p.get("baseAlong") {
None => true,
Some(Value::String(v)) if v.eq_ignore_ascii_case("x") || v.eq_ignore_ascii_case("y") => v.eq_ignore_ascii_case("x"),
Some(_) => return Err(bad("shape.arc", "`baseAlong` must be one of x, y")),
};
let reference = match p.get("reference") {
None => 0,
Some(v) => match (v.as_u64(), v.as_f64()) {
(Some(n), _) if n <= 8 => n as usize,
(None, Some(x)) if (0.0..=8.0).contains(&x) && x.fract() == 0.0 => x as usize,
_ => return Err(bad("shape.arc", "`reference` must be a whole number from 0 to 8")),
},
};
let slope = |default: f64| {
let (key, lo, hi) = ("slope", -100.0, 100.0);
let v = number_or(p, key, default, "shape.arc")?;
if (lo..=hi).contains(&v) { Ok(v) } else { Err(bad("shape.arc", format!("`{key}` must be from {lo} to {hi}, not {v}"))) }
};
// The upright path, and the point `rotation` turns it about.
let (path, pivot) = if p.get("lengthX").is_some() || p.get("lengthY").is_some() {
let anchor = Point::new(f64_req(p, "x", "shape.arc")?, f64_req(p, "y", "shape.arc")?);
let reference = p.get("reference").and_then(Value::as_u64).unwrap_or(0) as usize;
shapes::arc_segment(
let path = shapes::arc_segment(
anchor,
reference,
number_or(p, "lengthX", 100.0, "shape.arc")?,
number_or(p, "lengthY", 100.0, "shape.arc")?,
base_x,
number_or(p, "slope", 50.0, "shape.arc")?,
slope(50.0)?,
closed,
)
);
(path, anchor)
} else {
let a = Point::new(f64_req(p, "x1", "shape.arc")?, f64_req(p, "y1", "shape.arc")?);
let b = Point::new(f64_req(p, "x2", "shape.arc")?, f64_req(p, "y2", "shape.arc")?);
let slope = number_or(p, "slope", 100.0, "shape.arc")?;
shapes::arc(a, b, slope, closed, base_x)
(shapes::arc(a, b, slope(100.0)?, closed, base_x), a)
};
// 0 and whole turns leave the path as it is; quarter turns are exact.
let bbox_angle = bbox_turn(rotation);
let path = if bbox_angle == 0.0 {
path
} else {
let c = pivot.to_vec2();
path.transformed(Affine::translate(c) * vectorcraft_geom::rotate_deg(rotation) * Affine::translate(-c))
};
let fill = if fill_arc { s.paint.fill.clone() } else { vectorcraft_color::Paint::None };
let look = s.new_art_look(
@@ -617,7 +651,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),
);
add_look(s, "Arc", path_kind(path, None), look, None)
insert_look_turned(s, "Arc", path_kind(path, None), look, None, true, bbox_angle)
}
/// The grid `paths` (bottom first) as one selected group in the new-art stroke, filled with the
@@ -655,13 +689,11 @@ fn grid_group(s: &mut Session, label: &str, (paths, bbox_angle): (Vec<PathData>,
Ok(json!({ "id": id.0 }))
}
/// A grid's divider count `count` (an error unless it is a number or null; 5 unless it is a JSON
/// whole number of 0 or more, so 4.0 gives 4 and 2.5 gives 5; at most 999) with its skew `key` in percent (0 when
/// absent, clamped to ±[`shapes::GRID_SKEW_MAX`]).
/// A grid's divider count `count` (5 when absent or null; a whole number of 0 or more, so 4.0 gives
/// 4, and anything else, such as 2.5, -1 or `"3"`, is an error; at most 999) with its skew `key` in
/// percent (0 when absent, clamped to ±[`shapes::GRID_SKEW_MAX`]).
fn dividers(p: &Value, count: &str, key: &str, cmd: &str) -> Result<(u32, f64)> {
check_numbers(p, &[count], cmd)?;
let whole = |v: &Value| v.as_u64().or_else(|| v.as_f64().filter(|f| f.is_finite() && *f >= 0.0 && f.fract() == 0.0).map(|f| f as u64));
let n = p.get(count).and_then(whole).unwrap_or(5).min(999) as u32;
let n = count_or(p, count, 5, cmd)?.min(999) as u32;
let skew = match p.get(key) {
None | Some(Value::Null) => 0.0,
Some(v) => v.as_f64().filter(|v| v.is_finite()).ok_or_else(|| bad(cmd, format!("`{key}` must be a number")))?,
+70 -6
View File
@@ -1498,9 +1498,41 @@ mod tests {
s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
s.execute("swatch.new", &json!({"name": "Ink", "color": {"model": "cmyk", "c": 0, "m": 1, "y": 1, "k": 0}, "spot": true})).unwrap();
let mut bytes = Vec::new();
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(2, 1, vec![0, 255]).unwrap())
.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png)
.unwrap();
{
let __dyn: image::DynamicImage = image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(2, 1, vec![0, 255]).unwrap());
let (__w, __h) = (__dyn.width(), __dyn.height());
let (__layout, __sample, __raw) = match __dyn {
image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLuma16(b) => (
craft_image_codecs::ChannelLayout::Gray,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageLumaA16(b) => (
craft_image_codecs::ChannelLayout::GrayA,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgb16(b) => (
craft_image_codecs::ChannelLayout::Rgb,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgba16(b) => (
craft_image_codecs::ChannelLayout::Rgba,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()),
};
let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap();
craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default())
.map(|__b| bytes.extend_from_slice(&__b))
}
.unwrap();
let image = s
.edit("Place", |d, sel| {
d.images.insert("gray".into(), vectorcraft_doc::ImageBlob::png(bytes));
@@ -1655,9 +1687,41 @@ mod tests {
s.execute("paint.setStroke", &json!({"ids": [word], "none": true})).unwrap();
// A grayscale image colorized with the spot color.
let mut bytes = Vec::new();
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(2, 1, vec![0, 255]).unwrap())
.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png)
.unwrap();
{
let __dyn: image::DynamicImage = image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(2, 1, vec![0, 255]).unwrap());
let (__w, __h) = (__dyn.width(), __dyn.height());
let (__layout, __sample, __raw) = match __dyn {
image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLuma16(b) => (
craft_image_codecs::ChannelLayout::Gray,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageLumaA16(b) => (
craft_image_codecs::ChannelLayout::GrayA,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgb16(b) => (
craft_image_codecs::ChannelLayout::Rgb,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgba16(b) => (
craft_image_codecs::ChannelLayout::Rgba,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()),
};
let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap();
craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default())
.map(|__b| bytes.extend_from_slice(&__b))
}
.unwrap();
let image = s
.edit("Place", |d, sel| {
d.images.insert("gray".into(), vectorcraft_doc::ImageBlob::png(bytes));
+1 -1
View File
@@ -31,6 +31,6 @@ mod freehand;
mod smooth;
pub use commands::specs;
pub(super) use common::{ids_json, replace_with_pieces, usize_opt};
pub(super) use common::{center_strokes, ids_json, replace_with_pieces, usize_opt};
pub(super) use cut::{components, erase_outline};
pub(super) use freehand::freehand_brushed;
+2 -2
View File
@@ -74,7 +74,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Split Path",
[],
None,
"{id, subpath?, segment, t} or {id, subpath?, anchor}: closed paths open there, open paths become two; one of the two new end points is left selected → {ids}",
"{id, subpath?, segment, t: 0–1 (0.5)} or {id, subpath?, anchor}: closed paths open there, open paths become two; one of the two new end points is left selected; the paths keep the source's fill and stroke settings except that every stroke's alignment becomes Center (in a path of several subpaths, the other subpaths' strokes too) → {ids}. A t outside 0–1 is refused with an error, and nothing changes",
has_doc,
split
),
@@ -92,7 +92,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Eraser",
[],
None,
"{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1, tilt −90..90°, barrel rotation 0..360° clockwise; pen values are checked as path.freehand checks them), size?: pt (10; from 0.1 to 1000), angle?: ° (0: the tip's long axis counter-clockwise from level), roundness?: % (100, kept within 1–100), angleMode?, roundnessMode?, sizeMode?: \"fixed\" (default) | \"random\" | \"pressure\" | \"tilt\" | \"bearing\" | \"rotation\" (Eraser Tool Options' variation menus; a varied angle turns either way, clockwise or counter-clockwise), angleVariation?: ° (0–180, default 0, either way: clockwise or counter-clockwise), roundnessVariation?: % (0–100, default 0), sizeVariation?: pt (0–1000, default 0)} or {rect: [x, y, width, height] (pt; the Eraser's Alt-drag marquee)} erase the stroke of an elliptical tip from paths (selected, or all) → {ids}. The tip is `size` across its long axis, which runs at `angle` counter-clockwise from horizontal; its short axis is `roundness` percent of the long one. A value whose mode is not fixed varies by up to its variation either way: random draws one value for the drag; pressure goes from the value less the variation where the pen presses lightest to the value plus it where it presses hardest (size on pressure as path.blob); tilt from less with the pen lying flat to more with it upright; bearing and rotation from less at −180° to more at 180° of the pen's lean direction or barrel turn. A drag without that pen reading (a mouse) erases at the value itself. An unknown mode, or a variation below 0 or past its range, is an error and erases nothing. `rect` in place of `points` erases everything inside the rectangle: closed paths lose its area, and open paths are cut where they cross its edges; the tip's size, angle, roundness and variations do not apply. A width or height of 0 or less, a value that is not a finite number, or `points` and `rect` together is an error. When nothing is erased, no undo step is added",
"{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1, tilt −90..90°, barrel rotation 0..360° clockwise; pen values are checked as path.freehand checks them), size?: pt (10; from 0.1 to 1000), angle?: ° (0, −180–180: the tip's long axis counter-clockwise from level), roundness?: % (100, 1–100), angleMode?, roundnessMode?, sizeMode?: \"fixed\" (default) | \"random\" | \"pressure\" | \"tilt\" | \"bearing\" | \"rotation\" (Eraser Tool Options' variation menus; a varied angle turns either way, clockwise or counter-clockwise), angleVariation?: ° (0–180, default 0, either way: clockwise or counter-clockwise), roundnessVariation?: % (0–100, default 0), sizeVariation?: pt (0–1000, default 0)} or {rect: [x, y, width, height] (pt; the Eraser's Alt-drag marquee)} erase the stroke of an elliptical tip from paths (selected, or all) → {ids}. The tip is `size` across its long axis, which runs at `angle` counter-clockwise from horizontal; its short axis is `roundness` percent of the long one. A value whose mode is not fixed varies by up to its variation either way: random draws one value for the drag; pressure goes from the value less the variation where the pen presses lightest to the value plus it where it presses hardest (size on pressure as path.blob); tilt from less with the pen lying flat to more with it upright; bearing and rotation from less at −180° to more at 180° of the pen's lean direction or barrel turn. A drag without that pen reading (a mouse) erases at the value itself. An angle or roundness outside its range, an unknown mode, or a variation below 0 or past its range is refused with an error and erases nothing. `rect` in place of `points` erases everything inside the rectangle: closed paths lose its area, and open paths are cut where they cross its edges; the tip's size, angle, roundness and variations do not apply. A width or height of 0 or less, a value that is not a finite number, or `points` and `rect` together is an error. When nothing is erased, no undo step is added",
has_doc,
erase_region
),
+20
View File
@@ -406,6 +406,26 @@ pub(super) fn sibling_with(d: &mut Document, id: NodeId, pd: PathData) -> Result
Ok(n)
}
/// Set every stroke of node `id`, and every stroke of the compound path it is a member of (whose
/// strokes its members show), to Center alignment. Every other stroke and fill setting stays as it
/// is, and an appearance whose strokes are all centered stays shared with its other copies.
pub(in super::super) fn center_strokes(d: &mut Document, id: NodeId) {
use vectorcraft_doc::{AppearanceItem, StrokeAlign};
let parent = d.parent_of(id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. })));
for n in [Some(id), parent].into_iter().flatten() {
let Some(n) = d.node_mut(n) else { continue };
let off = |it: &AppearanceItem| matches!(it, AppearanceItem::Stroke(st) if st.align != StrokeAlign::Center);
if !n.appearance.items.iter().any(off) {
continue;
}
for it in &mut n.appearance.items {
if let AppearanceItem::Stroke(st) = it {
st.align = StrokeAlign::Center;
}
}
}
}
/// Replace path or compound path `id` with `pieces` (first keeps the id, the rest go right above
/// it; none removes it). `cut` removes the path or puts the other pieces above it. Returns ids.
pub(in super::super) fn replace_with_pieces(d: &mut Document, cut: &mut Beside, id: NodeId, pieces: Vec<PathData>) -> Result<Vec<NodeId>> {
+16 -3
View File
@@ -1,6 +1,6 @@
use super::common::{
PenRecord, SIZE_VARIATIONS, SIZES, Sample, dist_to_polyline, fill_targets, ids_json, path_mut, path_of, points_param, poly_bounds,
pressure_region, ranged, replace_with_pieces, samples_param, sibling_with, size_pressure, target_paths, usize_opt,
PenRecord, SIZE_VARIATIONS, SIZES, Sample, center_strokes, dist_to_polyline, fill_targets, ids_json, path_mut, path_of, points_param,
poly_bounds, pressure_region, ranged, replace_with_pieces, samples_param, sibling_with, size_pressure, target_paths, usize_opt,
};
use super::{
Anchor, AnchorKind, Beside, BezPath, BoolOp, Cap, EngineError, FillRule, Join, NodeId, Paint, ParamCurve, PathData, Point, Rect, Result, Session,
@@ -196,6 +196,9 @@ pub(super) fn split(s: &mut Session, p: &Value) -> Result<Value> {
if !t.is_finite() || p.get("t").is_some_and(|v| !v.is_f64() && !v.is_i64() && !v.is_u64()) {
return Err(bad(C, "invalid t"));
}
if !(0.0..=1.0).contains(&t) {
return Err(bad(C, "`t` must be from 0 to 1"));
}
let ids = s.edit("Split Path", |d, sel| {
let path = path_mut(d, id)?;
let mut sp = path.subpaths.get(si).cloned().ok_or_else(|| EngineError::Other("no such subpath".into()))?;
@@ -222,14 +225,17 @@ pub(super) fn split(s: &mut Session, p: &Value) -> Result<Value> {
sel.add(id);
sel.anchors.entry(id).or_default().insert((si, 0));
};
// The paths a cut makes keep the source's appearance with every stroke centered.
if sp.closed {
path.subpaths[si] = pieces.pop().ok_or_else(|| EngineError::Other("no such anchor".into()))?;
center_strokes(d, id);
pick(sel, id, si);
return Ok(vec![id]);
}
let [left, right] = <[SubPath; 2]>::try_from(pieces).map_err(|_| EngineError::Other("cannot split an open path at its end point".into()))?;
if path.subpaths.len() == 1 {
path.subpaths[0] = left;
center_strokes(d, id);
let node = sibling_with(d, id, PathData::single(right))?;
let (parent, idx, _) = d.position(id).ok_or(EngineError::NoNode(id))?;
let nid = d.insert(parent, idx + 1, node)?;
@@ -238,6 +244,7 @@ pub(super) fn split(s: &mut Session, p: &Value) -> Result<Value> {
} else {
path.subpaths[si] = left;
path.subpaths.insert(si + 1, right);
center_strokes(d, id);
pick(sel, id, si + 1);
Ok(vec![id])
}
@@ -295,7 +302,13 @@ pub(super) fn erase_region(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 !(1.0..=100.0).contains(&roundness) {
return Err(bad(C, "`roundness` must be from 1 to 100%"));
}
let vary = eraser_variations(p, C)?;
if varies_beyond_size_pressure(&vary) {
return erase_varied(s, &samples, [angle, roundness, size], vary);
@@ -305,7 +318,7 @@ pub(super) fn erase_region(s: &mut Session, p: &Value) -> Result<Value> {
let r = size / 2.0;
// The tip's short axis (its narrowest with Pressure): an open path is sampled at least every half of it.
let narrowest = pressure.as_ref().map_or(size, |(_, v)| vectorcraft_tools::draw2::pressure_size(size, *v, 0.0));
let short = narrowest * roundness.clamp(1.0, 100.0) / 100.0;
let short = narrowest * roundness / 100.0;
let st = s.doc()?;
// A point is under the tip when, with the tip squashed back into a circle, it is within the
// circle's radius of the squashed drag.
+22 -14
View File
@@ -526,26 +526,34 @@ fn doc_compare(s: &mut Session, p: &Value) -> Result<Value> {
/// RGBA: a PNG, JPEG, WebP, TIFF or BMP within the allocation an opened image may take.
#[cfg(not(target_arch = "wasm32"))]
fn compare_image(path: &str) -> Result<image::RgbaImage> {
use image::ImageDecoder as _;
const C: &str = "document.compare";
let bytes = super::fileio::read_file(path)?;
if let Some((w, h)) = vectorcraft_doc::cmyk::oversized_tiff(&bytes) {
return Err(bad(C, format!("an image of {w} × {h} pixels is too large to draw")));
}
let mut reader = image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format().map_err(|e| bad(C, format!("{path}: {e}")))?;
let readable = [image::ImageFormat::Png, image::ImageFormat::Jpeg, image::ImageFormat::WebP, image::ImageFormat::Tiff, image::ImageFormat::Bmp];
if !reader.format().is_some_and(|f| readable.contains(&f)) {
let format = craft_image_codecs::detect(&bytes);
let readable = [
craft_image_codecs::Format::Png,
craft_image_codecs::Format::Jpeg,
craft_image_codecs::Format::WebP,
craft_image_codecs::Format::Tiff,
craft_image_codecs::Format::Bmp,
];
let Some(format) = format.filter(|f| readable.contains(f)) else {
return Err(bad(C, format!("{path}: not a PNG, JPEG, WebP, TIFF or BMP image")));
}
let mut limits = image::Limits::default();
limits.max_alloc = Some(vectorcraft_doc::MAX_RASTER_ALLOC);
reader.limits(limits);
let decoder = reader.into_decoder().map_err(|e| bad(C, format!("{path}: {e}")))?;
let (w, h) = decoder.dimensions();
if decoder.total_bytes() > vectorcraft_doc::MAX_RASTER_ALLOC || u64::from(w) * u64::from(h) * 4 > vectorcraft_doc::MAX_RASTER_ALLOC {
return Err(bad(C, format!("an image of {w} × {h} pixels is too large to draw")));
}
Ok(image::DynamicImage::from_decoder(decoder).map_err(|e| bad(C, format!("{path}: {e}")))?.to_rgba8())
};
let mut opts = craft_image_codecs::DecodeOptions::default();
opts.limits.max_alloc = vectorcraft_doc::MAX_RASTER_ALLOC;
opts.limits.max_pixels = vectorcraft_doc::MAX_RASTER_ALLOC / 4;
let img = match craft_image_codecs::decode_as_with(format, &bytes, &opts) {
Ok(img) => img,
Err(craft_image_codecs::CodecError::LimitExceeded(_)) => {
return Err(bad(C, "image is too large to draw"));
}
Err(e) => return Err(bad(C, format!("{path}: {e}"))),
};
let (w, h) = img.dimensions();
image::RgbaImage::from_raw(w, h, img.to_rgba8()).ok_or_else(|| bad(C, format!("{path}: invalid pixel buffer")))
}
#[cfg(target_arch = "wasm32")]
+200 -46
View File
@@ -97,7 +97,7 @@ fn effect_specs() -> Vec<CommandSpec> {
"Expand Appearance",
["Object"],
None,
"{ids?|id?: [..], target?} turn each object's appearance into objects: every fill and stroke becomes an object of its own (a stroke stays a stroke, with its weight, dashes, arrowheads and width profile, on its own copy of the path, which object.expand or object.path.outlineStroke outline; brushed strokes become their brush art) grouped in paint order under the object's id and transparency, geometry effects are baked, raster effects become an embedded image (shadows and outer glows below the art; blur, feather and inner glow replace it; an object whose only raster effect is its own Rasterize becomes the image object.rasterize makes with the effect's options), type with effects or fills of its own is outlined; Crop Marks become a group of the object and its marks; Vector Halftone (addon.color.halftone) becomes a group of its dot paths, one per ink; a group's or layer's own fills and strokes become objects among its members, which are expanded too; a symbol instance whose topmost fill or stroke is visible, has an opacity above 0 and has a geometry effect becomes a group of its art, that fill's effects reshaping the art's filled shapes and that stroke's effects reshaping its stroked shapes, as the canvas draws them. An outlined frame of threaded text leaves its thread with the text it shows, and a frame kept as type in a group stays in its thread. A dimension whose art it changes becomes a plain group of its art, except one selected with art it measures, directly or in groups without fills, strokes or effects of their own: its lines and label stay as they are, and if the new art no longer fits its link it stays where it was, no longer linked. Hidden fills, strokes and effects are dropped. In Safe Mode, an object with a visible plug-in effect (in it, or in a symbol it places) is an error and nothing changes. Enabled when a selected or targeted object's appearance isn't basic (`ids` then pick which objects) → {ids, warning? (an image in the art couldn't be decoded, as object.rasterize says)}",
"{ids?|id?: [..], target?} turn each object's appearance into objects: every fill and stroke becomes an object of its own (a stroke stays a stroke, with its weight, dashes, arrowheads and width profile, on its own copy of the path, which object.expand or object.path.outlineStroke outline; brushed strokes become their brush art) grouped in paint order under the object's id and transparency, geometry effects are baked, raster effects become an embedded image (shadows and outer glows below the art; blur, feather and inner glow replace it; an object whose only raster effect is its own Rasterize becomes the image object.rasterize makes with the effect's options), type with effects or fills of its own is outlined; Crop Marks become a group of the object and its marks; Vector Halftone (addon.color.halftone) becomes a group of its dot paths, one per ink; a group's or layer's own fills and strokes become objects among its members, which are expanded too; a symbol instance whose topmost fill or stroke is visible, has an opacity above 0 and has a geometry or raster effect becomes a group of its art, that fill's effects reshaping the art's filled shapes and that stroke's effects reshaping its stroked shapes, as the canvas draws them, its raster effects an image as for other objects; a symbol instance in that art whose topmost fill or stroke has such an effect (its own or one the outer instance passes on) becomes its art and image in turn. An outlined frame of threaded text leaves its thread with the text it shows, and a frame kept as type in a group stays in its thread. A dimension whose art it changes becomes a plain group of its art, except one selected with art it measures, directly or in groups without fills, strokes or effects of their own: its lines and label stay as they are, and if the new art no longer fits its link it stays where it was, no longer linked. Hidden fills, strokes and effects are dropped. One expansion makes at most 1,024 images of raster effects, 256 megapixels in all (VectorCraft's own limits): an object or symbol instance whose image would go past them stays as it is, with its effects, and when nothing else expands that is an error. In Safe Mode, an object with a visible plug-in effect (in it, or in a symbol it places) is an error and nothing changes. Enabled when a selected or targeted object's appearance isn't basic (`ids` then pick which objects) → {ids, warning? (an image in the art couldn't be decoded, as object.rasterize says; or raster effects were left past the limits), rasterLeft? (how many objects were left so)}",
can_expand,
expand_appearance
),
@@ -963,16 +963,74 @@ fn is_container(n: &Node) -> bool {
/// The raster effects of `n` (its own, its fills' and strokes') as an embedded image rendered at
/// the document's raster effects resolution or a Rasterize effect's finer one, with whether they
/// all paint below it (shadows and outer glows: the image then holds just them). A group's or
/// layer's image leaves out its members' raster effects, which are expanded with them. `None`
/// when it has none.
fn raster_image(d: &mut Document, n: &Node) -> Option<(Node, bool)> {
/// all paint below it (shadows and outer glows: the image then holds just them, and paints with
/// their blend mode when they all use one). A group's or layer's image leaves out its members'
/// raster effects, which are expanded with them. `None` when it has none.
/// `Err` when that image would take `budget` past its limits: the object then stays as it is.
fn raster_image(d: &mut Document, n: &Node, budget: &mut RasterBudget) -> std::result::Result<Option<(Node, bool)>, OverBudget> {
let fx = rasterfx::raster_fx(n);
if fx.is_empty() {
return None;
return Ok(None);
}
let below = fx.iter().all(effects::RasterFx::is_below);
Some((rasterfx::raster_image(d, n, below, true)?, below))
let pixels = budget.take(rasterfx::raster_pixels(d, n, below, true))?;
let mut image = rasterfx::raster_image(d, n, below, true);
if image.is_none() {
// No image was made: it takes nothing from the budget.
budget.images += 1;
budget.pixels += pixels;
}
// Rendered alone, over nothing, the shadows and glows can't blend with the art below the
// object, so the image does, as the canvas draws them.
let mut modes = fx.iter().filter_map(effects::RasterFx::mode);
if below
&& let (Some(mode), Some(image)) = (modes.next(), image.as_mut())
&& modes.all(|m| m == mode)
{
image.blend = mode;
}
Ok(image.map(|image| (image, below)))
}
/// The most images of raster effects one Expand Appearance makes.
const MAX_RASTER_IMAGES: u32 = 1_024;
/// The most pixels the images of raster effects one Expand Appearance makes hold in all.
const MAX_RASTER_PIXELS: u64 = 256_000_000;
/// The note when objects keep their raster effects because their images would take an Expand
/// Appearance past [`MAX_RASTER_IMAGES`] or [`MAX_RASTER_PIXELS`].
pub(crate) const RASTER_EFFECTS_LEFT: &str =
"some raster effects were not made into images: they would take more than 1,024 images or 256 megapixels in all";
/// An image of raster effects that would take a [`RasterBudget`] past its limits.
#[derive(Debug)]
struct OverBudget;
/// What one Expand Appearance has left of [`MAX_RASTER_IMAGES`] and [`MAX_RASTER_PIXELS`], and the
/// objects whose raster effects it left as they are because their images would go past them.
pub(crate) struct RasterBudget {
images: u32,
pixels: u64,
pub(crate) left: usize,
}
impl RasterBudget {
pub(crate) fn new() -> Self {
Self { images: MAX_RASTER_IMAGES, pixels: MAX_RASTER_PIXELS, left: 0 }
}
/// Take an image of `pixels` ([`rasterfx::raster_pixels`]) before it is made, and return
/// them; `Err`, with its object counted in `left`, when it would go past what is left.
fn take(&mut self, pixels: u64) -> std::result::Result<u64, OverBudget> {
if self.images == 0 || pixels > self.pixels {
self.left += 1;
return Err(OverBudget);
}
self.images -= 1;
self.pixels -= pixels;
Ok(pixels)
}
}
/// Expand the pieces of `m`, art evaluated from the object of the same id (its pieces share that
@@ -983,6 +1041,7 @@ fn raster_image(d: &mut Document, n: &Node) -> Option<(Node, bool)> {
/// 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.
#[allow(clippy::too_many_arguments)]
fn expand_pieces(
d: &mut Document,
m: &mut Node,
@@ -991,6 +1050,7 @@ fn expand_pieces(
skip: &[NodeId],
kept: &mut Vec<NodeId>,
stroke_art: effects::StrokeArt,
raster: &mut RasterBudget,
) -> std::collections::HashMap<NodeId, Vec<Listed>> {
let id = m.id;
let mut seen = std::collections::HashSet::from([id]);
@@ -1005,7 +1065,7 @@ 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));
listed = Some(expand_in_place(d, c, brushes, skip, raster));
}
let mut was = vec![];
if !skip.is_empty() {
@@ -1029,38 +1089,87 @@ fn expand_pieces(
expanded
}
/// `m`, the art a 3D effect expanded into, with each object in it that has effects of its own (a
/// shadow blurred by the light's Softness) expanded as Expand Appearance expands it on its own:
/// a blurred shadow becomes an image. Groups in `m` without effects that hold such an object are
/// looked into; the rest are left as they are. The objects `skip` lists are not expanded.
fn expand_raster_pieces(d: &mut Document, mut m: Node, brushes: &[vectorcraft_brush::Brush], skip: &[NodeId], raster: &mut RasterBudget) -> Node {
for c in m.children_mut().into_iter().flatten() {
if !c.appearance.effects.is_empty() {
if let Some(e) = expanded_node(d, (**c).clone(), brushes, skip, &mut vec![], raster) {
*c = Arc::new(e);
}
} else if c.children().is_some() {
let mut holds = false;
c.walk(&mut |n| holds |= !n.appearance.effects.is_empty());
if holds {
*c = Arc::new(expand_raster_pieces(d, (**c).clone(), brushes, skip, raster));
}
}
}
m
}
/// Replace each symbol instance in `m`, art an instance placed (`depth` instances deep), whose
/// active fill or stroke has a geometry effect ([`effects::has_item_geometry`]) by its art as
/// [`effects::expand_outlined`] makes it, and the instances in that art in turn, so
/// [`expand_pieces`] bakes their effects with the rest. An instance stays as it is when it is more
/// than [`vectorcraft_doc::depth::MAX_DEPTH`] instances deep, its symbol is missing, or its art
/// would take the objects placed so far past `budget`.
fn expand_nested_instances(d: &Document, m: &mut Node, depth: usize, budget: &mut u64) {
/// active fill or stroke has a geometry or raster effect ([`effects::has_item_geometry`],
/// [`effects::has_instance_row_raster`]) by its art ([`expanded_instance`]), and the instances in
/// that art in turn, so [`expand_pieces`] bakes their effects with the rest.
fn expand_nested_instances(d: &mut Document, m: &mut Node, depth: usize, budget: &mut u64, raster: &mut RasterBudget) {
for c in m.children_mut().into_iter().flatten() {
if !matches!(c.kind, NodeKind::SymbolInstance { .. }) {
if c.children().is_some() {
expand_nested_instances(d, Arc::make_mut(c), depth, budget);
expand_nested_instances(d, Arc::make_mut(c), depth, budget, raster);
}
continue;
}
let NodeKind::SymbolInstance { symbol, .. } = &c.kind else { continue };
if depth >= vectorcraft_doc::depth::MAX_DEPTH || !effects::has_item_geometry(c) {
continue;
}
let Some(sym) = d.symbols.iter().find(|s| s.name == *symbol) else { continue };
let count = sym.art.count() as u64;
if count > *budget {
continue;
}
*budget -= count;
let art = vectorcraft_render::instance_art(&sym.art, c);
if let Some(mut a) = effects::expand_outlined(Some(d), c, Some(&art)) {
expand_nested_instances(d, &mut a, depth + 1, budget);
if let Some(a) = expanded_instance(d, c, depth, budget, raster) {
*c = Arc::new(a);
}
}
}
/// Symbol instance `c`, art an instance placed (`depth` instances deep), as art: the raster
/// effects of its active fill or stroke an embedded image ([`raster_image`]) that replaces the art
/// (blur, feather, inner glow) or goes below it (shadows, outer glows), and its art as
/// [`effects::expand_outlined`] makes it without them, or as [`effects::instance_as_art`] does when
/// it has no geometry effect, with the instances in that art expanded in turn. `None`, the instance
/// staying as it is, when its active fill and stroke have no such effect, it is more than
/// [`vectorcraft_doc::depth::MAX_DEPTH`] instances deep, its symbol is missing, or its art would
/// take the objects placed so far past `budget`, or the image of its raster effects would take
/// `raster` past its limits. When that image can't be made, they stay on the art its geometry
/// effects make, and without one it stays as it is.
fn expanded_instance(d: &mut Document, c: &Node, depth: usize, budget: &mut u64, raster: &mut RasterBudget) -> Option<Node> {
let NodeKind::SymbolInstance { symbol, .. } = &c.kind else { return None };
let has_raster = effects::has_instance_row_raster(c);
if depth >= vectorcraft_doc::depth::MAX_DEPTH || !(has_raster || effects::has_item_geometry(c)) {
return None;
}
let sym = d.symbols.iter().find(|s| s.name == *symbol)?;
let count = sym.art.count() as u64;
if count > *budget {
return None;
}
let art = vectorcraft_render::instance_art(&sym.art, c);
let image = if has_raster { raster_image(d, c, raster).ok()? } else { None };
*budget -= count;
let mut v = c.clone();
if image.is_some() {
rasterfx::strip_raster(&mut v, false);
}
let below = match image {
Some((image, false)) => return Some(rasterfx::replace_with_image(v, image)),
Some((image, true)) => Some(image),
None => None,
};
let mut a = effects::expand_outlined(Some(&*d), &v, Some(&art))
.or_else(|| if below.is_some() { effects::instance_as_art(Some(&*d), &v, Some(&art)) } else { None })?;
expand_nested_instances(d, &mut a, depth + 1, budget, raster);
if let Some(image) = below {
rasterfx::put_below(d, &mut a, image);
}
Some(a)
}
/// Does `n` hold an id of `seen`, or one id twice: does [`effects::fresh_ids`] give it new ids?
fn repeats_an_id(n: &Node, seen: &std::collections::HashSet<NodeId>) -> bool {
let mut ids = std::collections::HashSet::new();
@@ -1075,9 +1184,9 @@ fn repeats_an_id(n: &Node, seen: &std::collections::HashSet<NodeId>) -> bool {
type Listed = (NodeId, usize);
/// [`expanded_node`] of `c` in place. Returns what the expansion lists, by places in the walk of `c`.
fn expand_in_place(d: &mut Document, c: &mut Node, brushes: &[vectorcraft_brush::Brush], skip: &[NodeId]) -> Vec<Listed> {
fn expand_in_place(d: &mut Document, c: &mut Node, brushes: &[vectorcraft_brush::Brush], skip: &[NodeId], raster: &mut RasterBudget) -> Vec<Listed> {
let mut listed = vec![];
if let Some(e) = expanded_node(d, c.clone(), brushes, skip, &mut listed) {
if let Some(e) = expanded_node(d, c.clone(), brushes, skip, &mut listed, raster) {
*c = e;
}
listed
@@ -1099,18 +1208,26 @@ fn fresh_ids_listed(d: &mut Document, c: &mut Node, seen: &mut std::collections:
/// Expand Appearance of `id` (and, recursively, of a group's or layer's members): every fill and
/// stroke becomes an object of its own (a stroke a path stroked by it alone, brushes as their art),
/// geometry effects are baked, raster effects become an embedded image, and the object keeps its
/// transparency.
pub(crate) fn expand_node(d: &mut Document, id: NodeId, brushes: &[vectorcraft_brush::Brush], out: &mut Vec<NodeId>) {
expand_node_except(d, id, brushes, &[], out);
/// transparency. An object whose raster effects' image would take `raster` past its limits stays
/// as it is, with what is inside it.
pub(crate) fn expand_node(d: &mut Document, id: NodeId, brushes: &[vectorcraft_brush::Brush], out: &mut Vec<NodeId>, raster: &mut RasterBudget) {
expand_node_except(d, id, brushes, &[], out, raster);
}
/// [`expand_node`], leaving the objects `skip` lists, and what they hold, as they are. A geometry
/// effect of a group or layer around one still reshapes it with the rest of its members, and the
/// copies of it that such an effect makes are left as they are too.
fn expand_node_except(d: &mut Document, id: NodeId, brushes: &[vectorcraft_brush::Brush], skip: &[NodeId], out: &mut Vec<NodeId>) {
fn expand_node_except(
d: &mut Document,
id: NodeId,
brushes: &[vectorcraft_brush::Brush],
skip: &[NodeId],
out: &mut Vec<NodeId>,
raster: &mut RasterBudget,
) {
let Some(n) = d.node(id).cloned() else { return };
let mut listed = vec![];
let m = expanded_node(d, n, brushes, skip, &mut listed);
let m = expanded_node(d, n, brushes, skip, &mut listed, raster);
out.extend(listed.into_iter().map(|(id, _)| id));
if let Some(mut m) = m {
// Art made from type takes its emoji's pixels into the document.
@@ -1124,11 +1241,20 @@ fn expand_node_except(d: &mut Document, id: NodeId, brushes: &[vectorcraft_brush
/// [`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.
fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Brush], skip: &[NodeId], out: &mut Vec<Listed>) -> Option<Node> {
fn expanded_node(
d: &mut Document,
mut n: Node,
brushes: &[vectorcraft_brush::Brush],
skip: &[NodeId],
out: &mut Vec<Listed>,
raster: &mut RasterBudget,
) -> Option<Node> {
let id = n.id;
if skip.contains(&id) || !expandable(&n) {
return None;
}
// What `out` held before `n`: an object left by the raster budget lists nothing.
let listed_before = out.len();
// Colour adjustments: the colours inside become the adjusted ones (an embedded image a
// recoloured copy), then the rest of the appearance expands.
let mut changed = false;
@@ -1141,6 +1267,10 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br
}
_ => 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())
.then(|| d.images.keys().cloned().collect::<std::collections::HashSet<_>>());
if effects::has_adjustment(&n)
&& let Some(m) = effects::adjust_in_document(d, &n, symbol_art)
{
@@ -1163,7 +1293,7 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br
for (i, c) in m.children_mut().into_iter().flatten().enumerate() {
let c = Arc::make_mut(c);
if i == 0 {
expanded = expand_in_place(d, c, brushes, skip);
expanded = expand_in_place(d, c, brushes, skip, raster);
fresh_ids_listed(d, c, &mut seen, &mut expanded);
} else {
effects::fresh_ids(d, c, &mut seen);
@@ -1186,7 +1316,15 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br
}
return Some(m);
}
let image = raster_image(d, &n);
// 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));
}
return None;
};
let mut v = n.clone();
rasterfx::strip_raster(&mut v, false);
let mut stroke_art =
@@ -1206,7 +1344,7 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br
} 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);
members = expand_pieces(d, &mut m, false, brushes, skip, &mut kept, &mut stroke_art, raster);
m
})
} else if matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. })
@@ -1224,13 +1362,21 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br
}
_ => None,
};
effects::expand_outlined(Some(&*d), &v, symbol.as_ref()).map(|mut m| {
// A symbol instance whose active fill or stroke has only effects that paint below it
// (now in the image) becomes its art as well.
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);
expand_pieces(d, &mut m, true, brushes, skip, &mut kept, &mut stroke_art);
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
})
};
// A 3D effect's shadow blurred by the light's Softness keeps its blur in the art: it
// expands in turn, to an image.
let m = if effects::has_solid(&v) || effects::has_revolve(&v) { m.map(|m| expand_raster_pieces(d, m, brushes, skip, raster)) } else { m };
match image {
Some((image, _)) => {
let mut m = m.unwrap_or(v);
@@ -1262,7 +1408,7 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br
match members.remove(&c.id) {
Some(listed) => out.extend(listed),
None => {
if let Some(e) = expanded_node(d, (**c).clone(), brushes, &skip, out) {
if let Some(e) = expanded_node(d, (**c).clone(), brushes, &skip, out, raster) {
*c = Arc::new(e);
changed = true;
}
@@ -1336,6 +1482,7 @@ fn expand_appearance(s: &mut Session, p: &Value) -> Result<Value> {
}
let failed = vectorcraft_render::decode_failures();
let colorized_ok = super::paint::check_colorized(&s.doc()?.doc).is_ok();
let mut raster = RasterBudget::new();
let ids = s.edit("Expand Appearance", |d, _| {
let before = d.clone();
// The art of graph designs in the graphs and series among the roots stays as the graph draws it. A group whose
@@ -1351,7 +1498,7 @@ fn expand_appearance(s: &mut Session, p: &Value) -> Result<Value> {
let mut out = vec![];
let threaded = super::threads::frames(d);
for id in &roots {
expand_node_except(d, *id, &brushes, &designs, &mut out);
expand_node_except(d, *id, &brushes, &designs, &mut out, &mut raster);
}
super::dimension::put_back(d, lifted);
// A dimension whose source was replaced stays where it was, no longer linked.
@@ -1360,6 +1507,9 @@ fn expand_appearance(s: &mut Session, p: &Value) -> Result<Value> {
// stays type under a new id takes its frame's place.
super::threads::leave_threads(d, &threaded);
if out.is_empty() || (kept && d.layers == before.layers) {
if raster.left > 0 {
return Err(EngineError::Other(RASTER_EFFECTS_LEFT.into()));
}
return Err(EngineError::Other("Expand Appearance: the selection has a basic appearance".into()));
}
super::paint::check_colorized_kept(colorized_ok, d).map_err(|e| bad("Expand Appearance", e))?;
@@ -1367,8 +1517,12 @@ fn expand_appearance(s: &mut Session, p: &Value) -> Result<Value> {
})?;
let mut out = json!({ "ids": ids_json(&ids) });
// Raster effects become images rendered from the art.
if let Some(w) = rasterfx::undecoded_warning(failed) {
out["warning"] = json!(w);
let warnings: Vec<&str> = rasterfx::undecoded_warning(failed).into_iter().chain((raster.left > 0).then_some(RASTER_EFFECTS_LEFT)).collect();
if !warnings.is_empty() {
out["warning"] = json!(warnings.join("; "));
}
if raster.left > 0 {
out["rasterLeft"] = json!(raster.left);
}
Ok(out)
}
+68
View File
@@ -1017,6 +1017,49 @@ fn a_3d_shadow_is_one_undo_step_saved_exported_and_expanded() {
assert_eq!(shadows, 1);
}
/// With the light's Softness, the 3D shadow is blurred: the canvas paints past the hard shadow's
/// edge, the object's bounds take the blur in, SVG export blurs it as it does a Gaussian Blur
/// effect, and Expand Appearance keeps it as an image with no live effect left.
#[test]
fn a_soft_3d_shadow_is_drawn_measured_exported_and_expanded_blurred() {
let (mut s, id) = session_with_rect();
s.execute("effect.apply", &json!({"effect": effects::EXTRUDE, "ids": [id.0], "item": null})).unwrap();
let set = |s: &mut Session, params: serde_json::Value| {
s.execute("effect.setParams", &json!({"ids": [id.0], "index": 0, "item": null, "params": params})).unwrap();
};
let draw = |s: &Session| {
vectorcraft_render::Renderer::new().render(&s.doc().unwrap().doc, 400, 400, vectorcraft_geom::Affine::IDENTITY, &Default::default()).pixels
};
let bounds = |s: &Session| {
let doc = &s.doc().unwrap().doc;
vectorcraft_render::effect_bounds(&doc.symbol_boxes(), doc.node(id).unwrap()).unwrap()
};
let blurs = |s: &mut Session| {
let svg = s.execute("document.serialize", &json!({"format": "svg"})).unwrap();
let svg = svg["data"].as_str().or_else(|| svg["text"].as_str()).map(str::to_string).unwrap_or_else(|| svg.to_string());
svg.matches("<feGaussianBlur").count()
};
let none = draw(&s);
set(&mut s, json!({"shadow": true, "shadowDistance": 50}));
let (hard, hard_bounds, hard_blurs) = (draw(&s), bounds(&s), blurs(&mut s));
let undo = s.doc().unwrap().history.undo.len();
set(&mut s, json!({"lightSoftness": 100}));
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "one undo step");
let (soft, soft_bounds) = (draw(&s), bounds(&s));
// Pixels the hard shadow leaves as they are, the soft one paints.
let spread = none.chunks(4).zip(hard.chunks(4)).zip(soft.chunks(4)).filter(|((n, h), s)| n == h && n != s).count();
assert!(spread > 100, "{spread}");
assert!(soft_bounds.contains_rect(hard_bounds) && soft_bounds.area() > hard_bounds.area(), "{hard_bounds:?} {soft_bounds:?}");
assert_eq!(blurs(&mut s), hard_blurs + 1, "SVG export blurs the shadow as a Gaussian Blur effect");
s.execute("effect.expandAppearance", &json!({"ids": [id.0]})).unwrap();
let (mut live, mut pictures) = (0, 0);
s.doc().unwrap().doc.walk(|n| {
live += usize::from(!n.appearance.effects.is_empty() || n.appearance.items.iter().any(|i| !i.effects().is_empty()));
pictures += usize::from(matches!(n.kind, NodeKind::Image(_)));
});
assert_eq!((live, pictures), (0, 1), "the blurred shadow expands to an image");
}
/// Radial Blur's Blur Center: stored as given, drawn about that point of the object's bounds, and
/// a value outside 0 to 1 (or not a number) is refused with nothing changed and no undo step.
#[test]
@@ -1082,3 +1125,28 @@ fn radial_blur_center_stays_in_the_object_when_the_stack_splits() {
let differ = (0..300 * 300).filter(|i| plain[i * 4 + 3].abs_diff(split[i * 4 + 3]) > 8).count();
assert!(differ < 50, "{differ} pixels' coverage moved with the room around the art");
}
/// The raster budget charges each image its pixels before it is made: an image past what is left
/// is refused and counted, and the object keeps its blur.
#[test]
fn an_image_past_the_pixels_left_stays_unmade() {
let (mut s, id) = session_with_rect();
s.execute("effect.apply", &json!({"ids": [id.0], "effect": "blur.gaussian", "params": {"radius": 3}})).unwrap();
let mut d = s.doc().unwrap().doc.as_ref().clone();
let n = d.node(id).cloned().unwrap();
let pixels = super::rasterfx::raster_pixels(&d, &n, false, true);
assert!(pixels > 10_000, "a 100 pt square at 72 ppi: {pixels}");
let mut budget = super::RasterBudget { images: 10, pixels: pixels - 1, left: 0 };
assert!(super::raster_image(&mut d, &n, &mut budget).is_err());
assert_eq!((budget.images, budget.pixels, budget.left), (10, pixels - 1, 1), "nothing is taken");
let mut budget = super::RasterBudget { images: 10, pixels, left: 0 };
let (image, _) = super::raster_image(&mut d, &n, &mut budget).unwrap().expect("the image is made");
let NodeKind::Image(img) = &image.kind else { panic!("not an image") };
assert_eq!(u64::from(img.width) * u64::from(img.height), pixels, "the charge is the image's size");
assert_eq!((budget.images, budget.pixels, budget.left), (9, 0, 0));
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");
}
+1 -1
View File
@@ -129,9 +129,9 @@ mod commands;
mod export_names;
mod formats;
pub(crate) use access::check_images_in;
#[cfg(not(target_arch = "wasm32"))]
pub(crate) use access::list_dir;
pub(crate) use access::{check_images_in, check_scripts_of};
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")))]
+43 -11
View File
@@ -121,22 +121,54 @@ pub(crate) fn naming_in_message(msg: &str, path: &str, name: &str) -> String {
out
}
/// The error for an SVG of a document that links a JavaScript file outside the read roots.
/// The error for a file that would name a JavaScript file the document links outside the read roots.
pub(crate) const SCRIPT_OUTSIDE: &str = "a linked JavaScript file is outside the read roots";
/// `cmd` may write `st`'s document in format `format` (a format id): any format but SVG and SVGZ,
/// and those too unless read roots are in force and the document links a JavaScript file outside
/// them (`svg_scripts`, a relative path taken from the document's folder; a URL is not checked),
/// which the file's `<script>` element would name. The error names no file or folder.
pub fn check_linked_scripts(cmd: &str, format: &str, st: &crate::DocState) -> Result<()> {
if !matches!(format, "svg" | "svgz") || crate::file_access::current().is_none() {
/// `cmd` may write `st`'s document in format `format` (a format id) with options `p` (presets
/// written out): always, unless read roots are in force, the document links a JavaScript file
/// outside them (`svg_scripts`, a relative path taken from the document's folder; a URL is not
/// checked) and the file names it ([`names_linked_scripts`], with the artboards `p` picks counted
/// in `st`'s document): an SVG's `<script>` element, or the native document that a native file, a
/// `.ai` file, an EPS file or a PDF with Preserve Editing carries. The error names no file or folder.
pub fn check_linked_scripts(cmd: &str, format: &str, st: &crate::DocState, p: &Value) -> Result<()> {
check_scripts_of(cmd, &st.doc, st.path.as_deref(), || names_linked_scripts(cmd, format, p, st.doc.artboards.len()))
}
/// `doc`, saved at `doc_path`, may be written by `cmd` in a file that names its linked JavaScript
/// files when `names` says so: as [`check_linked_scripts`] allows it.
pub(crate) fn check_scripts_of(cmd: &str, doc: &vectorcraft_doc::Document, doc_path: Option<&str>, names: impl FnOnce() -> bool) -> Result<()> {
if crate::file_access::current().is_none() || !doc.svg_scripts.iter().any(|f| crate::cmd::links::script_hidden(f, doc_path)) || !names() {
return Ok(());
}
let doc_path = st.path.as_deref();
if st.doc.svg_scripts.iter().any(|f| crate::cmd::links::script_hidden(f, doc_path)) {
return Err(bad(cmd, SCRIPT_OUTSIDE));
Err(bad(cmd, SCRIPT_OUTSIDE))
}
/// Does a file of a document with `artboards` artboards, written in format `format` with options
/// `p`, name the JavaScript files the document links? SVG, SVGZ, native files, native templates and
/// EPS files always do. A `.ai` or `.ait` file does unless it is a legacy version 7 `.ai` file or `p`
/// picks only some of the artboards; a PDF does with Preserve Editing on (as its preset, standard and
/// options leave it) unless `p` picks only some of the artboards. Neither a `.ai` file nor a PDF
/// does when `useArtboards` is false in `p` (one page, the bounds of the art). Options the encoder
/// refuses count as naming them.
pub(crate) fn names_linked_scripts(cmd: &str, format: &str, p: &Value, artboards: usize) -> bool {
use serde::Deserialize;
let every_artboard = || {
let pick = if p.is_object() { super::ArtboardPick::deserialize(p).ok() } else { Some(super::ArtboardPick::default()) };
pick.and_then(|pick| pick.resolve(artboards).ok()).is_none_or(|v| v.is_none_or(|v| v.iter().copied().eq(0..artboards)))
};
let art_page = || super::encode::use_artboards(cmd, p).is_ok_and(|u| u == Some(false));
match format {
"svg" | "svgz" | "vectorcraft" | "template" | "eps" => true,
"ai" | "ait" => {
let legacy = super::format(format).is_some_and(|f| super::legacy_ai::wanted(cmd, f, p).unwrap_or(false));
!legacy && !(format == "ai" && art_page()) && every_artboard()
}
"pdf" => {
let editing = super::pdf::settings(cmd, p).ok().is_none_or(|s| s.preserve_editing);
editing && !art_page() && every_artboard()
}
_ => false,
}
Ok(())
}
/// The error for an SVG that would name a linked image's file outside the read roots.
-1
View File
@@ -4,7 +4,6 @@
//! native document can't be read opens as its embedded preview instead, with a warning that says
//! why, and can't be placed.
use std::io::Cursor;
use std::sync::Arc;
use kurbo::{Affine, BezPath, Point, Rect, Vec2};
@@ -1,4 +1,4 @@
use super::{Builder, Cursor, Document, Result, err, raster_doc};
use super::{Builder, Document, Result, err, raster_doc};
/// What an Affinity file opened as.
pub(in super::super) struct Imported {
@@ -30,13 +30,11 @@ fn preview(name: &str, bytes: &[u8], native: &vectorcraft_affinity::Error) -> Re
let p = vectorcraft_affinity::preview(bytes).map_err(|e| err(format!("{native}; its embedded preview can't be read either ({e})")))?;
// `raster_doc` normally probes PNG dimensions and keeps its encoded bytes. Verify this
// untrusted preview's complete pixels first, so corrupt data cannot create a blank image.
let mut reader = image::ImageReader::with_format(Cursor::new(p.png), image::ImageFormat::Png);
let mut limits = image::Limits::default();
limits.max_image_width = Some(4096);
limits.max_image_height = Some(4096);
limits.max_alloc = Some(128 << 20);
reader.limits(limits);
let _pixels = reader.decode().map_err(err)?;
let mut opts = craft_image_codecs::DecodeOptions::default();
opts.limits.max_width = 4096;
opts.limits.max_height = 4096;
opts.limits.max_alloc = 128 << 20;
let _pixels = craft_image_codecs::decode_as_with(craft_image_codecs::Format::Png, p.png, &opts).map_err(err)?;
let d = raster_doc(name, p.png)?;
Ok((
d,
@@ -1,5 +1,5 @@
use super::nodes::MAX_DEPTH;
use super::{AfAlign, CharStyle, Cursor, Justify, Kind, Rect, TextKind, TextObject, VerticalAlign, af, shapes};
use super::{AfAlign, CharStyle, Justify, Kind, Rect, TextKind, TextObject, VerticalAlign, af, shapes};
/// The master page instances among `nodes` (also inside layers and groups): (master, first page,
/// first master page, page count).
@@ -131,10 +131,9 @@ pub(super) fn fit_lines(obj: &mut TextObject, w: f64, h: f64) -> bool {
/// RGBA pixels as a PNG file.
pub(super) fn png(width: u32, height: u32, rgba: Vec<u8>) -> Option<Vec<u8>> {
let buf = image::RgbaImage::from_raw(width, height, rgba)?;
let mut png = Vec::new();
buf.write_to(&mut Cursor::new(&mut png), image::ImageFormat::Png).ok()?;
Some(png)
let raw =
craft_image_codecs::Image::from_raw(width, height, craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, rgba).ok()?;
craft_image_codecs::encode(&raw, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok()
}
/// Where a line of `w` starts in a span from 0 to `room` (as a share of `room - w`).
File diff suppressed because one or more lines are too long
+4 -3
View File
@@ -53,10 +53,10 @@ pub(super) fn export_reads(f: &Format, legacy: bool, key: &str) -> bool {
pub(super) fn serialize(s: &mut Session, p: &Value) -> Result<Value> {
let f = writable("document.serialize", Some(text_param(p, "format", "document.serialize")?.unwrap_or("vectorcraft")), None)?;
check_linked_scripts("document.serialize", f.id, s.doc()?)?;
let unused = unused_option_notes("document.serialize", f, p);
let expanded = expand_presets(s, "document.serialize", p)?;
let p = with_black_output(s, &expanded);
check_linked_scripts("document.serialize", f.id, s.doc()?, &p)?;
let (doc, display_doc_title) = source(s, f, &p, "document.serialize")?;
let doc = &*doc;
let mut q = p.clone();
@@ -97,10 +97,10 @@ pub(super) fn export(s: &mut Session, p: &Value) -> Result<Value> {
super::check_not_lossy_overwrite(s.doc()?, path, p, "document.export")?;
}
let f = writable("document.export", text_param(p, "format", "document.export")?, path)?;
check_linked_scripts("document.export", f.id, s.doc()?)?;
let unused = unused_option_notes("document.export", f, p);
let expanded = expand_presets(s, "document.export", p)?;
let p = with_black_output(s, &expanded);
check_linked_scripts("document.export", f.id, s.doc()?, &p)?;
let (doc, display_doc_title) = source(s, f, &p, "document.export")?;
let doc = &*doc;
let mut q = p.clone();
@@ -375,10 +375,11 @@ pub(super) fn export_selection(s: &mut Session, p: &Value) -> Result<Value> {
super::check_not_lossy_overwrite(s.doc()?, path, p, C)?;
}
let f = writable(C, text_param(p, "format", C)?, path)?;
check_linked_scripts(C, f.id, s.doc()?)?;
let unused = unused_option_notes(C, f, p);
let expanded = expand_presets(s, C, p)?;
let p = with_black_output(s, &expanded);
// The selection is written on one artboard of its own: every artboard, whatever `p` picks.
check_linked_scripts(C, f.id, s.doc()?, &without_artboards(&p))?;
let (d, bounds) = selection(s, C, f.id == "txt")?;
// The selected objects' links are looked for from the document they are in.
check_images_in(C, f.id, &d, crate::cmd::links::LinkBase::of(s.doc()?), &without_artboards(&p))?;
+1 -1
View File
@@ -308,7 +308,7 @@ const PSD_LAYERS: FormatOption = FormatOption {
name: "layers",
ty: "boolean",
default: "true",
description: "write layers: each top-level layer a pixel layer with its opacity and blend mode (a background colour is a Background layer); false: one flat image, on white where transparent",
description: "write layers: each top-level layer a pixel layer with its opacity and blend mode (a background colour is a Background layer); false: one flat image, on white where transparent. The user and object slices are written either way",
};
const MAX_EDITABILITY: FormatOption = FormatOption {
+44 -227
View File
@@ -1,7 +1,7 @@
//! JPEG 2000 JP2 and codestream images for File › Open and File › Place. The decoded image is
//! bounded before allocation and converted to RGBA for the common PNG storage path.
use hayro_jpeg2000::{ColorSpace, DecodeSettings, DecoderContext, Image};
use craft_image_codecs::{ChannelLayout, CodecError, Format, Limits};
use vectorcraft_color::cms::{IccProfile, Intent};
/// Recognize a JP2 signature box or the start of a raw codestream. The decoder checks the rest.
@@ -31,249 +31,66 @@ pub(super) fn boxes(b: &[u8]) -> impl Iterator<Item = (&[u8], &[u8])> {
})
}
/// The decoder ignores JPX layers and composition and silently uses the last top-level jp2c.
fn unsupported_jpx_content(bytes: &[u8]) -> bool {
fn association_has_content(data: &[u8], depth: usize) -> bool {
if depth >= 16 {
return true;
}
boxes(data).any(|(ty, child)| {
matches!(ty, b"jp2c" | b"jpch" | b"jplh" | b"comp" | b"ftbl") || (ty == b"asoc" && association_has_content(child, depth + 1))
})
}
let mut codestreams = 0u8;
for (ty, data) in boxes(bytes) {
match ty {
b"jp2c" => {
codestreams = codestreams.saturating_add(1);
if codestreams > 1 {
return true;
}
}
b"jpch" | b"jplh" | b"comp" | b"ftbl" => return true,
b"asoc" if association_has_content(data, 0) => return true,
_ => {}
}
}
false
}
/// The largest embedded ICC profile read.
const MAX_PROFILE: usize = 4 * 1024 * 1024;
/// A codestream numbers its tiles 0 to 65,534 (Isot in SOT, ITU-T T.800 A.4.2).
const MAX_TILES: u64 = 65_535;
/// Bytes the decoder keeps for each component of each tile before decoding any of them.
const TILE_COMPONENT_BYTES: u64 = 256;
/// SIZ follows SOC in the codestream; Lsiz includes its two length bytes. Returns the component
/// count, the image size and the tile count.
fn codestream_size(bytes: &[u8]) -> Option<(u64, u32, u32, u64)> {
let stream = if bytes.starts_with(b"\xff\x4f") { bytes } else { boxes(bytes).find_map(|(ty, data)| (ty == b"jp2c").then_some(data))? };
if stream.get(..4)? != b"\xff\x4f\xff\x51" {
return None;
}
let length = u16::from_be_bytes(stream.get(4..6)?.try_into().ok()?) as usize;
let count = u16::from_be_bytes(stream.get(40..42)?.try_into().ok()?) as usize;
if count == 0 || length != 38usize.checked_add(count.checked_mul(3)?)? || stream.get(4..4usize.checked_add(length)?)?.len() != length {
return None;
}
let be32 = |range: std::ops::Range<usize>| stream.get(range).and_then(|v| v.try_into().ok()).map(u32::from_be_bytes);
let width = be32(8..12)?.checked_sub(be32(16..20)?)?;
let height = be32(12..16)?.checked_sub(be32(20..24)?)?;
// Tiles across and down (T.800 B-5): the grid from the tile offset, in whole tiles.
let tiles = |grid: u32, offset: u32, tile: u32| match (grid.checked_sub(offset), tile) {
(Some(span), 1..) => Some(u64::from(span).div_ceil(u64::from(tile))),
_ => None,
};
let across = tiles(be32(8..12)?, be32(32..36)?, be32(24..28)?)?;
let down = tiles(be32(12..16)?, be32(36..40)?, be32(28..32)?)?;
Some((count as u64, width, height, across.checked_mul(down)?))
}
/// One `jp2h` header with at most one palette, component mapping and channel definition box, so
/// the checks below read the boxes the decoder uses.
fn single_header_boxes(bytes: &[u8]) -> bool {
let mut headers = boxes(bytes).filter(|(ty, _)| *ty == b"jp2h");
let (Some((_, header)), None) = (headers.next(), headers.next()) else {
return false;
};
[b"pclr", b"cmap", b"cdef"].iter().all(|kind| boxes(header).filter(|(ty, _)| ty == kind).count() <= 1)
}
/// The number of channel definitions in a JP2 `cdef` box, `None` without one. Only color channels
/// 1 to n, in any order, followed by at most one opacity channel for the whole image are read;
/// any other layout (premultiplied opacity, opacity before a color, an unassociated channel) gives
/// `Some(0)`, which no image matches.
fn channel_definitions(bytes: &[u8]) -> Option<u64> {
if bytes.starts_with(b"\xff\x4f") {
return None;
}
let header = boxes(bytes).find_map(|(ty, data)| (ty == b"jp2h").then_some(data))?;
let cdef = boxes(header).find_map(|(ty, data)| (ty == b"cdef").then_some(data))?;
let count = cdef.get(..2).and_then(|n| n.try_into().ok()).map_or(0, |n: [u8; 2]| usize::from(u16::from_be_bytes(n)));
let Some(entries) = cdef.get(2..).filter(|rest| count > 0 && rest.len() == count * 6) else {
return Some(0);
};
// (channel, type, association) by channel.
let mut defs: Vec<[u16; 3]> =
entries.as_chunks::<6>().0.iter().map(|&[a, b, c, d, e, f]| [[a, b], [c, d], [e, f]].map(u16::from_be_bytes)).collect();
defs.sort_unstable();
let opacity = defs.last().is_some_and(|&[_, kind, association]| kind == 1 && association == 0);
let colors = defs.len() - usize::from(opacity);
let mut seen = vec![false; colors];
let layout_ok = defs.iter().enumerate().all(|(i, &[channel, kind, association])| {
usize::from(channel) == i
&& (i >= colors
|| (kind == 0
&& usize::from(association).checked_sub(1).and_then(|slot| seen.get_mut(slot)).is_some_and(|s| !std::mem::replace(s, true))))
});
Some(if layout_ok { defs.len() as u64 } else { 0 })
}
/// The column count of a JP2 palette (`pclr`), `Ok(None)` without one. A component mapping (`cmap`)
/// beside it needs one entry per column, each naming a codestream component and, when it maps
/// through the palette, a palette column; anything else is `Err`.
fn palette_columns(bytes: &[u8], components: u64) -> Result<Option<u64>, ()> {
if bytes.starts_with(b"\xff\x4f") {
return Ok(None);
}
let Some(header) = boxes(bytes).find_map(|(ty, data)| (ty == b"jp2h").then_some(data)) else {
return Ok(None);
};
let Some(palette) = boxes(header).find_map(|(ty, data)| (ty == b"pclr").then_some(data)) else {
return Ok(None);
};
let columns = palette.get(2).copied().ok_or(())?;
// Each column's descriptor: unsigned, 1 to 31 bits, as codestream samples are.
let depths = palette.get(3..3 + usize::from(columns)).ok_or(())?;
if columns == 0 || depths.iter().any(|&d| d & 0x80 != 0 || (d & 0x7f) + 1 > 31) {
return Err(());
}
// Without a mapping the decoder maps every column from the first component.
let Some(mapping) = boxes(header).find_map(|(ty, data)| (ty == b"cmap").then_some(data)) else {
return Ok(Some(u64::from(columns)));
};
if mapping.len() != usize::from(columns) * 4 {
return Err(());
}
for &[c0, c1, kind, column] in mapping.as_chunks::<4>().0 {
let valid = u64::from(u16::from_be_bytes([c0, c1])) < components
&& match kind {
0 => true,
1 => column < columns,
_ => false,
};
if !valid {
return Err(());
}
}
Ok(Some(u64::from(columns)))
}
/// Decode within the raster allocation allowance, counting source samples, RGBA output, and
/// decoder intermediates. The decoder may need multiple full-sized component planes.
/// Decode `bytes` to RGBA, checking memory limits and converting embedded ICC/CMYK color spaces
/// to sRGB via `vectorcraft_color`.
pub(super) fn decode(bytes: &[u8], max_alloc: u64) -> Result<image::RgbaImage, String> {
if bytes.starts_with(b"\0\0\0\x0cjP \r\n\x87\n") && unsupported_jpx_content(bytes) {
return Err("the JPEG 2000 file has an unsupported color space or JPX content".into());
}
if bytes.starts_with(b"\0\0\0\x0cjP \r\n\x87\n") && !single_header_boxes(bytes) {
if !is_jpeg2000(bytes) {
return Err("the JPEG 2000 file can't be read".into());
}
let (codestream_channels, declared_w, declared_h, tile_count) = codestream_size(bytes).ok_or("the JPEG 2000 file can't be read")?;
if tile_count == 0 || tile_count > MAX_TILES {
return Err("the JPEG 2000 file can't be read".into());
}
let declared_pixels = u64::from(declared_w).checked_mul(u64::from(declared_h));
if declared_w == 0
|| declared_h == 0
|| declared_pixels.and_then(|n| n.checked_mul(codestream_channels)).and_then(|n| n.checked_mul(4)).is_none_or(|n| n > max_alloc)
|| tile_count.checked_mul(codestream_channels).and_then(|n| n.checked_mul(TILE_COMPONENT_BYTES)).is_none_or(|n| n > max_alloc)
{
return Err(format!("an image of {declared_w} × {declared_h} pixels is too large to draw"));
}
// The decoder copies an embedded profile (after a 3-byte `colr` header) when it reads the file.
let header = boxes(bytes).find_map(|(ty, data)| (ty == b"jp2h").then_some(data)).unwrap_or_default();
if boxes(header).any(|(ty, data)| ty == b"colr" && data.len() > MAX_PROFILE + 3) {
return Err("the JPEG 2000 file has an unsupported color space or JPX content".into());
}
let palette = palette_columns(bytes, codestream_channels).map_err(|()| "the JPEG 2000 file can't be read")?;
// The decoder keeps each palette value in 8 bytes and each row in its own list.
let palette_rows = boxes(header).find_map(|(ty, data)| (ty == b"pclr").then(|| data.get(..2)).flatten());
if let (Some(columns), Some(&[r0, r1])) = (palette, palette_rows)
&& u64::from(u16::from_be_bytes([r0, r1])) * (columns * 8 + 24) > max_alloc
{
return Err(format!("an image of {declared_w} × {declared_h} pixels is too large to draw"));
}
let image = Image::new(bytes, &DecodeSettings::default()).map_err(|_| "the JPEG 2000 file can't be read")?;
let limits = Limits { max_alloc, max_pixels: max_alloc / 4, ..Limits::default() };
let opts = craft_image_codecs::DecodeOptions { limits, ..craft_image_codecs::DecodeOptions::default() };
let image = craft_image_codecs::decode_as_with(Format::Jp2, bytes, &opts).map_err(|e| match e {
CodecError::LimitExceeded(_) => "an image is too large to draw".to_string(),
CodecError::Unsupported { .. } => "the JPEG 2000 file has an unsupported color space or JPX content".to_string(),
_ => "the JPEG 2000 file can't be read".to_string(),
})?;
let (w, h) = (image.width(), image.height());
let color = image.color_space();
let channels = match color {
ColorSpace::Gray => 1,
ColorSpace::RGB => 3,
ColorSpace::CMYK => 4,
ColorSpace::Icc { num_channels: 1 | 3 | 4, profile } if profile.len() <= MAX_PROFILE => color.num_channels(),
_ => return Err("the JPEG 2000 file has an unsupported color space or JPX content".into()),
};
let stride = u64::from(channels) + u64::from(image.has_alpha());
// The decoder sizes its output by the palette's columns and writes one channel per mapping
// entry, so the columns, the entries and the output channels must all match.
if palette.is_some_and(|columns| columns != stride) {
return Err("the JPEG 2000 file can't be read".into());
}
// The decoder reorders the channels by their definitions (`cdef`) and drops any channel without
// one, so a definition is needed for every channel it writes.
if channel_definitions(bytes).is_some_and(|count| count != stride || count != palette.unwrap_or(codestream_channels)) {
return Err("the JPEG 2000 file can't be read".into());
}
let plane_channels = codestream_channels.max(stride).max(palette.unwrap_or(0));
let too_large = || format!("an image of {w} × {h} pixels is too large to draw");
let pixels = u64::from(w).checked_mul(u64::from(h)).ok_or_else(too_large)?;
let size = pixels.checked_mul(stride).ok_or_else(too_large)?;
let rgba_size = pixels.checked_mul(4).ok_or_else(too_large)?;
// hayro 0.3.5 keeps a f32 plane per component, including alpha, and a second
// f32 coefficient plane per component. Palette mapping or channel definitions
// can temporarily clone the component planes. Reserve another 8 bytes per
// pixel for IDWT and code-block scratch while samples and RGBA coexist.
let plane_bytes = pixels.checked_mul(plane_channels).and_then(|n| n.checked_mul(4)).ok_or_else(too_large)?;
let scratch_bytes = plane_bytes.checked_mul(2).and_then(|n| n.checked_add(pixels.checked_mul(8)?)).ok_or_else(too_large)?;
let working =
size.checked_add(rgba_size).and_then(|n| n.checked_add(plane_bytes)).and_then(|n| n.checked_add(scratch_bytes)).ok_or_else(too_large)?;
if w == 0 || h == 0 || working > max_alloc {
if rgba_size > max_alloc {
return Err(too_large());
}
let len = usize::try_from(size).map_err(|_| too_large())?;
let mut samples = vec![0; len];
image.decode_into(&mut samples, &mut DecoderContext::default()).map_err(|_| "the JPEG 2000 file can't be read")?;
let profile = match color {
ColorSpace::Icc { profile, .. } => {
Some(IccProfile::from_bytes(None, profile).map_err(|_| "the JPEG 2000 file has an unsupported color space or JPX content")?)
}
_ => None,
let layout = image.layout();
let (channels, has_alpha) = match layout {
ChannelLayout::Gray => (1usize, false),
ChannelLayout::GrayA => (1, true),
ChannelLayout::Rgb => (3, false),
ChannelLayout::Rgba => (3, true),
ChannelLayout::Cmyk => (4, false),
ChannelLayout::CmykA => (4, true),
_ => return Err("the JPEG 2000 file has an unsupported color space or JPX content".into()),
};
let stride = channels + usize::from(has_alpha);
let profile = match image.icc.as_deref() {
Some(icc) => Some(IccProfile::from_bytes(None, icc).map_err(|_| "the JPEG 2000 file has an unsupported color space or JPX content")?),
None => None,
};
let cms = vectorcraft_color::cms::active();
let mut rgba = Vec::with_capacity(usize::try_from(rgba_size).map_err(|_| too_large())?);
for sample in samples.chunks_exact(stride as usize) {
for sample in image.data().chunks_exact(stride) {
let at = |i: usize| sample.get(i).copied().unwrap_or(0);
let rgb = match (color, profile.as_ref()) {
(ColorSpace::Gray, _) => [at(0); 3],
(ColorSpace::RGB, _) => [at(0), at(1), at(2)],
(ColorSpace::CMYK, _) => {
cms.cmyk_to_srgb([at(0), at(1), at(2), at(3)].map(|v| f32::from(v) / 255.0), false).map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8)
let rgb = if let Some(profile) = profile.as_ref() {
let mut values = [0.0f32; 4];
for (dst, src) in values.iter_mut().zip(sample.iter().take(channels)) {
*dst = f32::from(*src) / 255.0;
}
(ColorSpace::Icc { .. }, Some(profile)) => {
let mut values = [0.0f32; 4];
for (dst, src) in values.iter_mut().zip(sample.iter().take(usize::from(channels))) {
*dst = f32::from(*src) / 255.0;
}
profile
.to_srgb_into(&values[..usize::from(channels)], Intent::RelativeColorimetric)
.ok_or("the JPEG 2000 file has an unsupported color space or JPX content")?
.map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8)
profile
.to_srgb_into(&values[..channels], Intent::RelativeColorimetric)
.ok_or("the JPEG 2000 file has an unsupported color space or JPX content")?
.map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8)
} else {
match layout {
ChannelLayout::Gray | ChannelLayout::GrayA => [at(0); 3],
ChannelLayout::Rgb | ChannelLayout::Rgba => [at(0), at(1), at(2)],
ChannelLayout::Cmyk | ChannelLayout::CmykA => cms
.cmyk_to_srgb([at(0), at(1), at(2), at(3)].map(|v| f32::from(v) / 255.0), false)
.map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8),
_ => return Err("the JPEG 2000 file has an unsupported color space or JPX content".into()),
}
_ => return Err("the JPEG 2000 file has an unsupported color space or JPX content".into()),
};
let [r, g, b] = rgb;
rgba.extend_from_slice(&[r, g, b, if image.has_alpha() { at(usize::from(channels)) } else { 255 }]);
rgba.extend_from_slice(&[r, g, b, if has_alpha { at(channels) } else { 255 }]);
}
image::RgbaImage::from_raw(w, h, rgba).ok_or_else(|| "the JPEG 2000 file can't be read".into())
}
+9 -4
View File
@@ -142,7 +142,9 @@ pub(super) fn encode(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Result
let one = super::save::artboard_doc(doc, b);
let (full, placed) = crate::cmd::place::document::full_documents(&one);
let mut d = full.into_owned();
expand_appearances(&mut d);
if expand_appearances(&mut d) {
note(&mut enc.warnings, super::super::effectcmd::RASTER_EFFECTS_LEFT);
}
if mode == SeeThrough::Flatten {
expand_image_patterns(&mut d)?;
}
@@ -175,14 +177,17 @@ pub(super) fn encode(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Result
Ok(enc)
}
/// Expand Appearance of every layer's art whose appearance the format can't hold.
fn expand_appearances(d: &mut Document) {
/// Expand Appearance of every layer's art whose appearance the format can't hold. Returns whether
/// objects kept raster effects whose images would go past Expand Appearance's limits.
fn expand_appearances(d: &mut Document) -> bool {
let brushes = vectorcraft_brush::library(d);
let layers: Vec<NodeId> = d.layers.iter().map(|l| l.id).collect();
let mut out = vec![];
let mut raster = super::super::effectcmd::RasterBudget::new();
for id in layers {
super::super::effectcmd::expand_node(d, id, &brushes, &mut out);
super::super::effectcmd::expand_node(d, id, &brushes, &mut out, &mut raster);
}
raster.left > 0
}
/// Expand every layer's pattern fills that paint an image with see-through pixels, a colorize paint,
+36 -38
View File
@@ -1,7 +1,5 @@
//! `document.open`: every readable format into a new document.
use std::io::Cursor;
use serde_json::{Value, json};
use vectorcraft_doc::{Document, ImageBlob, ImageObject, Node, NodeKind};
use vectorcraft_geom::Affine;
@@ -133,7 +131,7 @@ pub fn detect(name: &str, bytes: &[u8]) -> Option<&'static Format> {
if super::heifread::is_heif(bytes) {
return format("heif");
}
if let Some(f) = image::guess_format(bytes).ok().and_then(image_format) {
if let Some(f) = craft_image_codecs::detect(bytes).and_then(image_format) {
return Some(f);
}
// A version 2 PICT is known by its version opcodes after the picture's frame, at byte 522 of a
@@ -159,9 +157,17 @@ pub fn detect(name: &str, bytes: &[u8]) -> Option<&'static Format> {
by_name
}
/// The readable raster format behind an `image` crate format.
fn image_format(f: image::ImageFormat) -> Option<&'static Format> {
f.extensions_str().iter().find_map(|e| format(e)).filter(|f| f.read && f.raster)
/// The readable raster format behind a craft-image-codecs format.
fn image_format(f: craft_image_codecs::Format) -> Option<&'static Format> {
f.extensions().iter().find_map(|e| format(e)).filter(|f| f.read && f.raster)
}
/// The image's size and the bytes a pixel of it takes decoded, from its header
/// ([`vectorcraft_doc::decode::decoded_layout`]), for bytes in a format craft-image-codecs tells.
fn header_layout(bytes: &[u8]) -> Option<(craft_image_codecs::Format, u32, u32, u64)> {
let format = craft_image_codecs::detect(bytes)?;
let (w, h, per_pixel) = vectorcraft_doc::decode::decoded_layout(bytes, format)?;
Some((format, w, h, per_pixel))
}
/// Why a file carrying editing data (an SVG or PDF saved with Preserve Editing) opened as plain
@@ -892,22 +898,18 @@ pub(crate) use vectorcraft_doc::MAX_RASTER_ALLOC;
/// says so; the pixels aren't read): Open, Place and the Links panel say it ([`size_note`], #1479).
/// `None` for images within the allowance, and for bytes that aren't an image.
pub(crate) fn too_large_note(bytes: &[u8]) -> Option<String> {
use image::ImageDecoder as _;
if let Some((w, h)) = vectorcraft_doc::cmyk::oversized_tiff(bytes) {
return Some(format!("an image of {w} × {h} pixels is too large to draw"));
}
let reader = image::ImageReader::new(Cursor::new(bytes)).with_guessed_format().ok()?;
let format = reader.format()?;
let d = reader.into_decoder().ok()?;
let (w, h) = d.dimensions();
let (format, w, h, per_pixel) = header_layout(bytes)?;
// The allowance also counts the pixels as RGBA: an image of fewer than 4 bytes a pixel (gray,
// gray with alpha, RGB) takes more than the decoder counts (#1717).
let rgba_over = u64::from(w) * u64::from(h) > MAX_RASTER_ALLOC / 4;
let samples_over = d.total_bytes() > MAX_RASTER_ALLOC;
let samples_over = (u64::from(w) * u64::from(h)).saturating_mul(per_pixel) > MAX_RASTER_ALLOC;
// The renderer can stream a non-interlaced PNG a row at a time when those buffers fit. Its
// full decoded byte count can exceed the allowance even though drawing it at native size is
// safe; use the renderer's decision for that case instead of warning from total_bytes alone.
let png_streams_at_size = samples_over && format == image::ImageFormat::Png && vectorcraft_render::reduced_size(bytes) == Some((w, h));
let png_streams_at_size = samples_over && format == craft_image_codecs::Format::Png && vectorcraft_render::reduced_size(bytes) == Some((w, h));
(rgba_over || (samples_over && !png_streams_at_size)).then(|| format!("an image of {w} × {h} pixels is too large to draw"))
}
@@ -918,7 +920,7 @@ pub(crate) fn too_large_note(bytes: &[u8]) -> Option<String> {
pub(crate) fn size_note(bytes: &[u8]) -> Option<String> {
let note = too_large_note(bytes)?;
let Some(drawn) = vectorcraft_render::reduced_size(bytes) else { return Some(note) };
let (w, h) = image::ImageReader::new(Cursor::new(bytes)).with_guessed_format().ok()?.into_dimensions().ok()?;
let (w, h) = vectorcraft_doc::header_size(bytes)?;
(drawn != (w, h)).then(|| format!("an image of {w} × {h} pixels is shown at reduced size"))
}
@@ -978,17 +980,14 @@ pub fn raster_image(bytes: &[u8]) -> Result<RasterImage> {
if super::pxrread::is_pxr(bytes) {
return as_png(super::pxrread::decode(bytes, MAX_RASTER_ALLOC).map_err(err)?, None, ppi);
}
let mut reader = image::ImageReader::new(Cursor::new(bytes)).with_guessed_format().map_err(err)?;
if reader.format().is_none() && super::tgaread::is_targa(bytes) {
reader.set_format(image::ImageFormat::Tga);
let mut detected = craft_image_codecs::detect(bytes);
if detected.is_none() && super::tgaread::is_targa(bytes) {
detected = Some(craft_image_codecs::Format::Tga);
}
if reader.format().is_none() && super::pcxread::is_pcx(bytes) {
if (detected.is_none() || detected == Some(craft_image_codecs::Format::Pcx)) && super::pcxread::is_pcx(bytes) {
return as_png(super::pcxread::decode(bytes, MAX_RASTER_ALLOC).map_err(err)?, None, ppi);
}
let mut limits = image::Limits::default();
limits.max_alloc = Some(MAX_RASTER_ALLOC);
reader.limits(limits);
let kind = reader.format().ok_or_else(|| err("not an image VectorCraft reads (see document.formats)"))?;
let kind = detected.ok_or_else(|| err("not an image VectorCraft reads (see document.formats)"))?;
let f = image_format(kind).ok_or_else(|| err(format!("{kind:?} images can't be opened (see document.formats)")))?;
// A photo whose EXIF orientation turns or flips it (a camera held upright) is stored as it is
// seen, so it places the way it was taken (#4284); the others keep their own bytes.
@@ -1009,8 +1008,8 @@ pub fn raster_image(bytes: &[u8]) -> Result<RasterImage> {
_ => None,
};
if let Some(kept) = kept {
let (width, height) = reader.into_dimensions().map_err(err)?;
return stored(kept, f.mime, (width, height), ppi);
let size = vectorcraft_doc::header_size(bytes).ok_or_else(|| err("the image's size can't be read"))?;
return stored(kept, f.mime, size, ppi);
}
let extra_samples = || {
let cms = vectorcraft_color::cms::active();
@@ -1023,21 +1022,23 @@ pub fn raster_image(bytes: &[u8]) -> Result<RasterImage> {
None => match (f.id == "tiff").then(|| vectorcraft_doc::cmyk::group3_tiff_rgba(bytes)).flatten() {
Some(read) => image::DynamicImage::ImageRgba8(read.map_err(err)?),
None => {
use image::ImageDecoder as _;
let mut decoder = reader.into_decoder().map_err(err)?;
// The allowance counts the decoded samples and the RGBA pixels they become (#1717).
let (w, h) = decoder.dimensions();
if decoder.total_bytes() > MAX_RASTER_ALLOC || u64::from(w) * u64::from(h) * 4 > MAX_RASTER_ALLOC {
// A Targa file's size is read from its header, which no signature points a probe at.
let tga = || (kind == craft_image_codecs::Format::Tga).then(|| super::tgaread::size(bytes)).flatten().map(|(w, h)| (w, h, 4));
let (w, h, per_pixel) =
vectorcraft_doc::decode::decoded_layout(bytes, kind).or_else(tga).ok_or_else(|| err("the image's size can't be read"))?;
let pixels = u64::from(w) * u64::from(h);
if pixels.saturating_mul(per_pixel) > MAX_RASTER_ALLOC || pixels * 4 > MAX_RASTER_ALLOC {
return Err(err(format!("an image of {w} × {h} pixels is too large to draw")));
}
// A profile the decoder can't read leaves the image without one. The image decoder
// reads a TIFF's tags within the size of its pixels, so a small TIFF's profile is
// read by the TIFF decoder itself.
let (img, profile) = vectorcraft_doc::decode::decode_image(kind, bytes, MAX_RASTER_ALLOC).map_err(err)?;
// A profile the decoder can't read leaves the image without one. A TIFF's profile is
// read by the TIFF reader, as before.
icc = match f.id {
"tiff" => vectorcraft_doc::cmyk::tiff_icc_profile(bytes),
_ => decoder.icc_profile().ok().flatten(),
_ => profile,
};
image::DynamicImage::from_decoder(decoder).map_err(err)?
img
}
},
};
@@ -1109,11 +1110,8 @@ pub fn texture_image(bytes: &[u8]) -> Result<String> {
LoadedTexture::from_rgba(inks.width, inks.height, &rgba)
}
None => {
let mut reader = image::ImageReader::new(Cursor::new(blob.bytes.as_slice())).with_guessed_format().map_err(err)?;
let mut limits = image::Limits::default();
limits.max_alloc = Some(MAX_RASTER_ALLOC);
reader.limits(limits);
let img = reader.decode().map_err(err)?.to_rgba8();
let kind = craft_image_codecs::detect(&blob.bytes).ok_or_else(|| err("the image can't be read as a texture"))?;
let img = vectorcraft_doc::decode::decode_image(kind, &blob.bytes, MAX_RASTER_ALLOC).map_err(err)?.0.to_rgba8();
LoadedTexture::from_rgba(img.width(), img.height(), img.as_raw())
}
};
File diff suppressed because one or more lines are too long
+17 -1
View File
@@ -39,7 +39,23 @@ mod tests {
let out = with_text(png.clone(), &[("Title", "Café".into()), ("Author", "Łukasz".into()), ("bad\u{1}", "x".into())]);
assert_eq!(text(&out), [("Title".to_string(), "Café".to_string()), ("Author".into(), "Łukasz".into())]);
// Still a PNG every decoder reads (the CRCs check out).
let img = image::load_from_memory(&out).unwrap();
let img = craft_image_codecs::decode(&out)
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap();
assert_eq!((img.width(), img.height()), (2, 1));
assert_eq!(with_text(b"not a png".to_vec(), &[("Title", "x".into())]), b"not a png");
assert_eq!(with_text(png.clone(), &[]), png);
+122 -4
View File
@@ -114,7 +114,41 @@ mod tests {
fn png_of(w: u32, h: u32) -> Vec<u8> {
let mut out = Vec::new();
image::RgbaImage::new(w, h).write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap();
{
let __dyn: image::DynamicImage = (image::RgbaImage::new(w, h)).into();
let (__w, __h) = (__dyn.width(), __dyn.height());
let (__layout, __sample, __raw) = match __dyn {
image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLuma16(b) => (
craft_image_codecs::ChannelLayout::Gray,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageLumaA16(b) => (
craft_image_codecs::ChannelLayout::GrayA,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgb16(b) => (
craft_image_codecs::ChannelLayout::Rgb,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgba16(b) => (
craft_image_codecs::ChannelLayout::Rgba,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()),
};
let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap();
craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default())
.map(|__b| out.extend_from_slice(&__b))
}
.unwrap();
out
}
@@ -131,14 +165,64 @@ mod tests {
let again = with_png_resolution(&tagged, (72.0, 72.0));
assert!(close(resolution(&again).unwrap(), (72.0, 72.0)), "replaced, not duplicated");
assert_eq!(again.len(), tagged.len());
let img = image::load_from_memory(&again).unwrap();
let img = craft_image_codecs::decode(&again)
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap();
assert_eq!((img.width(), img.height()), (4, 3));
}
#[test]
fn jpeg_jfif_density_in_dpi_and_dpcm() {
let mut jpg = Vec::new();
image::RgbImage::new(2, 2).write_to(&mut std::io::Cursor::new(&mut jpg), image::ImageFormat::Jpeg).unwrap();
{
let __dyn: image::DynamicImage = (image::RgbImage::new(2, 2)).into();
let (__w, __h) = (__dyn.width(), __dyn.height());
let (__layout, __sample, __raw) = match __dyn {
image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLuma16(b) => (
craft_image_codecs::ChannelLayout::Gray,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageLumaA16(b) => (
craft_image_codecs::ChannelLayout::GrayA,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgb16(b) => (
craft_image_codecs::ChannelLayout::Rgb,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgba16(b) => (
craft_image_codecs::ChannelLayout::Rgba,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()),
};
let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap();
craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Jpeg, &craft_image_codecs::EncodeOptions::default())
.map(|__b| jpg.extend_from_slice(&__b))
}
.unwrap();
// The encoder writes JFIF with units 0 (aspect only).
assert_eq!(resolution(&jpg), None);
let jfif = jpg.windows(5).position(|w| w == b"JFIF\0").unwrap();
@@ -202,7 +286,41 @@ mod tests {
#[test]
fn bmp_pixels_per_metre() {
let mut bmp = Vec::new();
image::RgbImage::new(2, 2).write_to(&mut std::io::Cursor::new(&mut bmp), image::ImageFormat::Bmp).unwrap();
{
let __dyn: image::DynamicImage = (image::RgbImage::new(2, 2)).into();
let (__w, __h) = (__dyn.width(), __dyn.height());
let (__layout, __sample, __raw) = match __dyn {
image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLuma16(b) => (
craft_image_codecs::ChannelLayout::Gray,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageLumaA16(b) => (
craft_image_codecs::ChannelLayout::GrayA,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgb16(b) => (
craft_image_codecs::ChannelLayout::Rgb,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgba16(b) => (
craft_image_codecs::ChannelLayout::Rgba,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()),
};
let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap();
craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Bmp, &craft_image_codecs::EncodeOptions::default())
.map(|__b| bmp.extend_from_slice(&__b))
}
.unwrap();
bmp[38..42].copy_from_slice(&11811u32.to_le_bytes());
bmp[42..46].copy_from_slice(&11811u32.to_le_bytes());
assert!(close(resolution(&bmp).unwrap(), (300.0, 300.0)));
+10 -3
View File
@@ -889,7 +889,6 @@ pub(crate) fn job_for(s: &Session, st: &DocState, plan: SavePlan) -> Result<Save
fn job_for_stamped(s: &Session, st: &DocState, plan: SavePlan, stamped: Option<i64>) -> Result<SaveJob> {
let cmd = plan.mode.command();
super::check_linked_scripts(cmd, plan.format.id, st)?;
let mut own = doc_to_save(st, plan.format);
let mut params = plan.options.clone();
if is_svg(plan.format) {
@@ -934,6 +933,14 @@ fn job_for_stamped(s: &Session, st: &DocState, plan: SavePlan, stamped: Option<i
o.insert("range".into(), json!("all"));
}
}
// A saved `.ai` or `.ait` file has the artboards as its pages, whatever `useArtboards` says.
let checked = match (&params, plan.format.id) {
(Value::Object(o), "ai" | "ait") => {
std::borrow::Cow::Owned(Value::Object(o.iter().filter(|(k, _)| *k != "useArtboards").map(|(k, v)| (k.clone(), v.clone())).collect()))
}
_ => std::borrow::Cow::Borrowed(&params),
};
super::check_linked_scripts(cmd, plan.format.id, st, &checked)?;
Ok(SaveJob { plan, doc, params, snapshot, source: st.doc.clone(), stamped, boards })
}
@@ -1318,7 +1325,7 @@ pub(super) fn specs() -> Vec<CommandSpec> {
"Save Document",
[],
None,
"{path?, format?: vectorcraft|template|pdf|svg|svgz|ai|eps (default: the path's extension, else the document's own format), options?: {…the format's options, see file.formatOptions; default: as last saved}, svg?: {…SVG options} (an SVG save keeps hidden layers, display:none, unless hiddenLayers is false), …the SVG and PDF options given flat instead (an option given flat or in svg and in options with different values is an error), compress?: bool (native, also in options: gzip; default: the useCompression preference; warnings name an option given flat or in options that the file doesn't read: a legacy .ai reads only its own options, and other .ai files don't read outlineText, hiddenObjects, transparentImages or preserveEditing), version?: 4 (3, 2 or 1: for older VectorCraft versions; 1 and 2 are never compressed), preview?: false (embed a PNG of the first artboard, at most 256 px), precision?: 0..9 (native: round path anchors and handles to this many decimal places, a smaller file; colors, transforms and type stay exact; default: exact, and a later save without it writes exactly again), separateArtboards?: false (native and .ai: also save each artboard of `range` to <name>-<artboard>.<ext> beside the file, holding that artboard and the art touching it; the result's files lists every file written), range?: \"1-3, 5\"|\"all\" (default; with separateArtboards), includeLinked?: false (keep linked files' own pixels, not just their previews; they stay linked), embedProfiles?: true (carry the ICC profiles loaded from files that the document is tagged with; opening the file installs them where missing), pdfCompatible?: true (native: also carry a PDF of every artboard; false omits it) | true for .ai (false: blank pages, only the native document; a .ai file's compress, default true, is its compression.compressText), modified?: Unix seconds|null (the File Info modified date, and created date when there is none, a save to a file stamps; default now, recorded in the journal so a replay matches; null: leave the dates)} → {path, format, bytes, warnings, files?: [path…] (the file and its artboards' files), linked?: [path…] (images an SVG links to)}. Save writes one artboard, except a .ai file and EPS (below): a .ai file is a PDF-compatible file of every artboard carrying the native document (preserveEditing always on; PDF options flat or in options), which document.open restores exactly, on the active artboard (the app's, else the one the document opened on; with editingData: false, the first); separateArtboards writes more files, one per artboard. EPS takes the options of document.exportEps: by default one file whose bounding box fits the visible art (the first artboard when no art shows), carrying the whole editable document; useArtboards: true (also when artboard, artboards or range names artboards; file.formatOptions then reports it true) makes the chosen artboard the page, drawn with its background color (without Use Artboards, only the first artboard's page when no art shows has its color), and with two or more chosen the file at the path is the central file of the visible art (again the first artboard when none shows) and each artboard is also written to <name>_<artboard>.eps beside it, holding that artboard; selectedOnly is refused; its PostScript appearance flattens transparency, as EPS requires. Without a path it writes the document's own file in its own format: a document opened from or saved as SVG/PDF/EPS saves as that again (warnings name what the format loses). No path known (never saved, converted from an older version, restored by Data Recovery, or another format) → {dataBase64, format, name, folder?, warnings} and the document stays modified. Under automation read roots, a reply leaves out the document's own file outside them when no path is given (files and linked then name the files by their file names), and a suggested folder outside them; an svg or svgz save (a document whose own format is SVG or SVGZ included) is refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while the file would name a linked image's file outside them (images: link, preserveEditing, or an image whose pixels the document doesn't hold; a URL is not checked), also by file.saveAs and file.saveCopy. A key that no save format takes, beside the path or in options, and an unknown key inside a PDF option's object or svg, are refused. A terminal filesystem permission/read-only refusal returns READ_ONLY_LOCATION: followed by the reason; recovery-copy failures keep their original error. Non-UI callers never open a save panel",
"{path?, format?: vectorcraft|template|pdf|svg|svgz|ai|eps (default: the path's extension, else the document's own format), options?: {…the format's options, see file.formatOptions; default: as last saved}, svg?: {…SVG options} (an SVG save keeps hidden layers, display:none, unless hiddenLayers is false), …the SVG and PDF options given flat instead (an option given flat or in svg and in options with different values is an error), compress?: bool (native, also in options: gzip; default: the useCompression preference; warnings name an option given flat or in options that the file doesn't read: a legacy .ai reads only its own options, and other .ai files don't read outlineText, hiddenObjects, transparentImages or preserveEditing), version?: 4 (3, 2 or 1: for older VectorCraft versions; 1 and 2 are never compressed), preview?: false (embed a PNG of the first artboard, at most 256 px), precision?: 0..9 (native: round path anchors and handles to this many decimal places, a smaller file; colors, transforms and type stay exact; default: exact, and a later save without it writes exactly again), separateArtboards?: false (native and .ai: also save each artboard of `range` to <name>-<artboard>.<ext> beside the file, holding that artboard and the art touching it; the result's files lists every file written), range?: \"1-3, 5\"|\"all\" (default; with separateArtboards), includeLinked?: false (keep linked files' own pixels, not just their previews; they stay linked), embedProfiles?: true (carry the ICC profiles loaded from files that the document is tagged with; opening the file installs them where missing), pdfCompatible?: true (native: also carry a PDF of every artboard; false omits it) | true for .ai (false: blank pages, only the native document; a .ai file's compress, default true, is its compression.compressText), modified?: Unix seconds|null (the File Info modified date, and created date when there is none, a save to a file stamps; default now, recorded in the journal so a replay matches; null: leave the dates)} → {path, format, bytes, warnings, files?: [path…] (the file and its artboards' files), linked?: [path…] (images an SVG links to)}. Save writes one artboard, except a .ai file and EPS (below): a .ai file is a PDF-compatible file of every artboard carrying the native document (preserveEditing always on; PDF options flat or in options), which document.open restores exactly, on the active artboard (the app's, else the one the document opened on; with editingData: false, the first); separateArtboards writes more files, one per artboard. EPS takes the options of document.exportEps: by default one file whose bounding box fits the visible art (the first artboard when no art shows), carrying the whole editable document; useArtboards: true (also when artboard, artboards or range names artboards; file.formatOptions then reports it true) makes the chosen artboard the page, drawn with its background color (without Use Artboards, only the first artboard's page when no art shows has its color), and with two or more chosen the file at the path is the central file of the visible art (again the first artboard when none shows) and each artboard is also written to <name>_<artboard>.eps beside it, holding that artboard; selectedOnly is refused; its PostScript appearance flattens transparency, as EPS requires. Without a path it writes the document's own file in its own format: a document opened from or saved as SVG/PDF/EPS saves as that again (warnings name what the format loses). No path known (never saved, converted from an older version, restored by Data Recovery, or another format) → {dataBase64, format, name, folder?, warnings} and the document stays modified. Under automation read roots, a reply leaves out the document's own file outside them when no path is given (files and linked then name the files by their file names), and a suggested folder outside them; an svg or svgz save (a document whose own format is SVG or SVGZ included), and a save whose file carries the native document (vectorcraft, template, eps, ai but a version 7 file, pdf of every artboard with preserveEditing on and useArtboards not false), is refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while the file would name a linked image's file outside them (images: link, preserveEditing, or an image whose pixels the document doesn't hold; a URL is not checked), also by file.saveAs and file.saveCopy. A key that no save format takes, beside the path or in options, and an unknown key inside a PDF option's object or svg, are refused. A terminal filesystem permission/read-only refusal returns READ_ONLY_LOCATION: followed by the reason; recovery-copy failures keep their original error. Non-UI callers never open a save panel",
has_doc,
|s, p| save(s, SaveMode::Save, p)
),
@@ -1345,7 +1352,7 @@ pub(super) fn specs() -> Vec<CommandSpec> {
"Save as Template…",
["File"],
None,
"{…as document.save} {path? (saved with the format's extension: one naming another format is replaced, and one is added to a name without it), format?: template (default) | ait (also when format is not given and the path ends in .ait), compress?, version?, preview?, precision?} a template that opens as a new untitled document: a native template (.vctemplate), or a PDF-compatible .ait written as a .ai file is (the .ai options and the PDF options, as document.save takes them for .ai; aiVersion 7 is an error); the document is unchanged → {path, format, bytes, warnings}; no path → {dataBase64, format, name: \"<name> template.<ext>\", folder: the Templates folder (preference templatesFolder), warnings}",
"{…as document.save} {path? (saved with the format's extension: one naming another format is replaced, and one is added to a name without it), format?: template (default) | ait (also when format is not given and the path ends in .ait), compress?, version?, preview?, precision?} a template that opens as a new untitled document: a native template (.vctemplate), or a PDF-compatible .ait written as a .ai file is (the .ai options and the PDF options, as document.save takes them for .ai; aiVersion 7 is an error); the document is unchanged → {path, format, bytes, warnings}; no path → {dataBase64, format, name: \"<name> template.<ext>\", folder: the Templates folder (preference templatesFolder), warnings}. Under automation read roots, it is refused, before any file is written, while the document links a JavaScript file outside them, as document.save refuses it",
has_doc,
|s, p| save(s, SaveMode::Template, p)
),
+37 -8
View File
@@ -350,8 +350,8 @@ struct ScreenParams {
/// Where files go: `none` (all in the folder), `rows` (the rows' sub-folders, as
/// `subfolders`), `format` (a folder per extension), `item`, or `itemFormat`.
folders: Option<String>,
/// Export PDFs As: `single` (the artboards a PDF row writes are the pages of one file) or
/// `multiple` (a file per artboard, the default).
/// Export PDFs As: `single` (the artboards a PDF row writes are the pages of one file; refused
/// with assets, layers or `selection: "each"`) or `multiple` (a file per artboard, the default).
pdfs: Option<String>,
}
@@ -399,12 +399,18 @@ impl ScreenParams {
if p.is_object() { Self::deserialize(p).map_err(|e| bad(C, e.to_string())) } else { Ok(Self::default()) }
}
/// An error when more than one of `assets`, `layers`, `selection` and `fullDocument` is given.
/// An error when more than one of `assets`, `layers`, `selection` and `fullDocument` is given,
/// and when `pdfs: "single"` is given with `assets`, `layers` or `selection: "each"`, whose
/// files each hold the art of one item.
fn one_source(&self) -> Result<()> {
let sources = [self.full_document, self.assets.is_some(), self.layers.is_some(), self.selection.is_some()].iter().filter(|b| **b).count();
if sources > 1 {
return Err(bad(C, "give one of assets, layers, selection or fullDocument"));
}
let per_piece = self.assets.is_some() || self.layers.is_some() || self.selection.as_deref() == Some("each");
if per_piece && self.pdfs.as_deref() == Some("single") {
return Err(bad(C, "pdfs `single` writes artboards as the pages of one PDF: assets, layers and selection `each` write a PDF each"));
}
Ok(())
}
@@ -764,7 +770,7 @@ fn leave_out_folder(r: &mut Value, folder: &str) {
/// Export settings kept in the document or a preset, as the request being served may see them: a
/// `folder` outside the read roots ([`super::access::shown`]) is left out.
fn leave_out_unreadable_settings_folder(mut settings: Map<String, Value>) -> Map<String, Value> {
pub(super) fn leave_out_unreadable_settings_folder(mut settings: Map<String, Value>) -> Map<String, Value> {
if settings.get("folder").and_then(Value::as_str).is_some_and(|f| !f.is_empty() && !super::access::shown(f)) {
settings.remove("folder");
}
@@ -1089,6 +1095,29 @@ pub(crate) fn with_export_preset(s: &Session, cmd: &str, settings: &mut Map<Stri
Ok(())
}
/// Does the file of `item` that row `r` writes carry the native document, and with it the
/// JavaScript files the document links ([`super::access::names_linked_scripts`])? A PDF holds the
/// artboards it is written with: those of `single` (Export PDFs As › Single file), every artboard
/// (Full Document), else the item's artboard of its document.
fn names_scripts(item: &Item, r: &Row, single: Option<&[usize]>) -> bool {
if r.format.id != "pdf" {
return super::access::names_linked_scripts(C, r.format.id, &r.options, item.doc.artboards.len());
}
let (doc, options) = match (single, &item.every_artboard) {
(Some(boards), _) => {
let mut options = r.options.clone();
options["range"] = json!(boards.iter().map(|b| (b + 1).to_string()).collect::<Vec<_>>().join(", "));
(&item.doc, options)
}
(None, Some(all)) => (all, r.options.clone()),
(None, None) => match r.options_for(item.region, item.artboard) {
Ok(options) => (&item.doc, options),
Err(_) => return true,
},
};
super::access::names_linked_scripts(C, "pdf", &options, doc.artboards.len())
}
/// Every chosen artboard (asset, layer, selected object) in every format row, one file each (a PDF
/// holds its artboard alone), or with `fullDocument` one file per row (a PDF of every artboard,
/// else the bounds of all art). Items that share a name get `-2`, `-3`… instead of overwriting, and
@@ -1105,10 +1134,6 @@ pub(crate) fn export(s: &mut Session, p: &Value, asked: &Value) -> Result<Value>
o.one_source()?;
// `<filename>`: the document's file, as Save names it, or its title before it is saved.
let st = s.doc()?;
// Before the folder is made or any row is written.
for r in &rows {
super::check_linked_scripts(C, r.format.id, st)?;
}
let naming = Naming::of(&o, st.path.as_deref().unwrap_or(&st.doc.title))?;
let selection = o.selection_mode()?;
let selected = if selection.is_some() { selected_artwork(s)? } else { vec![] };
@@ -1125,6 +1150,10 @@ pub(crate) fn export(s: &mut Session, p: &Value, asked: &Value) -> Result<Value>
};
let crop = rows.iter().any(|r| r.format.id != "pdf");
let items = items(&doc, &o, selection, &selected, &naming.filename, crop, true)?;
// Before the folder is made or any row is written, with the artboards each file holds.
let single: Option<Vec<usize>> = items.iter().map(|i| i.artboard).collect::<Option<Vec<_>>>().filter(|a| naming.single_pdf && a.len() > 1);
let st = s.doc()?;
super::check_scripts_of(C, &st.doc, st.path.as_deref(), || rows.iter().any(|r| items.iter().any(|i| names_scripts(i, r, single.as_deref()))))?;
// The file each item writes for each SVG row, before the folder is made or any row is written.
let base = crate::cmd::links::LinkBase::of(s.doc()?);
for r in rows.iter().filter(|r| matches!(r.format.id, "svg" | "svgz")) {
+13 -1
View File
@@ -180,12 +180,24 @@ pub(super) fn lost_artboards_warning(doc: &Document, p: &Value, label: &str) ->
})
}
/// The native document Preserve Editing embeds: `doc`, without an Export for Screens `folder`
/// outside the read roots of the request being served (the open document keeps it).
fn native_attachment(doc: &Document) -> Vec<u8> {
let settings = super::screens::leave_out_unreadable_settings_folder(doc.export_settings.clone());
if settings.len() == doc.export_settings.len() {
return vectorcraft_format::save(doc, false);
}
let mut kept = doc.clone();
kept.export_settings = settings;
vectorcraft_format::save(&kept, false)
}
/// Encode `doc` as SVG (or gzipped, SVGZ): one file per chosen artboard, with the images they
/// link to and the writer's warnings.
pub(super) fn encode(doc: &Document, p: &Value, compressed: bool) -> Result<Encoded, String> {
let (opts, boards, chosen) = plan(doc, p)?;
// Preserve editing embeds the native document (once, shared by every file).
let native = opts.preserve_editing.then(|| vectorcraft_format::save(doc, false));
let native = opts.preserve_editing.then(|| native_attachment(doc));
// Draw linked files as vectors when available, or their previews with a warning. Keep
// that preparation out of the native attachment so missing links remain relinkable.
let (full, warnings) = crate::cmd::place::document::full_documents(doc);
+35 -2
View File
@@ -4,12 +4,45 @@
use super::*;
use proptest::prelude::*;
use serde_json::json;
use std::io::Cursor;
fn png() -> Vec<u8> {
let im = image::RgbaImage::from_fn(2, 1, |x, _| if x == 0 { image::Rgba([220, 40, 60, 255]) } else { image::Rgba([0, 0, 0, 0]) });
let mut bytes = Vec::new();
im.write_to(&mut Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap();
{
let __dyn: image::DynamicImage = im.into();
let (__w, __h) = (__dyn.width(), __dyn.height());
let (__layout, __sample, __raw) = match __dyn {
image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLuma16(b) => (
craft_image_codecs::ChannelLayout::Gray,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageLumaA16(b) => (
craft_image_codecs::ChannelLayout::GrayA,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgb16(b) => (
craft_image_codecs::ChannelLayout::Rgb,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgba16(b) => (
craft_image_codecs::ChannelLayout::Rgba,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()),
};
let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap();
craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default())
.map(|__b| bytes.extend_from_slice(&__b))
}
.unwrap();
bytes
}
+39 -2
View File
@@ -571,7 +571,24 @@ fn a_one_bit_rgb_image_opens_from_the_editing_data_in_its_colors() {
assert_eq!(names(&doc.layers), ["Art"], "{r}");
let mut found = vec![];
doc.visit_images(|_, im| {
let img = image::load_from_memory(&doc.images[&im.key].bytes).unwrap().to_rgb8();
let img = craft_image_codecs::decode(&doc.images[&im.key].bytes)
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap()
.to_rgb8();
found.push(img.pixels().map(|p| p.0).collect::<Vec<_>>());
});
assert_eq!(found, [[[255, 0, 0], [0, 255, 0], [0, 0, 255]]], "{r}");
@@ -589,7 +606,27 @@ fn a_zero_width_stroke_in_the_editing_data_draws_a_hairline() {
assert_eq!(names(&s.doc().unwrap().doc.layers), ["Art"], "{r}");
let v = s.execute("document.export", &json!({"format": "png", "background": "transparent"})).unwrap();
let png = vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).unwrap();
image::load_from_memory(&png).unwrap().to_rgba8().pixels().filter(|p| p.0[3] > 0).count()
craft_image_codecs::decode(&png)
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap()
.to_rgba8()
.pixels()
.filter(|p| p.0[3] > 0)
.count()
};
assert!(drawn("0 1 1 0 1 0 0 XA\n0 w\n20 20 m\n180 80 L\nS\n") > 0, "the hairline draws");
assert_eq!(drawn("0 1 1 0 1 0 0 XA\n0 w\n20 20 m\n180 80 L\nN\n"), 0, "the unstroked path draws nothing");
@@ -32,7 +32,24 @@ fn with(mut p: Value, more: &Value) -> Value {
/// The pixels of the PNG `document.export` writes of the active document with `p`, on transparency.
fn png(s: &mut Session, p: Value) -> image::RgbaImage {
let v = s.execute("document.export", &with(json!({"format": "png", "background": "transparent"}), &p)).unwrap();
image::load_from_memory(&b64(&v)).unwrap().to_rgba8()
craft_image_codecs::decode(&b64(&v))
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap()
.to_rgba8()
}
/// The file `document.export` writes with `p`.
@@ -61,7 +78,26 @@ fn raster_exports_paint_the_color_behind_the_art() {
assert_eq!(png(&mut s, json!({"artboard": 0, "includeArtboardFill": false})).get_pixel(2, 2)[3], 0, "left out");
assert_eq!(png(&mut s, json!({"artboard": 1})).get_pixel(2, 2)[3], 0, "an artboard without a color");
let jpg = file(&mut s, json!({"format": "jpg", "artboard": 0, "quality": 100}));
let px = image::load_from_memory(&jpg).unwrap().to_rgb8().get_pixel(2, 2).0;
let px = craft_image_codecs::decode(&jpg)
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap()
.to_rgb8()
.get_pixel(2, 2)
.0;
assert!(px[0] > 240 && px[1] < 16 && px[2] < 16, "JPEG too: {px:?}");
for bad in [json!("no"), json!(1)] {
assert!(s.execute("document.export", &json!({"format": "png", "includeArtboardFill": bad})).is_err(), "{bad}");
@@ -163,7 +199,28 @@ fn export_for_screens_includes_the_fill_unless_unchecked() {
let p = with(json!({"artboards": [0], "formats": [{"format": "png"}], "settings": {"png": {"background": "transparent"}}}), &more);
s.execute("document.exportForScreens", &p).unwrap()
};
let corner = |r: &Value| image::load_from_memory(&b64(&r["files"][0])).unwrap().to_rgba8().get_pixel(2, 2).0;
let corner = |r: &Value| {
craft_image_codecs::decode(&b64(&r["files"][0]))
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap()
.to_rgba8()
.get_pixel(2, 2)
.0
};
assert_eq!(corner(&screens(&mut s, json!({}))), RED, "on by default");
assert_eq!(corner(&screens(&mut s, json!({"includeArtboardFill": false})))[3], 0, "unchecked");
assert_eq!(s.execute("document.exportSettings", &json!({})).unwrap()["settings"]["includeArtboardFill"], false, "remembered");
+53 -3
View File
@@ -50,7 +50,23 @@ fn eps_covers_the_art_y_up_from_the_first_artboard_with_a_preview_and_the_docume
let bytes = b64(&r);
// The default TIFF preview sits behind the binary header.
let (_, tiff) = vectorcraft_eps::sections(&bytes).unwrap();
let preview = image::load_from_memory_with_format(tiff.unwrap(), image::ImageFormat::Tiff).unwrap();
let preview = craft_image_codecs::decode_as(craft_image_codecs::Format::Tiff, tiff.unwrap())
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap();
assert_eq!((preview.width(), preview.height()), (100, 40));
let ps = postscript(&bytes);
assert_eq!(dsc(&ps, "BoundingBox").as_deref(), Some("50 100 150 140"), "60..100 down is 100..140 up");
@@ -221,13 +237,47 @@ fn placed_images_are_written_and_previews_are_black_and_white_on_request() {
/// The PNG thumbnail of an EPS file, decoded.
fn thumbnail_png(bytes: &[u8]) -> image::RgbaImage {
let png = vectorcraft_eps::thumbnail(bytes).expect("a thumbnail");
image::load_from_memory_with_format(&png, image::ImageFormat::Png).unwrap().to_rgba8()
craft_image_codecs::decode_as(craft_image_codecs::Format::Png, &png)
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap()
.to_rgba8()
}
/// The TIFF preview of an EPS file, decoded.
fn preview_tiff(bytes: &[u8]) -> image::RgbaImage {
let tiff = vectorcraft_eps::sections(bytes).unwrap().1.expect("a preview");
image::load_from_memory_with_format(tiff, image::ImageFormat::Tiff).unwrap().to_rgba8()
craft_image_codecs::decode_as(craft_image_codecs::Format::Tiff, tiff)
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap()
.to_rgba8()
}
/// The size of a thumbnail render of the rect an EPS file's preview shows (its bounding box).
@@ -115,7 +115,25 @@ fn tiff_predicted_4_bit_images_open_from_eps_and_postscript_ai_files() {
let mut grays = vec![];
d.walk(|n| {
if let vectorcraft_doc::NodeKind::Image(im) = &n.kind {
grays = image::load_from_memory(&d.images[&im.key].bytes).unwrap().to_luma8().into_raw();
grays = craft_image_codecs::decode(&d.images[&im.key].bytes)
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap()
.to_luma8()
.into_raw();
}
});
assert_eq!(grays, [0, 5, 15, 3, 9, 9, 2, 0].map(|v| v * 17), "{name}");
+18 -1
View File
@@ -16,7 +16,24 @@ fn b64(v: &Value) -> Vec<u8> {
}
fn rgba(bytes: &[u8]) -> image::RgbaImage {
image::load_from_memory(bytes).unwrap().to_rgba8()
craft_image_codecs::decode(bytes)
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap()
.to_rgba8()
}
fn tmp_dir(tag: &str) -> std::path::PathBuf {
+69 -3
View File
@@ -12,7 +12,27 @@ const COLORS: [[u8; 4]; 4] = [[255, 0, 0, 255], [0, 255, 0, 255], [0, 0, 255, 25
fn pixels(bytes: &[u8]) -> Vec<[u8; 4]> {
let raster = load::raster_image(bytes).unwrap();
image::load_from_memory(&raster.blob.bytes).unwrap().to_rgba8().pixels().map(|p| p.0).collect()
craft_image_codecs::decode(&raster.blob.bytes)
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap()
.to_rgba8()
.pixels()
.map(|p| p.0)
.collect()
}
fn boxed(ty: &[u8; 4], data: &[u8]) -> Vec<u8> {
@@ -54,12 +74,58 @@ fn checker_opens_and_places_with_exact_pixels() {
assert_eq!(opened["format"], "jpeg2000");
assert_eq!(s.doc().unwrap().doc.artboards[0].rect.size(), vectorcraft_geom::Size::new(2.0, 2.0));
let blob = s.doc().unwrap().doc.images.values().next().unwrap();
assert_eq!(image::load_from_memory(&blob.bytes).unwrap().to_rgba8().pixels().map(|p| p.0).collect::<Vec<_>>(), COLORS);
assert_eq!(
craft_image_codecs::decode(&blob.bytes)
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap()
.to_rgba8()
.pixels()
.map(|p| p.0)
.collect::<Vec<_>>(),
COLORS
);
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
let placed = s.execute("file.place", &json!({"name": name, "dataBase64": encoded})).unwrap();
assert_eq!(placed["format"], "jpeg2000");
let blob = s.doc().unwrap().doc.images.values().next().unwrap();
assert_eq!(image::load_from_memory(&blob.bytes).unwrap().to_rgba8().pixels().map(|p| p.0).collect::<Vec<_>>(), COLORS);
assert_eq!(
craft_image_codecs::decode(&blob.bytes)
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap()
.to_rgba8()
.pixels()
.map(|p| p.0)
.collect::<Vec<_>>(),
COLORS
);
assert!(load::texture_image(bytes).is_ok());
}
}
+57 -3
View File
@@ -33,14 +33,48 @@ fn png8_and_gif_export_palettes() {
let png8 = b64(&s.execute("document.export", &json!({"format": "png8", "colors": 16})).unwrap());
assert_eq!(png8[25], 3, "colour type 3");
assert!(plte_len(&png8) <= 16);
let img = image::load_from_memory(&png8).unwrap().to_rgba8();
let img = craft_image_codecs::decode(&png8)
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap()
.to_rgba8();
assert_eq!(img.dimensions(), (40, 30));
assert_eq!(img.get_pixel(5, 15).0, [255, 0, 0, 255]);
assert_eq!(img.get_pixel(39, 0)[3], 0, "transparent where there is no art");
let gif = b64(&s.execute("document.export", &json!({"format": "gif", "background": "white", "dither": "none"})).unwrap());
assert_eq!(&gif[..6], b"GIF89a");
let img = image::load_from_memory_with_format(&gif, image::ImageFormat::Gif).unwrap().to_rgba8();
let img = craft_image_codecs::decode_as(craft_image_codecs::Format::Gif, &gif)
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap()
.to_rgba8();
assert_eq!(img.get_pixel(5, 15).0, [255, 0, 0, 255]);
assert_eq!(img.get_pixel(39, 0).0, [255, 255, 255, 255], "the white background");
@@ -68,5 +102,25 @@ fn palette_formats_reach_export_as_and_screens() {
let names: Vec<&str> = r["files"].as_array().unwrap().iter().map(|f| f["name"].as_str().unwrap()).collect();
assert_eq!(names, ["Artboard-1@2x.gif", "Artboard-1.png"]);
let gif = vectorcraft_format::base64_decode(r["files"][0]["dataBase64"].as_str().unwrap()).unwrap();
assert_eq!(image::load_from_memory(&gif).unwrap().width(), 80);
assert_eq!(
craft_image_codecs::decode(&gif)
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap()
.width(),
80
);
}
+21 -1
View File
@@ -49,7 +49,27 @@ fn rle(raw: &[u8]) -> Vec<u8> {
/// The pixels `raster_image` stores for `f`, row by row.
fn pixels(f: &[u8]) -> Vec<[u8; 4]> {
let img = raster_image(f).unwrap();
image::load_from_memory(&img.blob.bytes).unwrap().to_rgba8().pixels().map(|p| p.0).collect()
craft_image_codecs::decode(&img.blob.bytes)
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap()
.to_rgba8()
.pixels()
.map(|p| p.0)
.collect()
}
/// The 16 colors of a header palette: entry `i` is (16 i, 255 − 16 i, i).
+35 -1
View File
@@ -375,7 +375,41 @@ fn a_16_bit_png_is_written_at_8_bits_before_pdf_1_5() {
let mut s = session(1);
let deep = image::ImageBuffer::from_fn(8, 8, |x, y| image::Rgb([x as u16 * 8000, y as u16 * 8000, 40000]));
let mut png = vec![];
image::DynamicImage::ImageRgb16(deep).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
{
let __dyn: image::DynamicImage = image::DynamicImage::ImageRgb16(deep);
let (__w, __h) = (__dyn.width(), __dyn.height());
let (__layout, __sample, __raw) = match __dyn {
image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLuma16(b) => (
craft_image_codecs::ChannelLayout::Gray,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageLumaA16(b) => (
craft_image_codecs::ChannelLayout::GrayA,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgb16(b) => (
craft_image_codecs::ChannelLayout::Rgb,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgba16(b) => (
craft_image_codecs::ChannelLayout::Rgba,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()),
};
let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap();
craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default())
.map(|__b| png.extend_from_slice(&__b))
}
.unwrap();
s.execute("file.place", &json!({"name": "deep.png", "dataBase64": vectorcraft_format::base64_encode(&png), "at": [50, 40]})).unwrap();
let readable = json!({"compressText": false});
for (cmd, p, depth) in [
+35 -3
View File
@@ -26,9 +26,41 @@ fn session() -> Session {
run(&mut s, "paint.setFill", json!({"color": "#e0c020"}));
run(&mut s, "effect.apply", json!({"effect": "stylize.dropShadow", "ids": [shadowed]}));
let mut png = vec![];
image::RgbaImage::from_fn(8, 8, |x, _| image::Rgba([0, 120, 255, if x < 4 { 0 } else { 255 }]))
.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
.unwrap();
{
let __dyn: image::DynamicImage = (image::RgbaImage::from_fn(8, 8, |x, _| image::Rgba([0, 120, 255, if x < 4 { 0 } else { 255 }]))).into();
let (__w, __h) = (__dyn.width(), __dyn.height());
let (__layout, __sample, __raw) = match __dyn {
image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLuma16(b) => (
craft_image_codecs::ChannelLayout::Gray,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageLumaA16(b) => (
craft_image_codecs::ChannelLayout::GrayA,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgb16(b) => (
craft_image_codecs::ChannelLayout::Rgb,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgba16(b) => (
craft_image_codecs::ChannelLayout::Rgba,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()),
};
let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap();
craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default())
.map(|__b| png.extend_from_slice(&__b))
}
.unwrap();
run(&mut s, "file.place", json!({"name": "dots.png", "dataBase64": vectorcraft_format::base64_encode(&png), "at": [150, 120]}));
s
}
+57 -2
View File
@@ -807,7 +807,28 @@ fn image_outline(doc: &vectorcraft_doc::Document) -> Vec<String> {
((p.x * 100.0).round() / 100.0, (p.y * 100.0).round() / 100.0)
});
let link = im.link.as_ref().map(|l| (l.path.clone(), l.relative.clone()));
let pixels = doc.image_blob(im).and_then(|b| image::load_from_memory(&b.bytes).ok()).map(|i| i.to_rgba8().into_raw());
let pixels = doc
.image_blob(im)
.and_then(|b| {
craft_image_codecs::decode(&b.bytes)
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.ok()
})
.map(|i| i.to_rgba8().into_raw());
out.push(format!("{}x{} {corners:?} {link:?} {pixels:?}", im.width, im.height));
}
});
@@ -825,7 +846,41 @@ fn images_come_back_from_the_editing_copy() {
std::fs::create_dir_all(format!("{dir}/art")).unwrap();
let png = |w: u32, h: u32, f: &dyn Fn(u32, u32) -> [u8; 4]| {
let mut out = vec![];
image::RgbaImage::from_fn(w, h, |x, y| image::Rgba(f(x, y))).write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap();
{
let __dyn: image::DynamicImage = (image::RgbaImage::from_fn(w, h, |x, y| image::Rgba(f(x, y)))).into();
let (__w, __h) = (__dyn.width(), __dyn.height());
let (__layout, __sample, __raw) = match __dyn {
image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLuma16(b) => (
craft_image_codecs::ChannelLayout::Gray,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageLumaA16(b) => (
craft_image_codecs::ChannelLayout::GrayA,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgb16(b) => (
craft_image_codecs::ChannelLayout::Rgb,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgba16(b) => (
craft_image_codecs::ChannelLayout::Rgba,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()),
};
let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap();
craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default())
.map(|__b| out.extend_from_slice(&__b))
}
.unwrap();
out
};
let linked = format!("{dir}/art/linked.png");
@@ -97,7 +97,23 @@ fn pdf_info_lists_pages_boxes_and_a_thumbnail() {
assert_eq!(p2["boxes"]["trim"], json!([15.0, 15.0, 185.0, 385.0]));
assert_eq!(p2["boxes"]["media"], json!([0.0, 0.0, 200.0, 400.0]));
let png = vectorcraft_format::base64_decode(v["thumbnail"].as_str().unwrap()).unwrap();
let img = image::load_from_memory(&png).unwrap();
let img = craft_image_codecs::decode(&png)
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap();
assert_eq!((img.width(), img.height()), (50, 100), "the art box at 100 px on its longest side");
assert!(s.execute("document.pdfInfo", &json!({"dataBase64": b64(&bytes), "thumbnail": 4})).is_err());
// Locked: no pages until the password is given.
@@ -214,7 +230,27 @@ fn pdf_info_refuses_a_thumbnail_size_that_is_not_a_number() {
assert!(e.contains("`colorMode` must be a string"), "{e}");
let v = s.execute("document.pdfInfo", &json!({"dataBase64": b64(&bytes), "thumbnail": 1, "thumbnailSize": null})).unwrap();
let png = vectorcraft_format::base64_decode(v["thumbnail"].as_str().unwrap()).unwrap();
assert_eq!(image::load_from_memory(&png).unwrap().width(), 160);
assert_eq!(
craft_image_codecs::decode(&png)
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap()
.width(),
160
);
}
#[test]
@@ -284,7 +320,23 @@ fn pdf_info_reads_postscript_as_one_page() {
] {
let v = s.execute("document.pdfInfo", &json!({"dataBase64": b64(bytes), "thumbnail": 1, "thumbnailSize": 100})).unwrap();
let png = vectorcraft_format::base64_decode(v["thumbnail"].as_str().unwrap()).unwrap();
let img = image::load_from_memory(&png).unwrap();
let img = craft_image_codecs::decode(&png)
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap();
assert_eq!(img.width().max(img.height()), 100, "{name}");
let mut v = v;
v["thumbnail"] = json!("png");
@@ -314,7 +366,23 @@ fn pdf_info_refuses_a_thumbnail_that_is_not_a_page_number() {
}
let v = s.execute("document.pdfInfo", &json!({"dataBase64": b64(bytes), "thumbnail": 1, "thumbnailSize": 64})).unwrap();
let png = vectorcraft_format::base64_decode(v["thumbnail"].as_str().unwrap()).unwrap();
let img = image::load_from_memory(&png).unwrap();
let img = craft_image_codecs::decode(&png)
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap();
assert_eq!(img.width().max(img.height()), 64, "{pages}");
}
}
+144 -13
View File
@@ -17,9 +17,41 @@ fn session() -> Session {
s.execute("paint.setFill", &json!({"color": {"model": "rgb", "r": 1.0, "g": 0.2, "b": 0.0}})).unwrap();
s.execute("transparency.set", &json!({"opacity": 50})).unwrap();
let mut png = vec![];
image::RgbaImage::from_fn(8, 8, |x, _| image::Rgba([0, 120, 255, if x < 4 { 0 } else { 255 }]))
.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
.unwrap();
{
let __dyn: image::DynamicImage = (image::RgbaImage::from_fn(8, 8, |x, _| image::Rgba([0, 120, 255, if x < 4 { 0 } else { 255 }]))).into();
let (__w, __h) = (__dyn.width(), __dyn.height());
let (__layout, __sample, __raw) = match __dyn {
image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLuma16(b) => (
craft_image_codecs::ChannelLayout::Gray,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageLumaA16(b) => (
craft_image_codecs::ChannelLayout::GrayA,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgb16(b) => (
craft_image_codecs::ChannelLayout::Rgb,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgba16(b) => (
craft_image_codecs::ChannelLayout::Rgba,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()),
};
let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap();
craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default())
.map(|__b| png.extend_from_slice(&__b))
}
.unwrap();
s.execute("file.place", &json!({"name": "dots.png", "dataBase64": vectorcraft_format::base64_encode(&png), "at": [150, 50]})).unwrap();
s
}
@@ -175,9 +207,41 @@ fn pdfx_1a_flattening_keeps_the_inks_behind_an_image_in_a_cmyk_document() {
s.execute("paint.setFill", &json!({"color": {"c": teal[0], "m": teal[1], "y": teal[2], "k": teal[3]}})).unwrap();
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
let mut png = vec![];
image::RgbaImage::from_fn(40, 40, |x, _| image::Rgba([0, 120, 255, if x < 20 { 0 } else { 255 }]))
.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
.unwrap();
{
let __dyn: image::DynamicImage = (image::RgbaImage::from_fn(40, 40, |x, _| image::Rgba([0, 120, 255, if x < 20 { 0 } else { 255 }]))).into();
let (__w, __h) = (__dyn.width(), __dyn.height());
let (__layout, __sample, __raw) = match __dyn {
image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLuma16(b) => (
craft_image_codecs::ChannelLayout::Gray,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageLumaA16(b) => (
craft_image_codecs::ChannelLayout::GrayA,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgb16(b) => (
craft_image_codecs::ChannelLayout::Rgb,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgba16(b) => (
craft_image_codecs::ChannelLayout::Rgba,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()),
};
let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap();
craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default())
.map(|__b| png.extend_from_slice(&__b))
}
.unwrap();
s.execute("file.place", &json!({"name": "logos.png", "dataBase64": vectorcraft_format::base64_encode(&png), "at": [100, 50]})).unwrap();
let v = s.execute("document.exportPdf", &json!({"standard": "pdfX1a"})).unwrap();
let bytes = vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).unwrap();
@@ -228,10 +292,45 @@ fn cropped_by(mode: &str, width: f64, art: Art, layer: bool) -> (Session, u64) {
let art = match art {
Art::Image { see_through } => {
let mut png = vec![];
image::RgbaImage::from_fn(240, 160, |x, y| {
image::Rgba([200, (x % 256) as u8, (y % 256) as u8, if see_through && x < 60 { 128 } else { 255 }])
})
.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
{
let __dyn: image::DynamicImage = (image::RgbaImage::from_fn(240, 160, |x, y| {
image::Rgba([200, (x % 256) as u8, (y % 256) as u8, if see_through && x < 60 { 128 } else { 255 }])
}))
.into();
let (__w, __h) = (__dyn.width(), __dyn.height());
let (__layout, __sample, __raw) = match __dyn {
image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLumaA8(b) => {
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw())
}
image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLuma16(b) => (
craft_image_codecs::ChannelLayout::Gray,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageLumaA16(b) => (
craft_image_codecs::ChannelLayout::GrayA,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgb16(b) => (
craft_image_codecs::ChannelLayout::Rgb,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgba16(b) => (
craft_image_codecs::ChannelLayout::Rgba,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()),
};
let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap();
craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default())
.map(|__b| png.extend_from_slice(&__b))
}
.unwrap();
let placed =
run(&mut s, "file.place", json!({"name": "photo.png", "dataBase64": vectorcraft_format::base64_encode(&png), "rect": FRAME}));
@@ -486,9 +585,41 @@ fn flat_pdf_files_of_art_that_no_clip_group_hides_are_unchanged() {
run(&mut fitted, "shape.rectangle", json!({"x": 180, "y": 90, "width": 160, "height": 160}));
run(&mut fitted, "paint.setFill", json!({"color": "#203040"}));
let mut png = vec![];
image::RgbaImage::from_fn(240, 160, |x, y| image::Rgba([200, x as u8, y as u8, 255]))
.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
.unwrap();
{
let __dyn: image::DynamicImage = (image::RgbaImage::from_fn(240, 160, |x, y| image::Rgba([200, x as u8, y as u8, 255]))).into();
let (__w, __h) = (__dyn.width(), __dyn.height());
let (__layout, __sample, __raw) = match __dyn {
image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLuma16(b) => (
craft_image_codecs::ChannelLayout::Gray,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageLumaA16(b) => (
craft_image_codecs::ChannelLayout::GrayA,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgb16(b) => (
craft_image_codecs::ChannelLayout::Rgb,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgba16(b) => (
craft_image_codecs::ChannelLayout::Rgba,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()),
};
let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap();
craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default())
.map(|__b| png.extend_from_slice(&__b))
}
.unwrap();
let photo =
run(&mut fitted, "file.place", json!({"name": "photo.png", "dataBase64": vectorcraft_format::base64_encode(&png), "rect": FRAME}))["ids"][0]
.clone();
@@ -274,7 +274,24 @@ fn image_of(s: &Session, l: &Node) -> ((f64, f64), image::RgbaImage) {
fn pixels_of(s: &Session, c: &Node) -> ((f64, f64), image::RgbaImage) {
let NodeKind::Image(img) = &c.kind else { panic!("{} isn't an image", name(c)) };
let blob = &s.doc().unwrap().doc.images[&img.key];
let px = image::load_from_memory(&blob.bytes).unwrap().to_rgba8();
let px = craft_image_codecs::decode(&blob.bytes)
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap()
.to_rgba8();
assert_eq!((px.width(), px.height()), (img.width, img.height));
let o = img.xf * kurbo::Point::ZERO;
((o.x, o.y), px)
+18 -1
View File
@@ -215,7 +215,24 @@ fn exported(s: &mut Session, p: Value) -> Vec<u8> {
#[test]
fn psd_exports_open_and_place_again() {
let mut s = art();
let png = image::load_from_memory(&exported(&mut s, json!({"format": "png"}))).unwrap().to_rgba8();
let png = craft_image_codecs::decode(&exported(&mut s, json!({"format": "png"})))
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap()
.to_rgba8();
for (options, what) in [(json!({}), "layered RGB"), (json!({"layers": false}), "flat RGB"), (json!({"colorModel": "gray"}), "grey")] {
let f = exported(&mut s, merge(json!({"format": "psd"}), options));
let back = decode(&f, 1 << 30, naive).unwrap();
@@ -511,3 +511,75 @@ fn damaged_slices_never_panic() {
}
}
}
/// The PSD file `document.export` writes from `s`, with its layers or flat.
fn export(s: &mut Session, layers: bool) -> Vec<u8> {
let r = s.execute("document.export", &json!({"format": "psd", "layers": layers})).unwrap();
vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap()
}
#[test]
fn an_opened_files_slices_survive_a_psd_export() {
let link =
S { url: "https://example.com/", target: "_blank", message: "Go", alt: "Logo", argb: [255, 0x12, 0x34, 0x56], ..user("logo", [2, 4, 10, 8]) };
let plain = S { kind: 0, cell: "a < b & c", ..user("note", [10, 10, 20, 20]) };
let html = S { kind: 0, html: true, cell: "<b>Hi</b>", argb: [0, 1, 2, 3], ..user("", [0, 12, 6, 18]) };
let auto = S { origin: 0, ..user("auto", [0, 0, 20, 2]) };
let f = with_resource(&psd(true), 1050, &v6(&[link, plain, html, auto], &[]));
let (mut s, _) = open(&f, json!({}));
let opened = slices(&s);
assert_eq!(opened.len(), 3);
for layers in [true, false] {
let out = export(&mut s, layers);
let (again, r) = open(&out, json!({}));
assert!(warnings(&r).is_empty(), "{r}");
// The same rectangles and options; the auto slices are laid out again around them.
let mut got = slices(&again);
let mut want = opened.clone();
let order = |v: &mut Vec<(Rect, SliceOptions)>| v.sort_by(|a, b| a.0.y0.total_cmp(&b.0.y0).then(a.0.x0.total_cmp(&b.0.x0)));
order(&mut got);
order(&mut want);
assert_eq!(got, want);
let layout = again.doc().unwrap().doc.slice_layout();
assert!(layout.iter().any(|a| a.source == vectorcraft_doc::SliceSource::Auto));
assert_eq!(s.execute("document.psdInfo", &json!({"dataBase64": b64(&out)})).unwrap()["slices"], json!(3));
}
}
#[test]
fn object_slices_are_written_as_user_slices_and_html_text_as_its_type() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap();
let r = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 40, "height": 30})).unwrap();
let rect = r["id"].as_u64().unwrap();
s.execute("object.slice.make", &json!({"ids": [rect]})).unwrap();
s.execute("select.set", &json!({"ids": [rect]})).unwrap();
s.execute("object.slice.options", &json!({"kind": "noImage", "name": "box", "text": "<i>x</i>", "background": "#00ff00"})).unwrap();
let t = s.execute("text.create", &json!({"x": 100, "y": 50, "text": "A & B"})).unwrap()["id"].as_u64().unwrap();
s.execute("object.slice.make", &json!({"ids": [t]})).unwrap();
s.execute("select.set", &json!({"ids": [t]})).unwrap();
s.execute("object.slice.options", &json!({"kind": "htmlText"})).unwrap();
let (again, _) = open(&export(&mut s, false), json!({}));
let got = slices(&again);
assert_eq!(got.len(), 2, "{got:?}");
let doc = &s.doc().unwrap().doc;
let rb = doc.slice_bounds(vectorcraft_doc::NodeId(rect)).unwrap();
let boxed = got.iter().find(|g| g.1.name == "box").unwrap();
// Within a pixel of the object's bounds.
for (a, b) in [(boxed.0.x0, rb.x0), (boxed.0.y0, rb.y0), (boxed.0.x1, rb.x1), (boxed.0.y1, rb.y1)] {
assert!((a - b).abs() <= 1.0, "{:?} against {rb:?}", boxed.0);
}
assert_eq!((boxed.1.kind, boxed.1.text.as_str(), boxed.1.background.as_str()), (SliceKind::NoImage, "<i>x</i>", "#00ff00"));
let text = got.iter().find(|g| g.1.name.is_empty()).unwrap();
assert_eq!((text.1.kind, text.1.text.as_str()), (SliceKind::NoImage, "A &amp; B"));
}
#[test]
fn twenty_exported_slices_open_again_with_the_one_whose_id_is_16() {
let columns: Vec<S> = (0..20).map(|x| user("", [x, 0, x + 1, 20])).collect();
let (mut s, _) = open(&with_resource(&psd(false), 1050, &v6(&columns, &[])), json!({}));
assert_eq!(slices(&s).len(), 20);
let (again, r) = open(&export(&mut s, true), json!({}));
assert!(warnings(&r).is_empty(), "{r}");
assert_eq!(slices(&again), slices(&s));
}
+74 -3
View File
@@ -72,7 +72,27 @@ fn wide(samples: &[u16]) -> Vec<u8> {
/// The pixels `raster_image` stores for `f`, row by row.
fn pixels(f: &[u8]) -> Vec<[u8; 4]> {
let img = raster_image(f).unwrap();
image::load_from_memory(&img.blob.bytes).unwrap().to_rgba8().pixels().map(|p| p.0).collect()
craft_image_codecs::decode(&img.blob.bytes)
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap()
.to_rgba8()
.pixels()
.map(|p| p.0)
.collect()
}
const RGBA: u16 = 15;
@@ -241,13 +261,64 @@ fn pxr_files_open_place_and_paste() {
let node = doc.node(vectorcraft_doc::NodeId(r["ids"][0].as_u64().unwrap())).unwrap();
let vectorcraft_doc::NodeKind::Image(im) = &node.kind else { panic!("link {link}: an image, got {:?}", node.kind) };
assert_eq!((im.link.is_some(), im.width, im.height), (link, 2, 1), "link {link}");
let shown = image::load_from_memory(&doc.images[&im.key].bytes).unwrap().to_rgba8();
let shown = craft_image_codecs::decode(&doc.images[&im.key].bytes)
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap()
.to_rgba8();
assert_eq!(shown.pixels().map(|p| p.0).collect::<Vec<_>>(), pixels(&f), "link {link}");
}
let _ = std::fs::remove_dir_all(&dir);
// Open sizes it as a PNG of 2 × 1 pixels without a resolution.
let mut png = vec![];
image::RgbaImage::new(2, 1).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
{
let __dyn: image::DynamicImage = (image::RgbaImage::new(2, 1)).into();
let (__w, __h) = (__dyn.width(), __dyn.height());
let (__layout, __sample, __raw) = match __dyn {
image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()),
image::DynamicImage::ImageLuma16(b) => (
craft_image_codecs::ChannelLayout::Gray,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageLumaA16(b) => (
craft_image_codecs::ChannelLayout::GrayA,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgb16(b) => (
craft_image_codecs::ChannelLayout::Rgb,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
image::DynamicImage::ImageRgba16(b) => (
craft_image_codecs::ChannelLayout::Rgba,
craft_image_codecs::SampleType::U16,
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
),
other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()),
};
let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap();
craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default())
.map(|__b| png.extend_from_slice(&__b))
}
.unwrap();
let mut t = Session::new();
t.execute("document.open", &json!({"name": "same.png", "dataBase64": b64(&png)})).unwrap();
assert_eq!(t.doc().unwrap().doc.artboards[0].rect.size(), size);
+70 -1
View File
@@ -16,7 +16,24 @@ fn b64(v: &Value) -> Vec<u8> {
}
fn rgba(bytes: &[u8]) -> image::RgbaImage {
image::load_from_memory(bytes).unwrap().to_rgba8()
craft_image_codecs::decode(bytes)
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap()
.to_rgba8()
}
/// A chunk's data by type (first match) in a PNG file.
@@ -427,3 +444,55 @@ fn export_for_screens_rows_keep_their_own_size() {
.unwrap();
assert_eq!(rgba(&b64(&r["files"][0])).dimensions(), (512, 256), "{r}");
}
/// File › Open's raster path reads images through craft-image-codecs (#778) as it read them with
/// the image crate: each format the image crate decoded for it (BMP, TGA, TIFF at 8 and 16 bits,
/// gray and color, with and without alpha; a PNG, JPEG, GIF and WebP stored as they are) gives
/// the same size, sample depth and pixels.
#[test]
fn opened_rasters_are_the_pixels_the_image_crate_read() {
use image::{DynamicImage as D, ImageFormat as F};
let rgba = image::RgbaImage::from_fn(11, 6, |x, y| image::Rgba([(x * 23) as u8, (y * 41) as u8, ((x ^ y) * 13) as u8, 255 - (x * y * 3) as u8]));
let deep = image::ImageBuffer::<image::Rgba<u16>, _>::from_fn(11, 6, |x, y| {
image::Rgba([(x * 5_003) as u16, (y * 9_011) as u16, 77, 65_535 - (x * y) as u16])
});
let images = [
D::ImageRgba8(rgba.clone()),
D::ImageRgb8(D::ImageRgba8(rgba.clone()).to_rgb8()),
D::ImageLuma8(D::ImageRgba8(rgba.clone()).to_luma8()),
D::ImageLumaA8(D::ImageRgba8(rgba).to_luma_alpha8()),
D::ImageRgba16(deep.clone()),
D::ImageRgb16(D::ImageRgba16(deep.clone()).to_rgb16()),
D::ImageLuma16(D::ImageRgba16(deep).to_luma16()),
];
let mut checked = 0;
for img in &images {
for f in [F::Bmp, F::Tga, F::Tiff, F::Png, F::Jpeg, F::Gif, F::WebP] {
let mut bytes = Vec::new();
if img.write_to(&mut std::io::Cursor::new(&mut bytes), f).is_err() {
continue;
}
let what = format!("{f:?} {:?}", img.color());
let mut want = image::load_from_memory_with_format(&bytes, f).unwrap();
let opened = super::load::raster_image(&bytes).unwrap_or_else(|e| panic!("{what}: {e}"));
assert_eq!((opened.width, opened.height), (want.width(), want.height()), "{what}");
if opened.blob.mime != "image/png" {
// Stored as they are: the file's own bytes.
assert_eq!(opened.blob.bytes.as_slice(), bytes.as_slice(), "{what}");
checked += 1;
continue;
}
if f == F::Tga {
let mut px = want.to_rgba8();
super::tgaread::fix_alpha(&bytes, &mut px);
want = D::ImageRgba8(px);
}
let got = image::load_from_memory_with_format(&opened.blob.bytes, F::Png).unwrap();
let deep_samples = |c: image::ColorType| c.bytes_per_pixel() > c.channel_count();
assert_eq!(deep_samples(got.color()), deep_samples(want.color()), "{what}: {:?} {:?}", got.color(), want.color());
assert_eq!(got.to_rgba16().as_raw(), want.to_rgba16().as_raw(), "{what}");
checked += 1;
}
}
assert!(checked >= 25, "{checked}");
}
+120 -4
View File
@@ -34,7 +34,25 @@ fn names(r: &Value) -> Vec<String> {
}
fn size(png: &[u8]) -> (u32, u32) {
image::load_from_memory(png).unwrap().to_rgba8().dimensions()
craft_image_codecs::decode(png)
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap()
.to_rgba8()
.dimensions()
}
#[test]
@@ -413,7 +431,28 @@ fn rich_black_reaches_the_files() {
s.execute("paint.setFill", &json!({"color": {"c": 0, "m": 0, "y": 0, "k": 1}})).unwrap();
s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 40, "height": 30})).unwrap();
let p = json!({"formats": [{"format": "png"}]});
let px = |r: &Value| image::load_from_memory(&files(r)[0].1).unwrap().to_rgba8().get_pixel(10, 10).0;
let px = |r: &Value| {
craft_image_codecs::decode(&files(r)[0].1)
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap()
.to_rgba8()
.get_pixel(10, 10)
.0
};
let accurate = px(&export(&mut s, p.clone()));
assert!(accurate[0] > 10, "accurate: dark grey, {accurate:?}");
s.execute("prefs.set", &json!({"key": "blackOutput", "value": "rich"})).unwrap();
@@ -589,7 +628,28 @@ fn png_8_rows_write_indexed_colour() {
#[test]
fn a_second_file_with_a_taken_name_is_numbered() {
let mut s = session(1);
let px = |png: &[u8]| image::load_from_memory(png).unwrap().to_rgba8().get_pixel(1, 1).0;
let px = |png: &[u8]| {
craft_image_codecs::decode(png)
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap()
.to_rgba8()
.get_pixel(1, 1)
.0
};
let rows = json!([{"format": "png", "background": "black"}, {"format": "png", "background": "white"}, {"format": "png", "background": "black"}]);
let r = export(&mut s, json!({ "formats": rows }));
assert_eq!(names(&r), ["Artboard-1.png", "Artboard-1-2.png"]);
@@ -873,7 +933,28 @@ fn kept_settings_leave_out_a_folder_outside_the_read_root() {
#[test]
fn format_settings_apply_to_their_rows_and_rows_win() {
let mut s = session(1);
let px = |png: &[u8]| image::load_from_memory(png).unwrap().to_rgba8().get_pixel(1, 1).0;
let px = |png: &[u8]| {
craft_image_codecs::decode(png)
.map(|__cimg| {
let (__w, __h) = __cimg.dimensions();
match (__cimg.layout(), __cimg.sample_type()) {
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
}
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
}
})
.unwrap()
.to_rgba8()
.get_pixel(1, 1)
.0
};
let r = export(
&mut s,
json!({"settings": {"png": {"background": "black", "scale": 9, "artboard": 7}, "jpg": {"quality": 5}}, "formats": [{"format": "png"}, {"format": "png", "suffix": "-w", "background": "white"}, {"format": "jpg"}, {"format": "jpg", "quality": 100, "suffix": "-100"}]}),
@@ -1164,6 +1245,41 @@ fn single_file_pdfs_hold_every_chosen_artboard() {
assert!(s.execute("document.exportForScreens", &json!({"pdfs": "both", "formats": [{"format": "pdf"}]})).is_err());
}
/// Export PDFs As › Single file holds artboards: with assets, layers or a file per selected object,
/// whose files each hold one item's art, it is refused (the Example line too) instead of writing
/// the first item alone under the document's name; Multiple files writes a PDF of each item. The
/// selection as one file is one PDF either way.
#[test]
fn single_file_pdfs_are_refused_for_assets_layers_and_each_object() {
let mut s = session(1);
s.execute("layer.new", &json!({"name": "Second"})).unwrap();
s.execute("shape.ellipse", &json!({"x": 30, "y": 5, "width": 8, "height": 8})).unwrap();
let doc = s.doc().unwrap().doc.clone();
let layers: Vec<u64> = doc.layers.iter().map(|l| l.id.0).collect();
let art: Vec<u64> = doc.layers.iter().filter_map(|l| l.children()).flatten().map(|c| c.id.0).collect();
assert_eq!((layers.len(), art.len()), (2, 2));
let a = s.execute("assets.add", &json!({"ids": [art[0]], "name": "Square"})).unwrap()["assets"][0].as_u64().unwrap();
let b = s.execute("assets.add", &json!({"ids": [art[1]], "name": "Dot"})).unwrap()["assets"][0].as_u64().unwrap();
s.execute("select.all", &json!({})).unwrap();
let pdf = json!([{"format": "pdf"}]);
for source in [json!({"assets": [a, b]}), json!({"layers": layers}), json!({"selection": "each"})] {
let mut p = source.clone();
p["formats"] = pdf.clone();
p["pdfs"] = json!("multiple");
let r = export(&mut s, p.clone());
assert_eq!(names(&r).len(), 2, "a PDF each: {:?} ({source})", names(&r));
for (name, bytes) in files(&r) {
assert_eq!(vectorcraft_pdf::import(&bytes).unwrap().artboards.len(), 1, "{name}");
}
p["pdfs"] = json!("single");
let e = s.execute("document.exportForScreens", &p).unwrap_err().to_string();
assert!(e.contains("pdfs `single`"), "{e} ({source})");
assert!(super::screens::first_file(&s, &p).is_err(), "{source}");
}
let r = export(&mut s, json!({"selection": "one", "pdfs": "single", "formats": pdf}));
assert_eq!(names(&r), ["Selection.pdf"]);
}
/// The warnings of reply `r` that name an option the file doesn't read.
fn unused(r: &Value) -> Vec<String> {
r["warnings"].as_array().unwrap().iter().filter_map(Value::as_str).filter(|w| w.contains("was not used")).map(str::to_string).collect()

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